Updates regarding moving to source.pztrn.name and dependencies bundling with golang/dep.

This commit is contained in:
2018-02-02 09:17:40 +05:00
parent e969b7018d
commit 14a19622bc
723 changed files with 251025 additions and 488 deletions

View File

@@ -0,0 +1 @@
*DS_Store*

View File

@@ -0,0 +1,8 @@
stages:
- test
test_job:
stage: test
tags:
- linux1
script: go test -test.v .

View File

@@ -0,0 +1,57 @@
[![GoDoc](https://godoc.org/lab.pztrn.name/golibs/flagger?status.svg)](https://godoc.org/lab.pztrn.name/golibs/flagger)
# Flagger
Flagger is an arbitrary CLI flags parser, like argparse in Python.
Flagger is able to parse boolean, integer and string flags.
# Installation
```
go get -u -v lab.pztrn.name/golibs/flagger
```
# Usage
Flagger requires logging interface to be passed on initialization.
See ``loggerinterface.go`` for required logging functions.
It is able to run with standart log package, in that case
initialize flagger like:
```
flgr = flagger.New(flagger.LoggerInterface(log.New(os.Stdout, "testing logger: ", log.Lshortfile)))
flgr.Initialize()
```
Adding a flag is easy, just fill ``Flag`` structure and pass to ``AddFlag()`` call:
```
flag_bool := Flag{
Name: "boolflag",
Description: "Boolean flag",
Type: "bool",
DefaultValue: true,
}
err := flgr.AddFlag(&flag_bool)
if err != nil {
...
}
```
After adding all neccessary flags you should issue ``Parse()`` call to get
them parsed:
```
flgr.Parse()
```
After parsed they can be obtained everywhere you want, like:
```
val, err := flgr.GetBoolValue("boolflag")
if err != nil {
...
}
```
For more examples take a look at ``flagger_test.go`` file or [at GoDoc](https://godoc.org/lab.pztrn.name/golibs/flagger).

View File

@@ -0,0 +1,29 @@
// Flagger - arbitrary CLI flags parser.
//
// Copyright (c) 2017, Stanislav N. aka pztrn.
// All rights reserved.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package flagger
var (
logger LoggerInterface
)
func New(l LoggerInterface) *Flagger {
logger = l
f := Flagger{}
return &f
}

View File

@@ -0,0 +1,31 @@
// Flagger - arbitrary CLI flags parser.
//
// Copyright (c) 2017, Stanislav N. aka pztrn.
// All rights reserved.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package flagger
// This structure represents addable flag for Flagger.
type Flag struct {
// Flag name. It will be accessible using this name later.
Name string
// Description for help output.
Description string
// Type can be one of "bool", "int", "string".
Type string
// This value will be reflected.
DefaultValue interface{}
}

View File

@@ -0,0 +1,121 @@
// Flagger - arbitrary CLI flags parser.
//
// Copyright (c) 2017, Stanislav N. aka pztrn.
// All rights reserved.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package flagger
import (
// stdlib
"errors"
"flag"
"sync"
)
// Flagger implements (kinda) extended CLI parameters parser. As it
// available from CommonContext, these flags will be available to
// whole application.
//
// It uses reflection to determine what kind of variable we should
// parse or get.
type Flagger struct {
// Flags that was added by user.
flags map[string]*Flag
flagsMutex sync.Mutex
// Flags that will be passed to flag module.
flagsBool map[string]*bool
flagsInt map[string]*int
flagsString map[string]*string
}
// Adds flag to list of flags we will pass to ``flag`` package.
func (f *Flagger) AddFlag(flag *Flag) error {
_, present := f.flags[flag.Name]
if present {
logger.Fatalln("Cannot add flag '" + flag.Name + "' - already added!")
return errors.New("Cannot add flag '" + flag.Name + "' - already added!")
}
f.flags[flag.Name] = flag
return nil
}
// This function returns boolean value for flag with given name.
// Returns bool value for flag and nil as error on success
// and false bool plus error with text on error.
func (f *Flagger) GetBoolValue(name string) (bool, error) {
fl, present := f.flagsBool[name]
if !present {
return false, errors.New("No such flag: " + name)
}
return (*fl), nil
}
// This function returns integer value for flag with given name.
// Returns integer on success and 0 on error.
func (f *Flagger) GetIntValue(name string) (int, error) {
fl, present := f.flagsInt[name]
if !present {
return 0, errors.New("No such flag: " + name)
}
return (*fl), nil
}
// This function returns string value for flag with given name.
// Returns string on success or empty string on error.
func (f *Flagger) GetStringValue(name string) (string, error) {
fl, present := f.flagsString[name]
if !present {
return "", errors.New("No such flag: " + name)
}
return (*fl), nil
}
// Flagger initialization.
func (f *Flagger) Initialize() {
logger.Println("Initializing CLI parameters parser...")
f.flags = make(map[string]*Flag)
f.flagsBool = make(map[string]*bool)
f.flagsInt = make(map[string]*int)
f.flagsString = make(map[string]*string)
}
// This function adds flags from flags map to flag package and parse
// them. They can be obtained later by calling GetTYPEValue(name),
// where TYPE is one of Bool, Int, String.
func (f *Flagger) Parse() {
for name, fl := range f.flags {
if fl.Type == "bool" {
fdef := fl.DefaultValue.(bool)
f.flagsBool[name] = &fdef
flag.BoolVar(&fdef, name, fdef, fl.Description)
} else if fl.Type == "int" {
fdef := fl.DefaultValue.(int)
f.flagsInt[name] = &fdef
flag.IntVar(&fdef, name, fdef, fl.Description)
} else if fl.Type == "string" {
fdef := fl.DefaultValue.(string)
f.flagsString[name] = &fdef
flag.StringVar(&fdef, name, fdef, fl.Description)
}
}
logger.Println("Parsing CLI parameters...")
flag.Parse()
}

View File

@@ -0,0 +1,125 @@
// Flagger - arbitrary CLI flags parser.
//
// Copyright (c) 2017, Stanislav N. aka pztrn.
// All rights reserved.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package flagger
import (
// stdlib
"log"
"os"
"testing"
)
var (
f *Flagger
)
func TestFlaggerInitialization(t *testing.T) {
f = New(LoggerInterface(log.New(os.Stdout, "testing logger: ", log.Lshortfile)))
if f == nil {
t.Fatal("Logger initialization failed!")
t.FailNow()
}
f.Initialize()
}
func TestFlaggerAddBoolFlag(t *testing.T) {
flag_testbool := Flag{
Name: "testboolflag",
Description: "Testing boolean flag",
Type: "bool",
DefaultValue: true,
}
err := f.AddFlag(&flag_testbool)
if err != nil {
t.Fatal("Failed to add boolean flag!")
t.FailNow()
}
}
func TestFlaggerAddIntFlag(t *testing.T) {
flag_testint := Flag{
Name: "testintflag",
Description: "Testing integer flag",
Type: "int",
DefaultValue: 1,
}
err := f.AddFlag(&flag_testint)
if err != nil {
t.Fatal("Failed to add integer flag!")
t.FailNow()
}
}
func TestFlaggerAddStringFlag(t *testing.T) {
flag_teststring := Flag{
Name: "teststringflag",
Description: "Testing string flag",
Type: "string",
DefaultValue: "superstring",
}
err := f.AddFlag(&flag_teststring)
if err != nil {
t.Fatal("Failed to add string flag!")
t.FailNow()
}
}
// This test doing nothing more but launching flags parsing.
func TestFlaggerParse(t *testing.T) {
f.Parse()
}
func TestFlaggerGetBoolFlag(t *testing.T) {
val, err := f.GetBoolValue("testboolflag")
if err != nil {
t.Fatal("Failed to get boolean flag: " + err.Error())
t.FailNow()
}
if !val {
t.Fatal("Failed to get boolean flag - should be true, but false received")
t.FailNow()
}
}
func TestFlaggerGetIntFlag(t *testing.T) {
val, err := f.GetIntValue("testintflag")
if err != nil {
t.Fatal("Failed to get integer flag: " + err.Error())
t.FailNow()
}
if val == 0 {
t.Fatal("Failed to get integer flag - should be 1, but 0 received")
t.FailNow()
}
}
func TestFlaggerGetStringFlag(t *testing.T) {
val, err := f.GetStringValue("teststringflag")
if err != nil {
t.Fatal("Failed to get string flag: " + err.Error())
t.FailNow()
}
if val == "" {
t.Fatal("Failed to get string flag - should be 'superstring', but nothing received")
t.FailNow()
}
}

View File

@@ -0,0 +1,26 @@
// Flagger - arbitrary CLI flags parser.
//
// Copyright (c) 2017, Stanislav N. aka pztrn.
// All rights reserved.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package flagger
// LoggerInterface provide logging interface, so everyone can inject own
// logging handlers.
type LoggerInterface interface {
Fatalln(args ...interface{})
Println(v ...interface{})
}

View File

@@ -0,0 +1 @@
*DS_Store*

30
vendor/source.pztrn.name/golibs/mogrus/Gopkg.lock generated vendored Normal file
View File

@@ -0,0 +1,30 @@
# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'.
[[projects]]
name = "github.com/sirupsen/logrus"
packages = ["."]
revision = "d682213848ed68c0a260ca37d6dd5ace8423f5ba"
version = "v1.0.4"
[[projects]]
branch = "master"
name = "golang.org/x/crypto"
packages = ["ssh/terminal"]
revision = "3d37316aaa6bd9929127ac9a527abf408178ea7b"
[[projects]]
branch = "master"
name = "golang.org/x/sys"
packages = [
"unix",
"windows"
]
revision = "03467258950d845cd1877eab69461b98e8c09219"
[solve-meta]
analyzer-name = "dep"
analyzer-version = 1
inputs-digest = "97f3cd8b7a00b2b98fe58f834cf0d2f2c840a89809d15b451fdde156324ba6b1"
solver-name = "gps-cdcl"
solver-version = 1

View File

@@ -0,0 +1,25 @@
# Gopkg.toml example
#
# Refer to https://github.com/golang/dep/blob/master/docs/Gopkg.toml.md
# for detailed Gopkg.toml documentation.
#
# required = ["github.com/user/thing/cmd/thing"]
# ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"]
#
# [[constraint]]
# name = "github.com/user/project"
# version = "1.0.0"
#
# [[constraint]]
# name = "github.com/user/project2"
# branch = "dev"
# source = "github.com/myfork/project2"
#
# [[override]]
# name = "github.com/x/y"
# version = "2.4.0"
[[constraint]]
name = "github.com/sirupsen/logrus"
version = "1.0.4"

View File

@@ -0,0 +1,46 @@
# Mogrus
Logger thing built on top of github.com/sirupsen/logrus with ability to
create multiple loggers (e.g. console and file loggers) for one logger
instance.
The reason to create this handler was a need of logging things to both
console and, e.g., file, which is unsupported by logrus itself (you have
to create several loggers for each output).
## Example
```
package main
import (
// stdlib
"os"
// tools
"bitbucket.org/pztrn/mogrus"
)
func main() {
l := mogrus.New()
l.Initialize()
log := l.CreateLogger("helloworld")
log.CreateOutput("stdout", os.Stdout, true)
// File output.
file_output, err := os.Create("/tmp/hellorowld.log")
if err != nil {
log.Errorln("Failed to create file output:", err.Error())
}
log.CreateOutput("file /tmp/hellorowld.log", file_output, false)
log.Println("Starting log experiment tool...")
log.Debugln("Debug here!")
log.Infoln("This is INFO level")
log.Println("This is also INFO level.")
log.Warnln("This is WARN.")
log.Errorln("This is ERROR level.")
log.Fatalln("We will exit here.")
}
```

View File

@@ -0,0 +1,24 @@
package mogrus
// Mogrus is a logger package built on top of Logrus with extended
// (and kinda simplified) approach for multilogging.
//
// Example usage:
//
// TBF
//
// Output functions are splitted in three things:
// * ``Debug`` - simple debug printing
// * ``Debugf`` - debug printing with line formatting
// * ``Debugln`` - debug printing, same as Debug().
//
// It will try to resemble Logrus as much as possible.
//
// About functions.
//
// Info(f,ln) and Print(f,ln) doing same thing - logging to
// INFO log level.
//
// Be careful while using Fatal(f,ln) functions, because
// it will log only to first logger and then will os.Exit(1)!
// There is no guarantee what logger will be first ATM.

View File

@@ -0,0 +1,5 @@
package mogrus
func New() *MogrusLogger {
return &MogrusLogger{}
}

View File

@@ -0,0 +1,249 @@
package mogrus
import (
// stdlib
"io"
"strings"
"sync"
// github
"github.com/sirupsen/logrus"
)
type LoggerHandler struct {
// Logrus instances
instances map[string]*logrus.Logger
instancesMutex sync.Mutex
}
// Adds output for logger handler.
// This actually creates new Logrus's Logger instance and configure
// it to write to given writer.
// To configure debug level you should pass it's name as debugLvl.
// Valid values: "", "debug" (the default), "info", "warn", "error"
func (lh *LoggerHandler) CreateOutput(name string, writer io.Writer, colors bool, debugLvl string) {
// Formatter.
logrus_formatter := new(logrus.TextFormatter)
logrus_formatter.DisableTimestamp = false
logrus_formatter.FullTimestamp = true
logrus_formatter.QuoteEmptyFields = true
logrus_formatter.TimestampFormat = "2006-01-02 15:04:05.000000000"
if colors {
logrus_formatter.DisableColors = false
logrus_formatter.ForceColors = true
} else {
logrus_formatter.DisableColors = true
logrus_formatter.ForceColors = false
}
logrus_instance := logrus.New()
logrus_instance.Out = writer
// Defaulting to debug.
logrus_instance.Level = logrus.DebugLevel
if debugLvl == "info" {
logrus_instance.Level = logrus.InfoLevel
} else if debugLvl == "warn" {
logrus_instance.Level = logrus.WarnLevel
} else if debugLvl == "error" {
logrus_instance.Level = logrus.ErrorLevel
}
logrus_instance.Formatter = logrus_formatter
lh.instancesMutex.Lock()
lh.instances[name] = logrus_instance
for _, logger := range lh.instances {
logger.Debugln("Added new logger output:", name)
}
lh.instancesMutex.Unlock()
}
// Formats string by replacing "{{ var }}"'s with data from passed map.
func (lh *LoggerHandler) FormatString(data string, replacers map[string]string) string {
for k, v := range replacers {
data = strings.Replace(data, "{{ "+k+" }}", v, -1)
}
return data
}
// Initializes logger handler.
// It will only initializes LoggerHandler structure, see CreateOutput()
// for configuring output for this logger handler.
func (lh *LoggerHandler) Initialize() {
lh.instances = make(map[string]*logrus.Logger)
}
// Removes previously created output.
// If output isn't found - doing nothing.
func (lh *LoggerHandler) RemoveOutput(output_name string) {
lh.instancesMutex.Lock()
_, found := lh.instances[output_name]
if found {
delete(lh.instances, output_name)
}
lh.instancesMutex.Unlock()
}
// Proxy for Logrus's Logger.Debug() function.
func (lh *LoggerHandler) Debug(args ...interface{}) {
lh.instancesMutex.Lock()
for _, logger := range lh.instances {
logger.Debug(args...)
}
lh.instancesMutex.Unlock()
}
// Proxy for Logrus's Logger.Debugf() function.
func (lh *LoggerHandler) Debugf(format string, args ...interface{}) {
lh.instancesMutex.Lock()
for _, logger := range lh.instances {
logger.Debugf(format, args...)
}
lh.instancesMutex.Unlock()
}
// Proxy for Logrus's Logger.Debugln() function.
func (lh *LoggerHandler) Debugln(args ...interface{}) {
lh.instancesMutex.Lock()
for _, logger := range lh.instances {
logger.Debugln(args...)
}
lh.instancesMutex.Unlock()
}
// Proxy for Logrus's Logger.Error() function.
func (lh *LoggerHandler) Error(args ...interface{}) {
lh.instancesMutex.Lock()
for _, logger := range lh.instances {
logger.Error(args...)
}
lh.instancesMutex.Unlock()
}
// Proxy for Logrus's Logger.Errorf() function.
func (lh *LoggerHandler) Errorf(format string, args ...interface{}) {
lh.instancesMutex.Lock()
for _, logger := range lh.instances {
logger.Errorf(format, args...)
}
lh.instancesMutex.Unlock()
}
// Proxy for Logrus's Logger.Errorln() function.
func (lh *LoggerHandler) Errorln(args ...interface{}) {
lh.instancesMutex.Lock()
for _, logger := range lh.instances {
logger.Errorln(args...)
}
lh.instancesMutex.Unlock()
}
// Proxy for Logrus's Logger.Fatal() function.
func (lh *LoggerHandler) Fatal(args ...interface{}) {
lh.instancesMutex.Lock()
for _, logger := range lh.instances {
logger.Fatal(args...)
}
lh.instancesMutex.Unlock()
}
// Proxy for Logrus's Logger.Fatalf() function.
func (lh *LoggerHandler) Fatalf(format string, args ...interface{}) {
lh.instancesMutex.Lock()
for _, logger := range lh.instances {
logger.Fatalf(format, args...)
}
lh.instancesMutex.Unlock()
}
// Proxy for Logrus's Logger.Fatalln() function.
func (lh *LoggerHandler) Fatalln(args ...interface{}) {
lh.instancesMutex.Lock()
for _, logger := range lh.instances {
logger.Fatalln(args...)
}
lh.instancesMutex.Unlock()
}
// Proxy for Logrus's Logger.Info() function.
func (lh *LoggerHandler) Info(args ...interface{}) {
lh.instancesMutex.Lock()
for _, logger := range lh.instances {
logger.Info(args...)
}
lh.instancesMutex.Unlock()
}
// Proxy for Logrus's Logger.Infof() function.
func (lh *LoggerHandler) Infof(format string, args ...interface{}) {
lh.instancesMutex.Lock()
for _, logger := range lh.instances {
logger.Infof(format, args...)
}
lh.instancesMutex.Unlock()
}
// Proxy for Logrus's Logger.Infoln() function.
func (lh *LoggerHandler) Infoln(args ...interface{}) {
lh.instancesMutex.Lock()
for _, logger := range lh.instances {
logger.Infoln(args...)
}
lh.instancesMutex.Unlock()
}
// Proxy for Logrus's Logger.Print() function.
func (lh *LoggerHandler) Print(args ...interface{}) {
lh.instancesMutex.Lock()
for _, logger := range lh.instances {
logger.Print(args...)
}
lh.instancesMutex.Unlock()
}
// Proxy for Logrus's Logger.Printf() function.
func (lh *LoggerHandler) Printf(format string, args ...interface{}) {
lh.instancesMutex.Lock()
for _, logger := range lh.instances {
logger.Printf(format, args...)
}
lh.instancesMutex.Unlock()
}
// Proxy for Logrus's Logger.Println() function.
func (lh *LoggerHandler) Println(args ...interface{}) {
lh.instancesMutex.Lock()
for _, logger := range lh.instances {
logger.Println(args...)
}
lh.instancesMutex.Unlock()
}
// Proxy for Logrus's Logger.Warn() function.
func (lh *LoggerHandler) Warn(args ...interface{}) {
lh.instancesMutex.Lock()
for _, logger := range lh.instances {
logger.Warn(args...)
}
lh.instancesMutex.Unlock()
}
// Proxy for Logrus's Logger.Warnf() function.
func (lh *LoggerHandler) Warnf(format string, args ...interface{}) {
lh.instancesMutex.Lock()
for _, logger := range lh.instances {
logger.Warnf(format, args...)
}
lh.instancesMutex.Unlock()
}
// Proxy for Logrus's Logger.Warnln() function.
func (lh *LoggerHandler) Warnln(args ...interface{}) {
lh.instancesMutex.Lock()
for _, logger := range lh.instances {
logger.Warnln(args...)
}
lh.instancesMutex.Unlock()
}

View File

@@ -0,0 +1,23 @@
package mogrus
type MogrusLogger struct {
// Initialized loggers.
// Key is a name of logger.
loggers map[string]*LoggerHandler
}
// Creates new logger handler, adds it to list of known loggers and
// return it to caller.
// Note that logger handler will be "just initialized", to actually
// use it you should add output with LoggerHandler.CreateOutput().
func (ml *MogrusLogger) CreateLogger(name string) *LoggerHandler {
lh := &LoggerHandler{}
lh.Initialize()
ml.loggers[name] = lh
return lh
}
func (ml *MogrusLogger) Initialize() {
ml.loggers = make(map[string]*LoggerHandler)
}