From 913ca9672d45b0ce5702126c94b579478e160eab Mon Sep 17 00:00:00 2001 From: andrey1s Date: Tue, 27 Apr 2021 14:58:19 +0300 Subject: [PATCH] first commit --- .drone.yml | 26 + .gitignore | 17 + .golangci.yml | 46 ++ LICENSE | 19 + README.md | 5 + client.go | 96 +++ client_example_test.go | 198 ++++++ docker-compose.yml | 17 + error.go | 8 + go.mod | 15 + go.sum | 317 +++++++++ key.go | 15 + key/helpers.go | 32 + key/helpers_test.go | 64 ++ key/key.go | 46 ++ provider.go | 19 + provider/arg/provider.go | 136 ++++ provider/arg/provider_test.go | 48 ++ provider/env/provider.go | 61 ++ provider/env/provider_test.go | 24 + provider/etcd/provider.go | 113 ++++ provider/etcd/provider_test.go | 119 ++++ provider/ini/provider.go | 62 ++ provider/ini/provider_test.go | 28 + provider/json/provider.go | 66 ++ provider/json/provider_test.go | 27 + provider/toml/provider.go | 71 ++ provider/toml/provider_test.go | 29 + provider/toml/value.go | 41 ++ provider/vault/secret.go | 90 +++ provider/vault/secret_test.go | 26 + provider/watcher/provider.go | 71 ++ provider/watcher/provider_test.go | 58 ++ provider/yaml/file.go | 57 ++ provider/yaml/provider.go | 88 +++ provider/yaml/provider_test.go | 26 + test/etcd.go | 46 ++ test/fixture/config.ini | 1038 +++++++++++++++++++++++++++++ test/fixture/config.json | 16 + test/fixture/config.toml | 31 + test/fixture/config.yaml | 12 + test/helpers.go | 17 + test/ini.go | 16 + test/json.go | 15 + test/provider_suite.go | 150 +++++ test/vault.go | 89 +++ value.go | 39 ++ value/decode.go | 109 +++ value/empty.go | 85 +++ value/helpers.go | 81 +++ value/jbytes.go | 112 ++++ value/jstring.go | 112 ++++ value/jstring_test.go | 37 + value/value.go | 158 +++++ variable.go | 11 + 55 files changed, 4355 insertions(+) create mode 100644 .drone.yml create mode 100644 .gitignore create mode 100644 .golangci.yml create mode 100644 LICENSE create mode 100644 README.md create mode 100644 client.go create mode 100644 client_example_test.go create mode 100644 docker-compose.yml create mode 100644 error.go create mode 100644 go.mod create mode 100644 go.sum create mode 100644 key.go create mode 100644 key/helpers.go create mode 100644 key/helpers_test.go create mode 100644 key/key.go create mode 100644 provider.go create mode 100644 provider/arg/provider.go create mode 100644 provider/arg/provider_test.go create mode 100644 provider/env/provider.go create mode 100644 provider/env/provider_test.go create mode 100644 provider/etcd/provider.go create mode 100644 provider/etcd/provider_test.go create mode 100644 provider/ini/provider.go create mode 100644 provider/ini/provider_test.go create mode 100644 provider/json/provider.go create mode 100644 provider/json/provider_test.go create mode 100644 provider/toml/provider.go create mode 100644 provider/toml/provider_test.go create mode 100644 provider/toml/value.go create mode 100644 provider/vault/secret.go create mode 100644 provider/vault/secret_test.go create mode 100644 provider/watcher/provider.go create mode 100644 provider/watcher/provider_test.go create mode 100644 provider/yaml/file.go create mode 100644 provider/yaml/provider.go create mode 100644 provider/yaml/provider_test.go create mode 100644 test/etcd.go create mode 100644 test/fixture/config.ini create mode 100644 test/fixture/config.json create mode 100644 test/fixture/config.toml create mode 100644 test/fixture/config.yaml create mode 100644 test/helpers.go create mode 100644 test/ini.go create mode 100644 test/json.go create mode 100644 test/provider_suite.go create mode 100644 test/vault.go create mode 100644 value.go create mode 100644 value/decode.go create mode 100644 value/empty.go create mode 100644 value/helpers.go create mode 100644 value/jbytes.go create mode 100644 value/jstring.go create mode 100644 value/jstring_test.go create mode 100644 value/value.go create mode 100644 variable.go diff --git a/.drone.yml b/.drone.yml new file mode 100644 index 0000000..be50dba --- /dev/null +++ b/.drone.yml @@ -0,0 +1,26 @@ +kind: pipeline +name: default + +services: + - name: vault + image: vault + environment: + VAULT_DEV_ROOT_TOKEN_ID: dev + - name: etcd + image: bitnami/etcd + +environment: + VAULT_DEV_LISTEN_ADDRESS: vault:8200 + VAULT_DEV_ROOT_TOKEN_ID: dev + FDEVS_CONFIG_ETCD_HOST: etcd:2379 + +steps: +- name: test + image: golang + commands: + - go test -parallel 10 -race ./... + +- name: golangci-lint + image: golangci/golangci-lint:v1.39 + commands: + - golangci-lint run diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f4d432a --- /dev/null +++ b/.gitignore @@ -0,0 +1,17 @@ +# ---> Go +# Binaries for programs and plugins +*.exe +*.exe~ +*.dll +*.so +*.dylib + +# Test binary, built with `go test -c` +*.test + +# Output of the go coverage tool, specifically when used with LiteIDE +*.out + +# Dependency directories (remove the comment below to include it) +# vendor/ + diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 0000000..23e5557 --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,46 @@ +run: + timeout: 5m + +linters-settings: + dupl: + threshold: 100 + funlen: + lines: 100 + statements: 50 + goconst: + min-len: 2 + min-occurrences: 2 + gocyclo: + min-complexity: 15 + golint: + min-confidence: 0 + govet: + check-shadowing: true + lll: + line-length: 140 + maligned: + suggest-new: true + misspell: + locale: US + +linters: + enable-all: true + disable: + - exhaustivestruct + - maligned + - interfacer + - scopelint + +issues: + # Excluding configuration per-path, per-linter, per-text and per-source + exclude-rules: + - path: _test\.go + linters: + - gomnd + - exhaustivestruct + - wrapcheck + - path: test/* + linters: + - gomnd + - exhaustivestruct + - wrapcheck diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f03940c --- /dev/null +++ b/LICENSE @@ -0,0 +1,19 @@ +MIT License Copyright (c) 2020 4devs + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice (including the next +paragraph) shall be included in all copies or substantial portions of the +Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS +OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF +OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..0fd4d85 --- /dev/null +++ b/README.md @@ -0,0 +1,5 @@ +# config + +[![Build Status](https://drone.gitoa.ru/api/badges/go-4devs/cache/status.svg)](https://drone.gitoa.ru/go-4devs/config) +[![Go Report Card](https://goreportcard.com/badge/gitoa.ru/go-4devs/config)](https://goreportcard.com/report/gitoa.ru/go-4devs/config) +[![GoDoc](https://godoc.org/gitoa.ru/go-4devs/config?status.svg)](http://godoc.org/gitoa.ru/go-4devs/config) diff --git a/client.go b/client.go new file mode 100644 index 0000000..d7df3ef --- /dev/null +++ b/client.go @@ -0,0 +1,96 @@ +package config + +import ( + "context" + "errors" + "fmt" +) + +func New(namespace, appName string, providers []Provider) *Client { + return &Client{ + namespace: namespace, + appName: appName, + providers: providers, + } +} + +type Client struct { + providers []Provider + appName string + namespace string +} + +func (c *Client) key(name string) Key { + return Key{ + Name: name, + AppName: c.appName, + Namespace: c.namespace, + } +} + +func (c *Client) Value(ctx context.Context, name string) (Value, error) { + variable, err := c.Variable(ctx, name) + if err != nil { + return nil, err + } + + return variable.Value, nil +} + +func (c *Client) Variable(ctx context.Context, name string) (Variable, error) { + var ( + variable Variable + err error + ) + + key := c.key(name) + + for _, provider := range c.providers { + variable, err = provider.Read(ctx, key) + if err == nil || !errors.Is(err, ErrVariableNotFound) { + break + } + } + + if err != nil { + return variable, fmt.Errorf("client failed get variable: %w", err) + } + + return variable, nil +} + +func NewWatch(namespace, appName string, providers []Provider) *WatchClient { + cl := WatchClient{ + Client: New(namespace, appName, providers), + } + + for _, provider := range providers { + if watch, ok := provider.(WatchProvider); ok { + cl.providers = append(cl.providers, watch) + } + } + + return &cl +} + +type WatchClient struct { + *Client + providers []WatchProvider +} + +func (wc *WatchClient) Watch(ctx context.Context, name string, callback WatchCallback) error { + key := wc.key(name) + + for _, provider := range wc.providers { + err := provider.Watch(ctx, key, callback) + if err != nil { + if errors.Is(err, ErrVariableNotFound) { + continue + } + + return fmt.Errorf("client: failed watch by provider %s: %w", provider.Name(), err) + } + } + + return nil +} diff --git a/client_example_test.go b/client_example_test.go new file mode 100644 index 0000000..fb0f40c --- /dev/null +++ b/client_example_test.go @@ -0,0 +1,198 @@ +package config_test + +import ( + "context" + "fmt" + "log" + "os" + "sync" + "time" + + "gitoa.ru/go-4devs/config" + "gitoa.ru/go-4devs/config/provider/arg" + "gitoa.ru/go-4devs/config/provider/env" + "gitoa.ru/go-4devs/config/provider/etcd" + "gitoa.ru/go-4devs/config/provider/json" + "gitoa.ru/go-4devs/config/provider/vault" + "gitoa.ru/go-4devs/config/provider/watcher" + "gitoa.ru/go-4devs/config/provider/yaml" + "gitoa.ru/go-4devs/config/test" +) + +func ExampleNew() { + ctx := context.Background() + _ = os.Setenv("FDEVS_CONFIG_LISTEN", "8080") + _ = os.Setenv("FDEVS_CONFIG_HOST", "localhost") + + args := os.Args + + defer func() { + os.Args = args + }() + + os.Args = []string{"main.go", "--host=gitoa.ru"} + + // configure etcd client + etcdClient, err := test.NewEtcd(ctx) + if err != nil { + log.Print(err) + + return + } + + // configure vault client + vaultClient, err := test.NewVault() + if err != nil { + log.Print(err) + + return + } + + // read json config + jsonConfig := test.ReadFile("config.json") + + providers := []config.Provider{ + arg.New(), + env.New(), + etcd.NewProvider(etcdClient), + vault.NewSecretKV2(vaultClient), + json.New(jsonConfig), + } + config := config.New(test.Namespace, test.AppName, providers) + + dsn, err := config.Value(ctx, "example:dsn") + if err != nil { + log.Print(err) + + return + } + + port, err := config.Value(ctx, "listen") + if err != nil { + log.Print(err) + + return + } + + enabled, err := config.Value(ctx, "maintain") + if err != nil { + log.Print(err) + + return + } + + title, err := config.Value(ctx, "app.name.title") + if err != nil { + log.Print(err) + + return + } + + cfgValue, err := config.Value(ctx, "cfg") + if err != nil { + log.Print(err) + + return + } + + hostValue, err := config.Value(ctx, "host") + if err != nil { + log.Print(err) + + return + } + + cfg := test.Config{} + _ = cfgValue.Unmarshal(&cfg) + + fmt.Printf("dsn from vault: %s\n", dsn.String()) + fmt.Printf("listen from env: %d\n", port.Int()) + fmt.Printf("maintain from etcd: %v\n", enabled.Bool()) + fmt.Printf("title from json: %v\n", title.String()) + fmt.Printf("struct from json: %+v\n", cfg) + fmt.Printf("replace env host by args: %v\n", hostValue.String()) + // Output: + // dsn from vault: pgsql://user@pass:127.0.0.1:5432 + // listen from env: 8080 + // maintain from etcd: true + // title from json: config title + // struct from json: {Duration:21m0s Enabled:true} + // replace env host by args: gitoa.ru +} + +func ExampleNewWatch() { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + // configure etcd client + etcdClient, err := test.NewEtcd(ctx) + if err != nil { + log.Print(err) + + return + } + + _ = os.Setenv("FDEVS_CONFIG_EXAMPLE_ENABLE", "true") + + _, err = etcdClient.KV.Put(ctx, "fdevs/config/example_db_dsn", "pgsql://user@pass:127.0.0.1:5432") + if err != nil { + log.Print(err) + + return + } + + defer func() { + cancel() + + if _, err = etcdClient.KV.Delete(context.Background(), "fdevs/config/example_db_dsn"); err != nil { + log.Print(err) + + return + } + }() + + providers := []config.Provider{ + watcher.New(time.Microsecond, env.New()), + watcher.New(time.Microsecond, yaml.NewFile("test/fixture/config.yaml")), + etcd.NewProvider(etcdClient), + } + watcher := config.NewWatch(test.Namespace, test.AppName, providers) + wg := sync.WaitGroup{} + wg.Add(2) + + err = watcher.Watch(ctx, "example_enable", func(ctx context.Context, oldVar, newVar config.Variable) { + fmt.Println("update ", oldVar.Provider, " variable:", oldVar.Name, ", old: ", oldVar.Value.Bool(), " new:", newVar.Value.Bool()) + wg.Done() + }) + if err != nil { + log.Print(err) + + return + } + + _ = os.Setenv("FDEVS_CONFIG_EXAMPLE_ENABLE", "false") + + err = watcher.Watch(ctx, "example_db_dsn", func(ctx context.Context, oldVar, newVar config.Variable) { + fmt.Println("update ", oldVar.Provider, " variable:", oldVar.Name, ", old: ", oldVar.Value.String(), " new:", newVar.Value.String()) + wg.Done() + }) + if err != nil { + log.Print(err) + + return + } + + time.AfterFunc(time.Second, func() { + if _, err := etcdClient.KV.Put(ctx, "fdevs/config/example_db_dsn", "mysql://localhost:5432"); err != nil { + log.Print(err) + + return + } + }) + + wg.Wait() + + // Output: + // update env variable: FDEVS_CONFIG_EXAMPLE_ENABLE , old: true new: false + // update etcd variable: fdevs/config/example_db_dsn , old: pgsql://user@pass:127.0.0.1:5432 new: mysql://localhost:5432 +} diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..a41d67b --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,17 @@ +version: '3' + +services: + vault: + image: vault:latest + cap_add: + - IPC_LOCK + ports: + - "8200:8200" + environment: + VAULT_DEV_ROOT_TOKEN_ID: "dev" + etcd: + image: bitnami/etcd + environment: + ALLOW_NONE_AUTHENTICATION: "yes" + ports: + - "2379:2379" diff --git a/error.go b/error.go new file mode 100644 index 0000000..5cce75f --- /dev/null +++ b/error.go @@ -0,0 +1,8 @@ +package config + +import "errors" + +var ( + ErrVariableNotFound = errors.New("variable not found") + ErrInvalidValue = errors.New("invalid value") +) diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..824d50a --- /dev/null +++ b/go.mod @@ -0,0 +1,15 @@ +module gitoa.ru/go-4devs/config + +go 1.16 + +require ( + github.com/hashicorp/vault/api v1.1.0 + github.com/pelletier/go-toml v1.9.0 + github.com/smartystreets/goconvey v1.6.4 // indirect + github.com/stretchr/testify v1.7.0 + github.com/tidwall/gjson v1.7.5 + go.etcd.io/etcd/api/v3 v3.5.0-alpha.0 + go.etcd.io/etcd/client/v3 v3.5.0-alpha.0 + gopkg.in/ini.v1 v1.62.0 + gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..21c49ad --- /dev/null +++ b/go.sum @@ -0,0 +1,317 @@ +cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ= +github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/DataDog/datadog-go v3.2.0+incompatible/go.mod h1:LButxg5PwREeZtORoXG3tL4fMGNddJ+vMq1mwgfaqoQ= +github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= +github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= +github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= +github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= +github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY= +github.com/armon/go-metrics v0.3.0/go.mod h1:zXjbSimjXTd7vOpY8B0/2LpvNvDoXBuplAD+gJD3GYs= +github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= +github.com/aws/aws-sdk-go v1.25.37/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo= +github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= +github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= +github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= +github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= +github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= +github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/circonus-labs/circonus-gometrics v2.3.1+incompatible/go.mod h1:nmEj6Dob7S7YxXgwXpfOuvO54S+tGdZdw9fuRZt25Ag= +github.com/circonus-labs/circonusllhist v0.1.3/go.mod h1:kMXHVDlOchFAehlya5ePtbp5jckzBHf4XRpQvBOLI+I= +github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= +github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= +github.com/coreos/go-semver v0.3.0 h1:wkHLiw0WNATZnSG7epLsujiMCgPAc9xhjJ4tgnAxmfM= +github.com/coreos/go-semver v0.3.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= +github.com/coreos/go-systemd/v22 v22.1.0 h1:kq/SbG2BCKLkDKkjQf5OWwKWUKj1lgs3lFI4PxnR5lg= +github.com/coreos/go-systemd/v22 v22.1.0/go.mod h1:xO0FLkIi5MaZafQlIrOotqXZ90ih+1atmu1JpKERPPk= +github.com/creack/pty v1.1.11/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= +github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= +github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= +github.com/fatih/color v1.7.0 h1:DkWD4oS2D8LGGgTQ6IvwJJXSL5Vp2ffcQg58nFV38Ys= +github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= +github.com/fatih/structs v1.1.0/go.mod h1:9NiDSp5zOcgEDl+j00MP/WkGVPOlPRLejGD8Ga6PJ7M= +github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= +github.com/go-asn1-ber/asn1-ber v1.3.1/go.mod h1:hEBeB/ic+5LoWskz+yKT7vGhhPYkProFKoKdwZRWMe0= +github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= +github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= +github.com/go-ldap/ldap/v3 v3.1.3/go.mod h1:3rbOH3jRS2u6jg2rJnKAMLE/xQyCKIveG2Sa/Cohzb8= +github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= +github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= +github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= +github.com/go-test/deep v1.0.2-0.20181118220953-042da051cf31/go.mod h1:wGDj63lr65AM2AQyKZd/NYHGb0R+1RLqB8NKt3aSFNA= +github.com/go-test/deep v1.0.2 h1:onZX1rnHT3Wv6cqNgYyFOOlgVKJrksuCMCRvJStbMYw= +github.com/go-test/deep v1.0.2/go.mod h1:wGDj63lr65AM2AQyKZd/NYHGb0R+1RLqB8NKt3aSFNA= +github.com/godbus/dbus/v5 v5.0.3/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= +github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= +github.com/gogo/protobuf v1.3.1 h1:DqDEcV5aeaTmdFBePNpYsp3FlcVH/2ISVVM9Qf8PSls= +github.com/gogo/protobuf v1.3.1/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXPKa29o= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= +github.com/golang/protobuf v1.3.5 h1:F768QJ1E9tib+q5Sc8MkdJi1RxLTbRcTf8LJV56aRls= +github.com/golang/protobuf v1.3.5/go.mod h1:6O5/vntMXwX2lRkT1hjjk0nAC1IDOTvTlVgjlRvqsdk= +github.com/golang/snappy v0.0.1 h1:Qgr9rKW7uDUkrbSmQeiDsGa8SjGyCOGtuasMWwvp2P4= +github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= +github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.4.0 h1:xsAVV57WRhGj6kEIi8ReJzQlHHqcBYCElAvkovg3B/4= +github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= +github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 h1:EGx4pi6eqNxGaHF6qqu48+N2wcFQ5qg5FXgOdqsJ5d8= +github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= +github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk= +github.com/grpc-ecosystem/grpc-gateway v1.14.6/go.mod h1:zdiPV4Yse/1gnckTHtghG4GkDEdKCRJduHpTxT3/jcw= +github.com/hashicorp/errwrap v1.0.0 h1:hLrqtEDnRye3+sgx6z4qVLNuviH3MR5aQ0ykNJa/UYA= +github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= +github.com/hashicorp/go-cleanhttp v0.5.0/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= +github.com/hashicorp/go-cleanhttp v0.5.1 h1:dH3aiDG9Jvb5r5+bYHsikaOUIpcM0xvgMXVoDkXMzJM= +github.com/hashicorp/go-cleanhttp v0.5.1/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= +github.com/hashicorp/go-hclog v0.0.0-20180709165350-ff2cf002a8dd/go.mod h1:9bjs9uLqI8l75knNv3lV1kA55veR+WUPSiKIWcQHudI= +github.com/hashicorp/go-hclog v0.9.2/go.mod h1:5CU+agLiy3J7N7QjHK5d05KxGsuXiQLrjA0H7acj2lQ= +github.com/hashicorp/go-hclog v0.12.0 h1:d4QkX8FRTYaKaCZBoXYY8zJX2BXjWxurN/GA2tkrmZM= +github.com/hashicorp/go-hclog v0.12.0/go.mod h1:whpDNt7SSdeAju8AWKIWsul05p54N/39EeqMAyrmvFQ= +github.com/hashicorp/go-immutable-radix v1.0.0/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60= +github.com/hashicorp/go-kms-wrapping/entropy v0.1.0/go.mod h1:d1g9WGtAunDNpek8jUIEJnBlbgKS1N2Q61QkHiZyR1g= +github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk= +github.com/hashicorp/go-multierror v1.1.0 h1:B9UzwGQJehnUY1yNrnwREHc3fGbC2xefo8g4TbElacI= +github.com/hashicorp/go-multierror v1.1.0/go.mod h1:spPvp8C1qA32ftKqdAHm4hHTbPw+vmowP0z+KUhOZdA= +github.com/hashicorp/go-plugin v1.0.1/go.mod h1:++UyYGoz3o5w9ZzAdZxtQKrWWP+iqPBn3cQptSMzBuY= +github.com/hashicorp/go-retryablehttp v0.5.3/go.mod h1:9B5zBasrRhHXnJnui7y6sL7es7NDiJgTc6Er0maI1Xs= +github.com/hashicorp/go-retryablehttp v0.6.6 h1:HJunrbHTDDbBb/ay4kxa1n+dLmttUlnP3V9oNE4hmsM= +github.com/hashicorp/go-retryablehttp v0.6.6/go.mod h1:vAew36LZh98gCBJNLH42IQ1ER/9wtLZZ8meHqQvEYWY= +github.com/hashicorp/go-rootcerts v1.0.2 h1:jzhAVGtqPKbwpyCPELlgNWhE1znq+qwJtW5Oi2viEzc= +github.com/hashicorp/go-rootcerts v1.0.2/go.mod h1:pqUvnprVnM5bf7AOirdbb01K4ccR319Vf4pU3K5EGc8= +github.com/hashicorp/go-sockaddr v1.0.2 h1:ztczhD1jLxIRjVejw8gFomI1BQZOe2WoVOu0SyteCQc= +github.com/hashicorp/go-sockaddr v1.0.2/go.mod h1:rB4wwRAUzs07qva3c5SdrY/NEtAUjGlgmH/UkBUC97A= +github.com/hashicorp/go-uuid v1.0.0/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= +github.com/hashicorp/go-uuid v1.0.2/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= +github.com/hashicorp/go-version v1.1.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= +github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= +github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= +github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4= +github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= +github.com/hashicorp/vault/api v1.1.0 h1:QcxC7FuqEl0sZaIjcXB/kNEeBa0DH5z57qbWBvZwLC4= +github.com/hashicorp/vault/api v1.1.0/go.mod h1:R3Umvhlxi2TN7Ex2hzOowyeNb+SfbVWI973N+ctaFMk= +github.com/hashicorp/vault/sdk v0.1.14-0.20200519221838-e0cfd64bc267 h1:e1ok06zGrWJW91rzRroyl5nRNqraaBe4d5hiKcVZuHM= +github.com/hashicorp/vault/sdk v0.1.14-0.20200519221838-e0cfd64bc267/go.mod h1:WX57W2PwkrOPQ6rVQk+dy5/htHIaB4aBM70EwKThu10= +github.com/hashicorp/yamux v0.0.0-20180604194846-3520598351bb/go.mod h1:+NfK9FKeTrX5uv1uIXGdwYDTeHna2qgaIlx54MXqjAM= +github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k= +github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= +github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= +github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo= +github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= +github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= +github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQLJ+jE2L00= +github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= +github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= +github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= +github.com/mattn/go-colorable v0.1.4 h1:snbPLB8fVfU9iwbbo30TPtbLRzwWu6aJS6Xh4eaaviA= +github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= +github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= +github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= +github.com/mattn/go-isatty v0.0.10 h1:qxFzApOv4WsAL965uUPIsXzAKCZxN2p9UqdhFS4ZW10= +github.com/mattn/go-isatty v0.0.10/go.mod h1:qgIWMr58cqv1PHHyhnkY9lrL7etaEgOFcMEpPG5Rm84= +github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= +github.com/mitchellh/cli v1.0.0/go.mod h1:hNIlj7HEI86fIcpObd7a0FcrxTWetlwJDGcceTlRvqc= +github.com/mitchellh/copystructure v1.0.0/go.mod h1:SNtv71yrdKgLRyLFxmLdkAbkKEFWgYaq1OVrnRcwhnw= +github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= +github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= +github.com/mitchellh/go-testing-interface v0.0.0-20171004221916-a61a99592b77/go.mod h1:kRemZodwjscx+RGhAo8eIhFbs2+BFgRtFPeD/KE+zxI= +github.com/mitchellh/go-testing-interface v1.0.0/go.mod h1:kRemZodwjscx+RGhAo8eIhFbs2+BFgRtFPeD/KE+zxI= +github.com/mitchellh/go-wordwrap v1.0.0/go.mod h1:ZXFpozHsX6DPmq2I0TCekCxypsnAUbP2oI0UX1GXzOo= +github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= +github.com/mitchellh/mapstructure v1.3.2 h1:mRS76wmkOn3KkKAyXDu42V+6ebnXWIztFSYGN7GeoRg= +github.com/mitchellh/mapstructure v1.3.2/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= +github.com/mitchellh/reflectwalk v1.0.0/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= +github.com/oklog/run v1.0.0/go.mod h1:dlhp/R75TPv97u0XWUtDeV/lRKWPKSdTuV0TZvrmrQA= +github.com/pascaldekloe/goe v0.1.0/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= +github.com/pelletier/go-toml v1.9.0 h1:NOd0BRdOKpPf0SxkL3HxSQOG7rNh+4kl6PHcBPFs7Q0= +github.com/pelletier/go-toml v1.9.0/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c= +github.com/pierrec/lz4 v2.0.5+incompatible h1:2xWsjqPFWcplujydGg4WmhC/6fZqK42wMM8aXeqhl0I= +github.com/pierrec/lz4 v2.0.5+incompatible/go.mod h1:pdkljMzZIN41W+lC3N2tnIh5sFi+IEE17M5jbnwPHcY= +github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I= +github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI= +github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= +github.com/prometheus/client_golang v0.9.2/go.mod h1:OsXs2jCmiKlQ1lTBmv21f2mNfw4xf/QclQDMrYNZzcM= +github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= +github.com/prometheus/client_golang v1.5.1/go.mod h1:e9GMxYsXl05ICDXkRhurwBS4Q3OK1iX/F2sw+iXX5zU= +github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= +github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/client_model v0.2.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/common v0.0.0-20181126121408-4724e9255275/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro= +github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= +github.com/prometheus/common v0.9.1/go.mod h1:yhUN8i9wzaXS3w1O07YhxHEBxD+W35wd8bs7vj7HSQ4= +github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= +github.com/prometheus/procfs v0.0.0-20181204211112-1dc9a6cbc91a/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= +github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= +github.com/prometheus/procfs v0.0.8/go.mod h1:7Qr8sr6344vo1JqZ6HhLceV9o3AJ1Ff+GxbHq6oeK9A= +github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ= +github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= +github.com/ryanuber/columnize v2.1.0+incompatible/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= +github.com/ryanuber/go-glob v1.0.0 h1:iQh3xXAumdQ+4Ufa5b25cRpC5TYKlno6hsv6Cb3pkBk= +github.com/ryanuber/go-glob v1.0.0/go.mod h1:807d1WSdnB0XRJzKNil9Om6lcp/3a0v4qIHxIXzX/Yc= +github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= +github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= +github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d h1:zE9ykElWQ6/NYmHa3jpm/yHnI4xSofP+UP6SpjHcSeM= +github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= +github.com/smartystreets/goconvey v1.6.4 h1:fv0U8FUIMPNf1L9lnHLvLhgicrIVChEkdzIKYqbNC9s= +github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= +github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/tidwall/gjson v1.7.5 h1:zmAN/xmX7OtpAkv4Ovfso60r/BiCi5IErCDYGNJu+uc= +github.com/tidwall/gjson v1.7.5/go.mod h1:5/xDoumyyDNerp2U36lyolv46b3uF/9Bu6OfyQ9GImk= +github.com/tidwall/match v1.0.3 h1:FQUVvBImDutD8wJLN6c5eMzWtjgONK9MwIBCOrUJKeE= +github.com/tidwall/match v1.0.3/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM= +github.com/tidwall/pretty v1.1.0 h1:K3hMW5epkdAVwibsQEfR/7Zj0Qgt4DxtNumTq/VloO8= +github.com/tidwall/pretty v1.1.0/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk= +github.com/tv42/httpunix v0.0.0-20150427012821-b75d8614f926/go.mod h1:9ESjWnEqriFuLhtthL60Sar/7RFoluCcXsuvEwTV5KM= +go.etcd.io/etcd/api/v3 v3.5.0-alpha.0 h1:+e5nrluATIy3GP53znpkHMFzPTHGYyzvJGFCbuI6ZLc= +go.etcd.io/etcd/api/v3 v3.5.0-alpha.0/go.mod h1:mPcW6aZJukV6Aa81LSKpBjQXTWlXB5r74ymPoSWa3Sw= +go.etcd.io/etcd/client/v3 v3.5.0-alpha.0 h1:dr1EOILak2pu4Nf5XbRIOCNIBjcz6UmkQd7hHRXwxaM= +go.etcd.io/etcd/client/v3 v3.5.0-alpha.0/go.mod h1:wKt7jgDgf/OfKiYmCq5WFGxOFAkVMLxiiXgLDFhECr8= +go.etcd.io/etcd/pkg/v3 v3.5.0-alpha.0 h1:3yLUEC0nFCxw/RArImOyRUI4OAFbg4PFpBbAhSNzKNY= +go.etcd.io/etcd/pkg/v3 v3.5.0-alpha.0/go.mod h1:tV31atvwzcybuqejDoY3oaNRTtlD2l/Ot78Pc9w7DMY= +go.uber.org/atomic v1.6.0 h1:Ezj3JGmsOnG1MoRWQkPBsKLe9DwWD9QeXzTRzzldNVk= +go.uber.org/atomic v1.6.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ= +go.uber.org/multierr v1.5.0 h1:KCa4XfM8CWFCpxXRGok+Q0SS/0XBhMDbHHGABQLvD2A= +go.uber.org/multierr v1.5.0/go.mod h1:FeouvMocqHpRaaGuG9EjoKcStLC43Zu/fmqdUMPcKYU= +go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee h1:0mgffUl7nfd+FpvXMVz4IDEaUSmT1ysygQC7qYo7sG4= +go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee/go.mod h1:vJERXedbb3MVM5f9Ejo0C68/HhF8uaILCdgjnY+goOA= +go.uber.org/zap v1.16.0 h1:uFRZXykJGK9lLY4HtgSw44DnIcAM+kRBP7x5m+NpAOM= +go.uber.org/zap v1.16.0/go.mod h1:MA8QOfq0BHJwdXa996Y4dYkAqRKB8/1K1QMMZVaNZjQ= +golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20190418165655-df01cb2cc480/go.mod h1:WFFai1msRO1wXaEeE5yQxYXgSfI8pQAWXbQop6sCtWE= +golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529 h1:iMGN4xG0cnqj3t+zOM8wUB0BiPKHEwSxEZCvzcbZuvk= +golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= +golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20190930215403-16217165b5de h1:5hukYrvBGR8/eNkX5mdUezrA6JiaEZDtJb9Ei+1LlBs= +golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= +golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20181201002055-351d144fa1fc/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20191002035440-2ec189313ef0/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200602114024-627f9648deb9 h1:pNX+40auqi2JqRfOP1akLGtYcn15TUbkhwuCO3foqqM= +golang.org/x/net v0.0.0-20200602114024-627f9648deb9/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190129075346-302c3dd5f1cc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190403152447-81d4e9dc473e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191008105621-543471e840be/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200122134326-e047566fdf82/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201009025420-dfb3f7c4e634 h1:bNEHhJCnrwMKNMmOx3yAynp5vs5/gRy+XWFtZFu7NBM= +golang.org/x/sys v0.0.0-20201009025420-dfb3f7c4e634/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/time v0.0.0-20200416051211-89c76fbcd5d1 h1:NusfzzA6yGQ+ua51ck7E3omNUX/JuqbFSaRGqU8CcLI= +golang.org/x/time v0.0.0-20200416051211-89c76fbcd5d1/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/tools v0.0.0-20181030221726-6c7e314b6563/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= +golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20191029041327-9cc4af7d6b2c/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191029190741-b9c20aec41a5 h1:hKsoRgsbwY1NafxrwTs+k64bikrLBkAgPir1TNCj3Zs= +golang.org/x/tools v0.0.0-20191029190741-b9c20aec41a5/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= +google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= +google.golang.org/genproto v0.0.0-20200513103714-09dca8ec2884 h1:fiNLklpBwWK1mth30Hlwk+fcdBmIALlgF5iy77O37Ig= +google.golang.org/genproto v0.0.0-20200513103714-09dca8ec2884/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/grpc v1.14.0/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw= +google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= +google.golang.org/grpc v1.22.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= +google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= +google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= +google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +google.golang.org/grpc v1.29.1/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3IjizoKk= +google.golang.org/grpc v1.32.0 h1:zWTV+LMdc3kaiJMSTOFz2UgSBgx8RNQoTGiZu3fR9S0= +google.golang.org/grpc v1.32.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= +gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo= +gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= +gopkg.in/ini.v1 v1.62.0 h1:duBzk771uxoUuOlyRLkHsygud9+5lrlGjdFBb4mSKDU= +gopkg.in/ini.v1 v1.62.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= +gopkg.in/square/go-jose.v2 v2.5.1 h1:7odma5RETjNHWJnR32wx8t+Io4djHE1PqxCFx3iiZ2w= +gopkg.in/square/go-jose.v2 v2.5.1/go.mod h1:M9dMgbHiYLoDGQrXy7OpJDJWiKiU//h+vD76mk0e1AI= +gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.3/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.5/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10= +gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo= +gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.1-2019.2.3 h1:3JgtbtFHMiCmsznwGVTUWbgGov+pVqnlf1dEJTNAXeM= +honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= +sigs.k8s.io/yaml v1.2.0/go.mod h1:yfXDCHCao9+ENCvLSE62v9VSji2MKu5jeNfTrofGhJc= diff --git a/key.go b/key.go new file mode 100644 index 0000000..76da1d4 --- /dev/null +++ b/key.go @@ -0,0 +1,15 @@ +package config + +import "context" + +type Key struct { + Name string + AppName string + Namespace string +} + +type KeyFactory func(ctx context.Context, key Key) string + +func (k Key) String() string { + return k.Namespace + "_" + k.AppName + "_" + k.Name +} diff --git a/key/helpers.go b/key/helpers.go new file mode 100644 index 0000000..311fcfa --- /dev/null +++ b/key/helpers.go @@ -0,0 +1,32 @@ +package key + +import ( + "context" + "strings" + + "gitoa.ru/go-4devs/config" +) + +func LastIndex(sep string, factory config.KeyFactory) func(ctx context.Context, key config.Key) (string, string) { + return func(ctx context.Context, key config.Key) (string, string) { + k := factory(ctx, key) + + idx := strings.LastIndex(k, sep) + if idx == -1 { + return k, "" + } + + return k[0:idx], k[idx+len(sep):] + } +} + +func LastIndexField(sep, def string, factory config.KeyFactory) func(ctx context.Context, key config.Key) (string, string) { + return func(ctx context.Context, key config.Key) (string, string) { + p, k := LastIndex(sep, factory)(ctx, key) + if k == "" { + return p, def + } + + return p, k + } +} diff --git a/key/helpers_test.go b/key/helpers_test.go new file mode 100644 index 0000000..d0fd980 --- /dev/null +++ b/key/helpers_test.go @@ -0,0 +1,64 @@ +package key_test + +import ( + "context" + "testing" + + "github.com/stretchr/testify/assert" + "gitoa.ru/go-4devs/config" + "gitoa.ru/go-4devs/config/key" +) + +func TestLastIndex(t *testing.T) { + t.Parallel() + + ctx := context.Background() + + cases := map[string]struct { + sep string + path string + field string + }{ + "/secret/with/field/name": { + sep: "/", + path: "/secret/with/field", + field: "name", + }, + "/secret/database:username": { + sep: ":", + path: "/secret/database", + field: "username", + }, + "database:username": { + sep: ":", + path: "database", + field: "username", + }, + "/secret/database-dsn": { + sep: ":", + path: "/secret/database-dsn", + field: "", + }, + "/secret/database--dsn": { + sep: "--", + path: "/secret/database", + field: "dsn", + }, + "/secret/database:dsn": { + sep: "--", + path: "/secret/database:dsn", + field: "", + }, + } + + for path, data := range cases { + k := config.Key{ + Name: path, + } + + fn := key.LastIndex(data.sep, key.Name) + ns, field := fn(ctx, k) + assert.Equal(t, data.field, field, k) + assert.Equal(t, data.path, ns, k) + } +} diff --git a/key/key.go b/key/key.go new file mode 100644 index 0000000..4ba9990 --- /dev/null +++ b/key/key.go @@ -0,0 +1,46 @@ +package key + +import ( + "context" + "strings" + + "gitoa.ru/go-4devs/config" +) + +func NsAppName(sep string) config.KeyFactory { + return func(_ context.Context, key config.Key) string { + return strings.Join([]string{key.Namespace, key.AppName, key.Name}, sep) + } +} + +func AppName(sep string) config.KeyFactory { + return func(_ context.Context, key config.Key) string { + return strings.Join([]string{key.AppName, key.Name}, sep) + } +} + +func PrefixName(prefix string, factory config.KeyFactory) config.KeyFactory { + return func(ctx context.Context, key config.Key) string { + return prefix + factory(ctx, key) + } +} + +func Name(_ context.Context, key config.Key) string { + return key.Name +} + +func AliasName(name string, alias string, def config.KeyFactory) config.KeyFactory { + return func(ctx context.Context, key config.Key) string { + if name == key.Name { + return alias + } + + return def(ctx, key) + } +} + +func ReplaceAll(oldVal, newVal string, parent config.KeyFactory) config.KeyFactory { + return func(ctx context.Context, key config.Key) string { + return strings.ReplaceAll(parent(ctx, key), oldVal, newVal) + } +} diff --git a/provider.go b/provider.go new file mode 100644 index 0000000..2b11b16 --- /dev/null +++ b/provider.go @@ -0,0 +1,19 @@ +package config + +import "context" + +type Provider interface { + Read(ctx context.Context, key Key) (Variable, error) + NamedProvider +} + +type WatchCallback func(ctx context.Context, oldVar, newVar Variable) + +type WatchProvider interface { + Watch(ctx context.Context, key Key, callback WatchCallback) error + NamedProvider +} + +type NamedProvider interface { + Name() string +} diff --git a/provider/arg/provider.go b/provider/arg/provider.go new file mode 100644 index 0000000..5164bd1 --- /dev/null +++ b/provider/arg/provider.go @@ -0,0 +1,136 @@ +package arg + +import ( + "context" + "fmt" + "os" + "strings" + + "gitoa.ru/go-4devs/config" + "gitoa.ru/go-4devs/config/key" + "gitoa.ru/go-4devs/config/value" + "gopkg.in/yaml.v3" +) + +var _ config.Provider = (*Provider)(nil) + +type Option func(*Provider) + +func WithKeyFactory(factory config.KeyFactory) Option { + return func(p *Provider) { p.key = factory } +} + +func New(opts ...Option) *Provider { + p := Provider{ + key: key.Name, + } + + for _, opt := range opts { + opt(&p) + } + + return &p +} + +type Provider struct { + args map[string][]string + key config.KeyFactory +} + +// nolint: cyclop +func (p *Provider) parseOne(arg string) (name, val string, err error) { + if arg[0] != '-' { + return + } + + numMinuses := 1 + + if arg[1] == '-' { + numMinuses++ + } + + name = strings.TrimSpace(arg[numMinuses:]) + if len(name) == 0 { + return + } + + if name[0] == '-' || name[0] == '=' { + return "", "", fmt.Errorf("%w: bad flag syntax: %s", config.ErrInvalidValue, arg) + } + + for i := 1; i < len(name); i++ { + if name[i] == '=' || name[i] == ' ' { + val = strings.TrimSpace(name[i+1:]) + name = name[0:i] + + break + } + } + + if val == "" && numMinuses == 1 && len(arg) > 2 { + name, val = name[:1], name[1:] + } + + return name, val, nil +} + +func (p *Provider) parse() error { + if len(p.args) > 0 { + return nil + } + + p.args = make(map[string][]string, len(os.Args[1:])) + + for _, arg := range os.Args[1:] { + name, value, err := p.parseOne(arg) + if err != nil { + return err + } + + if name != "" { + p.args[name] = append(p.args[name], value) + } + } + + return nil +} + +func (p *Provider) Name() string { + return "arg" +} + +func (p *Provider) IsSupport(ctx context.Context, key config.Key) bool { + return p.key(ctx, key) != "" +} + +func (p *Provider) Read(ctx context.Context, key config.Key) (config.Variable, error) { + if err := p.parse(); err != nil { + return config.Variable{Provider: p.Name()}, err + } + + k := p.key(ctx, key) + if val, ok := p.args[k]; ok { + switch { + case len(val) == 1: + return config.Variable{ + Name: k, + Provider: p.Name(), + Value: value.JString(val[0]), + }, nil + default: + var n yaml.Node + + if err := yaml.Unmarshal([]byte("["+strings.Join(val, ",")+"]"), &n); err != nil { + return config.Variable{}, fmt.Errorf("arg: failed unmarshal yaml:%w", err) + } + + return config.Variable{ + Name: k, + Provider: p.Name(), + Value: value.Decode(n.Decode), + }, nil + } + } + + return config.Variable{Name: k, Provider: p.Name()}, config.ErrVariableNotFound +} diff --git a/provider/arg/provider_test.go b/provider/arg/provider_test.go new file mode 100644 index 0000000..44216a5 --- /dev/null +++ b/provider/arg/provider_test.go @@ -0,0 +1,48 @@ +package arg_test + +import ( + "os" + "testing" + "time" + + "gitoa.ru/go-4devs/config/provider/arg" + "gitoa.ru/go-4devs/config/test" +) + +func TestProvider(t *testing.T) { + t.Parallel() + + args := os.Args + + defer func() { + os.Args = args + }() + + os.Args = []string{ + "main.go", + "--listen=8080", + "--config=config.hcl", + "--url=http://4devs.io", + "--url=https://4devs.io", + "--timeout=1m", + "--timeout=1h", + "--start-at=2010-01-02T15:04:05Z", + "--end-after=2009-01-02T15:04:05Z", + "--end-after=2008-01-02T15:04:05+03:00", + } + read := []test.Read{ + test.NewRead("listen", 8080), + test.NewRead("config", "config.hcl"), + test.NewRead("start-at", test.Time("2010-01-02T15:04:05Z")), + test.NewReadUnmarshal("url", &[]string{"http://4devs.io", "https://4devs.io"}, &[]string{}), + test.NewReadUnmarshal("timeout", &[]time.Duration{time.Minute, time.Hour}, &[]time.Duration{}), + test.NewReadUnmarshal("end-after", &[]time.Time{ + test.Time("2009-01-02T15:04:05Z"), + test.Time("2008-01-02T15:04:05+03:00"), + }, &[]time.Time{}), + } + + prov := arg.New() + + test.Run(t, prov, read) +} diff --git a/provider/env/provider.go b/provider/env/provider.go new file mode 100644 index 0000000..9102c16 --- /dev/null +++ b/provider/env/provider.go @@ -0,0 +1,61 @@ +package env + +import ( + "context" + "os" + "strings" + + "gitoa.ru/go-4devs/config" + "gitoa.ru/go-4devs/config/key" + "gitoa.ru/go-4devs/config/value" +) + +var _ config.Provider = (*Provider)(nil) + +type Option func(*Provider) + +func WithKeyFactory(factory config.KeyFactory) Option { + return func(p *Provider) { p.key = factory } +} + +func New(opts ...Option) *Provider { + p := Provider{ + key: func(ctx context.Context, k config.Key) string { + return strings.ToUpper(key.NsAppName("_")(ctx, k)) + }, + } + + for _, opt := range opts { + opt(&p) + } + + return &p +} + +type Provider struct { + key config.KeyFactory +} + +func (p *Provider) Name() string { + return "env" +} + +func (p *Provider) IsSupport(ctx context.Context, key config.Key) bool { + return p.key(ctx, key) != "" +} + +func (p *Provider) Read(ctx context.Context, key config.Key) (config.Variable, error) { + k := p.key(ctx, key) + if val, ok := os.LookupEnv(k); ok { + return config.Variable{ + Name: k, + Provider: p.Name(), + Value: value.JString(val), + }, nil + } + + return config.Variable{ + Name: k, + Provider: p.Name(), + }, config.ErrVariableNotFound +} diff --git a/provider/env/provider_test.go b/provider/env/provider_test.go new file mode 100644 index 0000000..4096718 --- /dev/null +++ b/provider/env/provider_test.go @@ -0,0 +1,24 @@ +package env_test + +import ( + "os" + "testing" + + "gitoa.ru/go-4devs/config/provider/env" + "gitoa.ru/go-4devs/config/test" +) + +func TestProvider(t *testing.T) { + t.Parallel() + + os.Setenv("FDEVS_CONFIG_DSN", test.DSN) + os.Setenv("FDEVS_CONFIG_PORT", "8080") + + provider := env.New() + + read := []test.Read{ + test.NewRead("dsn", test.DSN), + test.NewRead("port", 8080), + } + test.Run(t, provider, read) +} diff --git a/provider/etcd/provider.go b/provider/etcd/provider.go new file mode 100644 index 0000000..d5a27da --- /dev/null +++ b/provider/etcd/provider.go @@ -0,0 +1,113 @@ +package etcd + +import ( + "context" + "fmt" + "log" + + "gitoa.ru/go-4devs/config" + "gitoa.ru/go-4devs/config/key" + "gitoa.ru/go-4devs/config/value" + pb "go.etcd.io/etcd/api/v3/mvccpb" + client "go.etcd.io/etcd/client/v3" +) + +var ( + _ config.Provider = (*Provider)(nil) + _ config.WatchProvider = (*Provider)(nil) +) + +type Client interface { + client.KV + client.Watcher +} + +func NewProvider(client Client) *Provider { + p := Provider{ + client: client, + key: key.NsAppName("/"), + } + + return &p +} + +type Provider struct { + client Client + key config.KeyFactory +} + +func (p *Provider) IsSupport(ctx context.Context, key config.Key) bool { + return p.key(ctx, key) != "" +} + +func (p *Provider) Name() string { + return "etcd" +} + +func (p *Provider) Read(ctx context.Context, key config.Key) (config.Variable, error) { + k := p.key(ctx, key) + + resp, err := p.client.Get(ctx, k, client.WithPrefix()) + if err != nil { + return config.Variable{}, fmt.Errorf("%w: key:%s, prov:%s", err, k, p.Name()) + } + + val, err := p.resolve(k, resp.Kvs) + if err != nil { + return config.Variable{}, fmt.Errorf("%w: key:%s, prov:%s", err, k, p.Name()) + } + + return val, nil +} + +func (p *Provider) Watch(ctx context.Context, key config.Key, callback config.WatchCallback) error { + go func(ctx context.Context, key string, callback config.WatchCallback) { + watch := p.client.Watch(ctx, key, client.WithPrevKV(), client.WithPrefix()) + for w := range watch { + kvs, olds := p.getEventKvs(w.Events) + if len(kvs) > 0 { + newVar, _ := p.resolve(key, kvs) + oldVar, _ := p.resolve(key, olds) + callback(ctx, oldVar, newVar) + } + } + }(ctx, p.key(ctx, key), callback) + + return nil +} + +func (p *Provider) getEventKvs(events []*client.Event) ([]*pb.KeyValue, []*pb.KeyValue) { + kvs := make([]*pb.KeyValue, 0, len(events)) + old := make([]*pb.KeyValue, 0, len(events)) + + for i := range events { + kvs = append(kvs, events[i].Kv) + old = append(old, events[i].PrevKv) + log.Println(events[i].Type) + } + + return kvs, old +} + +func (p *Provider) resolve(key string, kvs []*pb.KeyValue) (config.Variable, error) { + for _, kv := range kvs { + switch { + case kv == nil: + return config.Variable{ + Name: key, + Provider: p.Name(), + }, nil + case string(kv.Key) == key: + return config.Variable{ + Value: value.JBytes(kv.Value), + Name: key, + Provider: p.Name(), + }, nil + } + } + + return config.Variable{ + Name: key, + Provider: p.Name(), + }, config.ErrVariableNotFound +} diff --git a/provider/etcd/provider_test.go b/provider/etcd/provider_test.go new file mode 100644 index 0000000..c547c71 --- /dev/null +++ b/provider/etcd/provider_test.go @@ -0,0 +1,119 @@ +package etcd_test + +import ( + "context" + "fmt" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "gitoa.ru/go-4devs/config" + "gitoa.ru/go-4devs/config/provider/etcd" + "gitoa.ru/go-4devs/config/test" +) + +func TestProvider(t *testing.T) { + t.Parallel() + + ctx := context.Background() + + et, err := test.NewEtcd(ctx) + require.NoError(t, err) + + provider := etcd.NewProvider(et) + read := []test.Read{ + test.NewRead("db_dsn", test.DSN), + test.NewRead("duration", 12*time.Minute), + test.NewRead("port", 8080), + test.NewRead("maintain", true), + test.NewRead("start_at", test.Time("2020-01-02T15:04:05Z")), + test.NewRead("percent", .064), + test.NewRead("count", uint(2020)), + test.NewRead("int64", int64(2021)), + test.NewRead("uint64", int64(2022)), + test.NewReadConfig("config"), + } + test.Run(t, provider, read) +} + +func value(cnt int32) string { + return fmt.Sprintf("test data: %d", cnt) +} + +func TestWatcher(t *testing.T) { + t.Parallel() + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + key := config.Key{ + AppName: "config", + Namespace: "fdevs", + Name: "test_watch", + } + + et, err := test.NewEtcd(ctx) + require.NoError(t, err) + + defer func() { + _, err = et.KV.Delete(context.Background(), "fdevs/config/test_watch") + require.NoError(t, err) + }() + + var cnt, cnt2 int32 + + prov := etcd.NewProvider(et) + wg := sync.WaitGroup{} + wg.Add(6) + + watch := func(cnt *int32) func(ctx context.Context, oldVar, newVar config.Variable) { + return func(ctx context.Context, oldVar, newVar config.Variable) { + switch *cnt { + case 0: + assert.Equal(t, value(*cnt), newVar.Value.String()) + assert.Nil(t, oldVar.Value) + case 1: + assert.Equal(t, value(*cnt), newVar.Value.String()) + assert.Equal(t, value(*cnt-1), oldVar.Value.String()) + case 2: + _, perr := newVar.Value.ParseString() + assert.NoError(t, perr) + assert.Equal(t, "", newVar.Value.String()) + assert.Equal(t, value(*cnt-1), oldVar.Value.String()) + default: + assert.Fail(t, "unexpected watch") + } + + wg.Done() + atomic.AddInt32(cnt, 1) + } + } + + err = prov.Watch(ctx, key, watch(&cnt)) + err = prov.Watch(ctx, key, watch(&cnt2)) + require.NoError(t, err) + + time.AfterFunc(time.Second, func() { + _, err = et.KV.Put(ctx, "fdevs/config/test_watch", value(0)) + require.NoError(t, err) + _, err = et.KV.Put(ctx, "fdevs/config/test_watch", value(1)) + require.NoError(t, err) + _, err = et.KV.Delete(ctx, "fdevs/config/test_watch") + require.NoError(t, err) + }) + + time.AfterFunc(time.Second*10, func() { + assert.Fail(t, "failed watch after 5 sec") + cancel() + }) + + go func() { + wg.Wait() + cancel() + }() + + <-ctx.Done() +} diff --git a/provider/ini/provider.go b/provider/ini/provider.go new file mode 100644 index 0000000..01fed28 --- /dev/null +++ b/provider/ini/provider.go @@ -0,0 +1,62 @@ +package ini + +import ( + "context" + "fmt" + "strings" + + "gitoa.ru/go-4devs/config" + "gitoa.ru/go-4devs/config/value" + "gopkg.in/ini.v1" +) + +var _ config.Provider = (*Provider)(nil) + +func New(data *ini.File) *Provider { + return &Provider{ + data: data, + resolve: func(ctx context.Context, key config.Key) (string, string) { + keys := strings.SplitN(key.Name, "/", 2) + if len(keys) == 1 { + return "", keys[0] + } + + return keys[0], keys[1] + }, + } +} + +type Provider struct { + data *ini.File + resolve func(ctx context.Context, key config.Key) (string, string) +} + +func (p *Provider) IsSupport(ctx context.Context, key config.Key) bool { + section, name := p.resolve(ctx, key) + + return section != "" && name != "" +} + +func (p *Provider) Name() string { + return "ini" +} + +func (p *Provider) Read(ctx context.Context, key config.Key) (config.Variable, error) { + section, name := p.resolve(ctx, key) + + iniSection, err := p.data.GetSection(section) + if err != nil { + return config.Variable{}, fmt.Errorf("%w: %s: %v", config.ErrVariableNotFound, p.Name(), err) + } + + iniKey, err := iniSection.GetKey(name) + if err != nil { + return config.Variable{}, fmt.Errorf("%w: %s: %v", config.ErrVariableNotFound, p.Name(), err) + } + + return config.Variable{ + Name: section + ":" + name, + Provider: p.Name(), + Value: value.JString(iniKey.String()), + }, nil +} diff --git a/provider/ini/provider_test.go b/provider/ini/provider_test.go new file mode 100644 index 0000000..3d1572d --- /dev/null +++ b/provider/ini/provider_test.go @@ -0,0 +1,28 @@ +package ini_test + +import ( + "testing" + "time" + + "gitoa.ru/go-4devs/config/provider/ini" + "gitoa.ru/go-4devs/config/test" +) + +func TestProvider(t *testing.T) { + t.Parallel() + + file := test.NewINI() + + read := []test.Read{ + test.NewRead("project/PROJECT_BOARD_BASIC_KANBAN_TYPE", "To Do, In Progress, Done"), + test.NewRead("repository.editor/PREVIEWABLE_FILE_MODES", "markdown"), + test.NewRead("server/LOCAL_ROOT_URL", "http://0.0.0.0:3000/"), + test.NewRead("server/LFS_HTTP_AUTH_EXPIRY", 20*time.Minute), + test.NewRead("repository.pull-request/DEFAULT_MERGE_MESSAGE_SIZE", 5120), + test.NewRead("ui/SHOW_USER_EMAIL", true), + test.NewRead("cors/ENABLED", false), + } + + prov := ini.New(file) + test.Run(t, prov, read) +} diff --git a/provider/json/provider.go b/provider/json/provider.go new file mode 100644 index 0000000..bacf6c2 --- /dev/null +++ b/provider/json/provider.go @@ -0,0 +1,66 @@ +package json + +import ( + "context" + "fmt" + "io/ioutil" + "path/filepath" + + "github.com/tidwall/gjson" + "gitoa.ru/go-4devs/config" + "gitoa.ru/go-4devs/config/key" + "gitoa.ru/go-4devs/config/value" +) + +var _ config.Provider = (*Provider)(nil) + +func New(json []byte, opts ...Option) *Provider { + provider := Provider{ + key: key.Name, + data: json, + } + + for _, opt := range opts { + opt(&provider) + } + + return &provider +} + +func NewFile(path string, opts ...Option) (*Provider, error) { + file, err := ioutil.ReadFile(filepath.Clean(path)) + if err != nil { + return nil, fmt.Errorf("%w: unable to read config file %#q: file not found or unreadable", err, path) + } + + return New(file), nil +} + +type Option func(*Provider) + +type Provider struct { + data []byte + key config.KeyFactory +} + +func (p *Provider) IsSupport(ctx context.Context, key config.Key) bool { + return p.key(ctx, key) != "" +} + +func (p *Provider) Name() string { + return "json" +} + +func (p *Provider) Read(ctx context.Context, key config.Key) (config.Variable, error) { + path := p.key(ctx, key) + + if val := gjson.GetBytes(p.data, path); val.Exists() { + return config.Variable{ + Name: path, + Provider: p.Name(), + Value: value.JString(val.String()), + }, nil + } + + return config.Variable{}, config.ErrVariableNotFound +} diff --git a/provider/json/provider_test.go b/provider/json/provider_test.go new file mode 100644 index 0000000..c5fa00c --- /dev/null +++ b/provider/json/provider_test.go @@ -0,0 +1,27 @@ +package json_test + +import ( + "testing" + "time" + + provider "gitoa.ru/go-4devs/config/provider/json" + "gitoa.ru/go-4devs/config/test" +) + +func TestProvider(t *testing.T) { + t.Parallel() + + js := test.ReadFile("config.json") + + prov := provider.New(js) + sl := []string{} + read := []test.Read{ + test.NewRead("app.name.title", "config title"), + test.NewRead("app.name.timeout", time.Minute), + test.NewReadUnmarshal("app.name.var", &[]string{"name"}, &sl), + test.NewReadConfig("cfg"), + test.NewRead("app.name.success", true), + } + + test.Run(t, prov, read) +} diff --git a/provider/toml/provider.go b/provider/toml/provider.go new file mode 100644 index 0000000..9a149a9 --- /dev/null +++ b/provider/toml/provider.go @@ -0,0 +1,71 @@ +package toml + +import ( + "context" + "fmt" + + "github.com/pelletier/go-toml" + "gitoa.ru/go-4devs/config" + "gitoa.ru/go-4devs/config/key" + "gitoa.ru/go-4devs/config/value" +) + +var _ config.Provider = (*Provider)(nil) + +func NewFile(file string, opts ...Option) (*Provider, error) { + tree, err := toml.LoadFile(file) + if err != nil { + return nil, fmt.Errorf("toml: failed load file: %w", err) + } + + return configure(tree, opts...), nil +} + +type Option func(*Provider) + +func configure(tree *toml.Tree, opts ...Option) *Provider { + p := &Provider{ + tree: tree, + key: key.Name, + } + + for _, opt := range opts { + opt(p) + } + + return p +} + +func New(data []byte, opts ...Option) (*Provider, error) { + tree, err := toml.LoadBytes(data) + if err != nil { + return nil, fmt.Errorf("toml failed load data: %w", err) + } + + return configure(tree, opts...), nil +} + +type Provider struct { + tree *toml.Tree + key config.KeyFactory +} + +func (p *Provider) IsSupport(ctx context.Context, key config.Key) bool { + return p.key(ctx, key) != "" +} + +func (p *Provider) Name() string { + return "toml" +} + +func (p *Provider) Read(ctx context.Context, key config.Key) (config.Variable, error) { + if k := p.key(ctx, key); p.tree.Has(k) { + return config.Variable{ + Name: k, + Provider: p.Name(), + Value: Value{Value: value.Value{Val: p.tree.Get(k)}}, + }, nil + } + + return config.Variable{}, config.ErrVariableNotFound +} diff --git a/provider/toml/provider_test.go b/provider/toml/provider_test.go new file mode 100644 index 0000000..98cfe02 --- /dev/null +++ b/provider/toml/provider_test.go @@ -0,0 +1,29 @@ +package toml_test + +import ( + "testing" + + "github.com/stretchr/testify/require" + "gitoa.ru/go-4devs/config/provider/toml" + "gitoa.ru/go-4devs/config/test" +) + +func TestProvider(t *testing.T) { + t.Parallel() + + prov, err := toml.NewFile(test.FixturePath("config.toml")) + require.NoError(t, err) + + m := []int{} + + read := []test.Read{ + test.NewRead("database.server", "192.168.1.1"), + test.NewRead("title", "TOML Example"), + test.NewRead("servers.alpha.ip", "10.0.0.1"), + test.NewRead("database.enabled", true), + test.NewRead("database.connection_max", 5000), + test.NewReadUnmarshal("database.ports", &[]int{8001, 8001, 8002}, &m), + } + + test.Run(t, prov, read) +} diff --git a/provider/toml/value.go b/provider/toml/value.go new file mode 100644 index 0000000..cd310bd --- /dev/null +++ b/provider/toml/value.go @@ -0,0 +1,41 @@ +package toml + +import ( + "encoding/json" + "fmt" + + "gitoa.ru/go-4devs/config" + "gitoa.ru/go-4devs/config/value" +) + +type Value struct { + value.Value +} + +func (s Value) Int() int { + v, _ := s.ParseInt() + + return v +} + +func (s Value) ParseInt() (int, error) { + v, err := s.ParseInt64() + if err != nil { + return 0, fmt.Errorf("toml failed parce int: %w", err) + } + + return int(v), nil +} + +func (s Value) Unmarshal(target interface{}) error { + b, err := json.Marshal(s.Raw()) + if err != nil { + return fmt.Errorf("%w: %s", config.ErrInvalidValue, err) + } + + if err := json.Unmarshal(b, target); err != nil { + return fmt.Errorf("%w: %s", config.ErrInvalidValue, err) + } + + return nil +} diff --git a/provider/vault/secret.go b/provider/vault/secret.go new file mode 100644 index 0000000..cfe09e8 --- /dev/null +++ b/provider/vault/secret.go @@ -0,0 +1,90 @@ +package vault + +import ( + "context" + "encoding/json" + "fmt" + + "github.com/hashicorp/vault/api" + "gitoa.ru/go-4devs/config" + "gitoa.ru/go-4devs/config/key" + "gitoa.ru/go-4devs/config/value" +) + +var _ config.Provider = (*SecretKV2)(nil) + +type SecretOption func(*SecretKV2) + +func WithSecretResolve(f func(context.Context, config.Key) (string, string)) SecretOption { + return func(s *SecretKV2) { s.resolve = f } +} + +func NewSecretKV2(client *api.Client, opts ...SecretOption) *SecretKV2 { + s := SecretKV2{ + client: client, + resolve: key.LastIndexField(":", "value", key.PrefixName("secret/data/", key.NsAppName("/"))), + } + + for _, opt := range opts { + opt(&s) + } + + return &s +} + +type SecretKV2 struct { + client *api.Client + resolve func(ctx context.Context, key config.Key) (string, string) +} + +func (p *SecretKV2) IsSupport(ctx context.Context, key config.Key) bool { + path, _ := p.resolve(ctx, key) + + return path != "" +} + +func (p *SecretKV2) Name() string { + return "vault" +} + +func (p *SecretKV2) Read(ctx context.Context, key config.Key) (config.Variable, error) { + path, field := p.resolve(ctx, key) + + s, err := p.client.Logical().Read(path) + if err != nil { + return config.Variable{}, fmt.Errorf("%w: path:%s, field:%s, provider:%s", err, path, field, p.Name()) + } + + if s == nil || len(s.Data) == 0 { + return config.Variable{}, fmt.Errorf("%w: path:%s, field:%s, provider:%s", config.ErrVariableNotFound, path, field, p.Name()) + } + + if len(s.Warnings) > 0 { + return config.Variable{}, + fmt.Errorf("%w: warn: %s, path:%s, field:%s, provider:%s", config.ErrVariableNotFound, s.Warnings, path, field, p.Name()) + } + + d, ok := s.Data["data"].(map[string]interface{}) + if !ok { + return config.Variable{}, fmt.Errorf("%w: path:%s, field:%s, provider:%s", config.ErrVariableNotFound, path, field, p.Name()) + } + + if val, ok := d[field]; ok { + return config.Variable{ + Name: path + field, + Provider: p.Name(), + Value: value.JString(fmt.Sprint(val)), + }, nil + } + + md, err := json.Marshal(d) + if err != nil { + return config.Variable{}, fmt.Errorf("%w: %s", config.ErrInvalidValue, err) + } + + return config.Variable{ + Name: path + field, + Provider: p.Name(), + Value: value.JBytes(md), + }, nil +} diff --git a/provider/vault/secret_test.go b/provider/vault/secret_test.go new file mode 100644 index 0000000..330286f --- /dev/null +++ b/provider/vault/secret_test.go @@ -0,0 +1,26 @@ +package vault_test + +import ( + "testing" + "time" + + "github.com/stretchr/testify/require" + "gitoa.ru/go-4devs/config/provider/vault" + "gitoa.ru/go-4devs/config/test" +) + +func TestProvider(t *testing.T) { + t.Parallel() + + cl, err := test.NewVault() + require.NoError(t, err) + + provider := vault.NewSecretKV2(cl) + + read := []test.Read{ + test.NewReadConfig("database"), + test.NewRead("db:dsn", test.DSN), + test.NewRead("db:timeout", time.Minute), + } + test.Run(t, provider, read) +} diff --git a/provider/watcher/provider.go b/provider/watcher/provider.go new file mode 100644 index 0000000..6e4845e --- /dev/null +++ b/provider/watcher/provider.go @@ -0,0 +1,71 @@ +package watcher + +import ( + "context" + "fmt" + "log" + "time" + + "gitoa.ru/go-4devs/config" +) + +var ( + _ config.Provider = (*Provider)(nil) + _ config.WatchProvider = (*Provider)(nil) +) + +func New(duration time.Duration, provider config.Provider, opts ...Option) *Provider { + p := &Provider{ + Provider: provider, + ticker: time.NewTicker(duration), + logger: func(_ context.Context, msg string) { + log.Print(msg) + }, + } + + for _, opt := range opts { + opt(p) + } + + return p +} + +func WithLogger(l func(context.Context, string)) Option { + return func(p *Provider) { + p.logger = l + } +} + +type Option func(*Provider) + +type Provider struct { + config.Provider + ticker *time.Ticker + logger func(context.Context, string) +} + +func (p *Provider) Watch(ctx context.Context, key config.Key, callback config.WatchCallback) error { + oldVar, err := p.Provider.Read(ctx, key) + if err != nil { + return fmt.Errorf("%s: failed watch variable: %w", p.Provider.Name(), err) + } + + go func() { + for { + select { + case <-p.ticker.C: + newVar, err := p.Provider.Read(ctx, key) + if err != nil { + p.logger(ctx, err.Error()) + } else if !newVar.IsEquals(oldVar) { + callback(ctx, oldVar, newVar) + oldVar = newVar + } + case <-ctx.Done(): + return + } + } + }() + + return nil +} diff --git a/provider/watcher/provider_test.go b/provider/watcher/provider_test.go new file mode 100644 index 0000000..2cfaa6a --- /dev/null +++ b/provider/watcher/provider_test.go @@ -0,0 +1,58 @@ +package watcher_test + +import ( + "context" + "fmt" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/stretchr/testify/require" + "gitoa.ru/go-4devs/config" + "gitoa.ru/go-4devs/config/provider/watcher" + "gitoa.ru/go-4devs/config/value" +) + +type provider struct { + cnt int32 +} + +func (p *provider) Name() string { + return "test" +} + +func (p *provider) Read(ctx context.Context, k config.Key) (config.Variable, error) { + p.cnt++ + + return config.Variable{ + Name: "tmpname", + Value: value.JString(fmt.Sprint(p.cnt)), + }, nil +} + +func TestWatcher(t *testing.T) { + t.Parallel() + + ctx := context.Background() + prov := &provider{} + + w := watcher.New(time.Second, prov) + wg := sync.WaitGroup{} + wg.Add(2) + + var cnt int32 + + err := w.Watch( + ctx, + config.Key{Name: "tmpname"}, + func(ctx context.Context, oldVar, newVar config.Variable) { + atomic.AddInt32(&cnt, 1) + wg.Done() + }, + ) + require.NoError(t, err) + wg.Wait() + + require.Equal(t, int32(2), cnt) +} diff --git a/provider/yaml/file.go b/provider/yaml/file.go new file mode 100644 index 0000000..858fdee --- /dev/null +++ b/provider/yaml/file.go @@ -0,0 +1,57 @@ +package yaml + +import ( + "context" + "fmt" + "io/ioutil" + + "gitoa.ru/go-4devs/config" + "gopkg.in/yaml.v3" +) + +func WithFileKeyFactory(f func(context.Context, config.Key) []string) FileOption { + return func(p *File) { + p.key = f + } +} + +type FileOption func(*File) + +func NewFile(name string, opts ...FileOption) *File { + f := File{ + file: name, + key: keyFactory, + } + + for _, opt := range opts { + opt(&f) + } + + return &f +} + +type File struct { + file string + key func(context.Context, config.Key) []string +} + +func (p *File) Name() string { + return "yaml_file" +} + +func (p *File) Read(ctx context.Context, key config.Key) (config.Variable, error) { + in, err := ioutil.ReadFile(p.file) + if err != nil { + return config.Variable{}, fmt.Errorf("yaml_file: read error: %w", err) + } + + var n yaml.Node + if err = yaml.Unmarshal(in, &n); err != nil { + return config.Variable{}, fmt.Errorf("yaml_file: unmarshal error: %w", err) + } + + data := node{Node: &n} + k := p.key(ctx, key) + + return data.read(p.Name(), k) +} diff --git a/provider/yaml/provider.go b/provider/yaml/provider.go new file mode 100644 index 0000000..7e439ce --- /dev/null +++ b/provider/yaml/provider.go @@ -0,0 +1,88 @@ +package yaml + +import ( + "context" + "errors" + "fmt" + "strings" + + "gitoa.ru/go-4devs/config" + "gitoa.ru/go-4devs/config/value" + "gopkg.in/yaml.v3" +) + +var _ config.Provider = (*Provider)(nil) + +func keyFactory(ctx context.Context, key config.Key) []string { + return strings.Split(key.Name, "/") +} + +func New(yml []byte, opts ...Option) (*Provider, error) { + var data yaml.Node + if err := yaml.Unmarshal(yml, &data); err != nil { + return nil, fmt.Errorf("yaml: unmarshal err: %w", err) + } + + p := Provider{ + key: keyFactory, + data: node{Node: &data}, + } + + for _, opt := range opts { + opt(&p) + } + + return &p, nil +} + +type Option func(*Provider) + +type Provider struct { + data node + key func(context.Context, config.Key) []string +} + +func (p *Provider) Name() string { + return "yaml" +} + +func (p *Provider) Read(ctx context.Context, key config.Key) (config.Variable, error) { + k := p.key(ctx, key) + + return p.data.read(p.Name(), k) +} + +type node struct { + *yaml.Node +} + +func (n *node) read(name string, k []string) (config.Variable, error) { + val, err := getData(n.Node.Content[0].Content, k) + if err != nil { + if errors.Is(err, config.ErrVariableNotFound) { + return config.Variable{}, fmt.Errorf("%w: %s", config.ErrVariableNotFound, name) + } + + return config.Variable{}, fmt.Errorf("%w: %s", err, name) + } + + return config.Variable{ + Name: strings.Join(k, "."), + Provider: name, + Value: value.Decode(val), + }, nil +} + +func getData(node []*yaml.Node, keys []string) (func(interface{}) error, error) { + for i := len(node) - 1; i > 0; i -= 2 { + if node[i-1].Value == keys[0] { + if len(keys) > 1 { + return getData(node[i].Content, keys[1:]) + } + + return node[i].Decode, nil + } + } + + return nil, config.ErrVariableNotFound +} diff --git a/provider/yaml/provider_test.go b/provider/yaml/provider_test.go new file mode 100644 index 0000000..c4e970c --- /dev/null +++ b/provider/yaml/provider_test.go @@ -0,0 +1,26 @@ +package yaml_test + +import ( + "testing" + "time" + + "github.com/stretchr/testify/require" + provider "gitoa.ru/go-4devs/config/provider/yaml" + "gitoa.ru/go-4devs/config/test" +) + +func TestProvider(t *testing.T) { + t.Parallel() + + prov, err := provider.New(test.ReadFile("config.yaml")) + require.Nil(t, err) + + read := []test.Read{ + test.NewRead("duration_var", 21*time.Minute), + test.NewRead("app/name/bool_var", true), + test.NewRead("time_var", test.Time("2020-01-02T15:04:05Z")), + test.NewReadConfig("cfg"), + } + + test.Run(t, prov, read) +} diff --git a/test/etcd.go b/test/etcd.go new file mode 100644 index 0000000..3660749 --- /dev/null +++ b/test/etcd.go @@ -0,0 +1,46 @@ +package test + +import ( + "context" + "os" + "time" + + client "go.etcd.io/etcd/client/v3" +) + +func NewEtcd(ctx context.Context) (*client.Client, error) { + dsn, ok := os.LookupEnv("FDEVS_CONFIG_ETCD_HOST") + if !ok { + dsn = "127.0.0.1:2379" + } + + et, err := client.New(client.Config{ + Endpoints: []string{dsn}, + DialTimeout: time.Second, + }) + if err != nil { + return nil, err + } + + values := map[string]string{ + "fdevs/config/db_dsn": "pgsql://user@pass:127.0.0.1:5432", + "fdevs/config/duration": "12m", + "fdevs/config/port": "8080", + "fdevs/config/maintain": "true", + "fdevs/config/start_at": "2020-01-02T15:04:05Z", + "fdevs/config/percent": "0.064", + "fdevs/config/count": "2020", + "fdevs/config/int64": "2021", + "fdevs/config/uint64": "2022", + "fdevs/config/config": ConfigJSON, + } + + for name, val := range values { + _, err = et.KV.Put(ctx, name, val) + if err != nil { + return nil, err + } + } + + return et, nil +} diff --git a/test/fixture/config.ini b/test/fixture/config.ini new file mode 100644 index 0000000..6242149 --- /dev/null +++ b/test/fixture/config.ini @@ -0,0 +1,1038 @@ +; This file lists the default values used by Gitea +; Copy required sections to your own app.ini (default is custom/conf/app.ini) +; and modify as needed. + +; see https://docs.gitea.io/en-us/config-cheat-sheet/ for additional documentation. + +; App name that shows in every page title +APP_NAME = Gitea: Git with a cup of tea +; Change it if you run locally +RUN_USER = git +; Either "dev", "prod" or "test", default is "dev" +RUN_MODE = dev + +[project] +; Default templates for project boards +PROJECT_BOARD_BASIC_KANBAN_TYPE = To Do, In Progress, Done +PROJECT_BOARD_BUG_TRIAGE_TYPE = Needs Triage, High Priority, Low Priority, Closed + +[repository] +ROOT = +SCRIPT_TYPE = bash +; DETECTED_CHARSETS_ORDER tie-break order for detected charsets. +; If the charsets have equal confidence, tie-breaking will be done by order in this list +; with charsets earlier in the list chosen in preference to those later. +; Adding "defaults" will place the unused charsets at that position. +DETECTED_CHARSETS_ORDER=UTF-8, UTF-16BE, UTF-16LE, UTF-32BE, UTF-32LE, ISO-8859, windows-1252, ISO-8859, windows-1250, ISO-8859, ISO-8859, ISO-8859, windows-1253, ISO-8859, windows-1255, ISO-8859, windows-1251, windows-1256, KOI8-R, ISO-8859, windows-1254, Shift_JIS, GB18030, EUC-JP, EUC-KR, Big5, ISO-2022, ISO-2022, ISO-2022, IBM424_rtl, IBM424_ltr, IBM420_rtl, IBM420_ltr +; Default ANSI charset to override non-UTF-8 charsets to +ANSI_CHARSET = +; Force every new repository to be private +FORCE_PRIVATE = false +; Default privacy setting when creating a new repository, allowed values: last, private, public. Default is last which means the last setting used. +DEFAULT_PRIVATE = last +; Global limit of repositories per user, applied at creation time. -1 means no limit +MAX_CREATION_LIMIT = -1 +; Mirror sync queue length, increase if mirror syncing starts hanging +MIRROR_QUEUE_LENGTH = 1000 +; Patch test queue length, increase if pull request patch testing starts hanging +PULL_REQUEST_QUEUE_LENGTH = 1000 +; Preferred Licenses to place at the top of the List +; The name here must match the filename in conf/license or custom/conf/license +PREFERRED_LICENSES = Apache License 2.0,MIT License +; Disable the ability to interact with repositories using the HTTP protocol +DISABLE_HTTP_GIT = false +; Value for Access-Control-Allow-Origin header, default is not to present +; WARNING: This maybe harmful to you website if you do not give it a right value. +ACCESS_CONTROL_ALLOW_ORIGIN = +; Force ssh:// clone url instead of scp-style uri when default SSH port is used +USE_COMPAT_SSH_URI = false +; Close issues as long as a commit on any branch marks it as fixed +DEFAULT_CLOSE_ISSUES_VIA_COMMITS_IN_ANY_BRANCH = false +; Allow users to push local repositories to Gitea and have them automatically created for a user or an org +ENABLE_PUSH_CREATE_USER = false +ENABLE_PUSH_CREATE_ORG = false +; Comma separated list of globally disabled repo units. Allowed values: repo.issues, repo.ext_issues, repo.pulls, repo.wiki, repo.ext_wiki +DISABLED_REPO_UNITS = +; Comma separated list of default repo units. Allowed values: repo.code, repo.releases, repo.issues, repo.pulls, repo.wiki, repo.projects. +; Note: Code and Releases can currently not be deactivated. If you specify default repo units you should still list them for future compatibility. +; External wiki and issue tracker can't be enabled by default as it requires additional settings. +; Disabled repo units will not be added to new repositories regardless if it is in the default list. +DEFAULT_REPO_UNITS = repo.code,repo.releases,repo.issues,repo.pulls,repo.wiki,repo.projects +; Prefix archive files by placing them in a directory named after the repository +PREFIX_ARCHIVE_FILES = true +; Disable the creation of new mirrors. Pre-existing mirrors remain valid. +DISABLE_MIRRORS = false +; The default branch name of new repositories +DEFAULT_BRANCH=master + +[repository.editor] +; List of file extensions for which lines should be wrapped in the Monaco editor +; Separate extensions with a comma. To line wrap files without an extension, just put a comma +LINE_WRAP_EXTENSIONS = .txt,.md,.markdown,.mdown,.mkd, +; Valid file modes that have a preview API associated with them, such as api/v1/markdown +; Separate the values by commas. The preview tab in edit mode won't be displayed if the file extension doesn't match +PREVIEWABLE_FILE_MODES = markdown + +[repository.local] +; Path for local repository copy. Defaults to `tmp/local-repo` +LOCAL_COPY_PATH = tmp/local-repo +; Path for local wiki copy. Defaults to `tmp/local-wiki` +LOCAL_WIKI_PATH = tmp/local-wiki + +[repository.upload] +; Whether repository file uploads are enabled. Defaults to `true` +ENABLED = true +; Path for uploads. Defaults to `data/tmp/uploads` (tmp gets deleted on gitea restart) +TEMP_PATH = data/tmp/uploads +; One or more allowed types, e.g. image/jpeg|image/png. Nothing means any file type +ALLOWED_TYPES = +; Max size of each file in megabytes. Defaults to 3MB +FILE_MAX_SIZE = 3 +; Max number of files per upload. Defaults to 5 +MAX_FILES = 5 + +[repository.pull-request] +; List of prefixes used in Pull Request title to mark them as Work In Progress +WORK_IN_PROGRESS_PREFIXES=WIP:,[WIP] +; List of keywords used in Pull Request comments to automatically close a related issue +CLOSE_KEYWORDS=close,closes,closed,fix,fixes,fixed,resolve,resolves,resolved +; List of keywords used in Pull Request comments to automatically reopen a related issue +REOPEN_KEYWORDS=reopen,reopens,reopened +; In the default merge message for squash commits include at most this many commits +DEFAULT_MERGE_MESSAGE_COMMITS_LIMIT=50 +; In the default merge message for squash commits limit the size of the commit messages to this +DEFAULT_MERGE_MESSAGE_SIZE=5120 +; In the default merge message for squash commits walk all commits to include all authors in the Co-authored-by otherwise just use those in the limited list +DEFAULT_MERGE_MESSAGE_ALL_AUTHORS=false +; In default merge messages limit the number of approvers listed as Reviewed-by: to this many +DEFAULT_MERGE_MESSAGE_MAX_APPROVERS=10 +; In default merge messages only include approvers who are official +DEFAULT_MERGE_MESSAGE_OFFICIAL_APPROVERS_ONLY=true + +[repository.issue] +; List of reasons why a Pull Request or Issue can be locked +LOCK_REASONS=Too heated,Off-topic,Resolved,Spam + +[repository.signing] +; GPG key to use to sign commits, Defaults to the default - that is the value of git config --get user.signingkey +; run in the context of the RUN_USER +; Switch to none to stop signing completely +SIGNING_KEY = default +; If a SIGNING_KEY ID is provided and is not set to default, use the provided Name and Email address as the signer. +; These should match a publicized name and email address for the key. (When SIGNING_KEY is default these are set to +; the results of git config --get user.name and git config --get user.email respectively and can only be overrided +; by setting the SIGNING_KEY ID to the correct ID.) +SIGNING_NAME = +SIGNING_EMAIL = +; Determines when gitea should sign the initial commit when creating a repository +; Either: +; - never +; - pubkey: only sign if the user has a pubkey +; - twofa: only sign if the user has logged in with twofa +; - always +; options other than none and always can be combined as comma separated list +INITIAL_COMMIT = always +; Determines when to sign for CRUD actions +; - as above +; - parentsigned: requires that the parent commit is signed. +CRUD_ACTIONS = pubkey, twofa, parentsigned +; Determines when to sign Wiki commits +; - as above +WIKI = never +; Determines when to sign on merges +; - basesigned: require that the parent of commit on the base repo is signed. +; - commitssigned: require that all the commits in the head branch are signed. +; - approved: only sign when merging an approved pr to a protected branch +MERGES = pubkey, twofa, basesigned, commitssigned + +[cors] +; More information about CORS can be found here: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#The_HTTP_response_headers +; enable cors headers (disabled by default) +ENABLED=false +; scheme of allowed requests +SCHEME=http +; list of requesting domains that are allowed +ALLOW_DOMAIN=* +; allow subdomains of headers listed above to request +ALLOW_SUBDOMAIN=false +; list of methods allowed to request +METHODS=GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS +; max time to cache response +MAX_AGE=10m +; allow request with credentials +ALLOW_CREDENTIALS=false + +[ui] +; Number of repositories that are displayed on one explore page +EXPLORE_PAGING_NUM = 20 +; Number of issues that are displayed on one page +ISSUE_PAGING_NUM = 10 +; Number of maximum commits displayed in one activity feed +FEED_MAX_COMMIT_NUM = 5 +; Number of items that are displayed in home feed +FEED_PAGING_NUM = 20 +; Number of maximum commits displayed in commit graph. +GRAPH_MAX_COMMIT_NUM = 100 +; Number of line of codes shown for a code comment +CODE_COMMENT_LINES = 4 +; Value of `theme-color` meta tag, used by Android >= 5.0 +; An invalid color like "none" or "disable" will have the default style +; More info: https://developers.google.com/web/updates/2014/11/Support-for-theme-color-in-Chrome-39-for-Android +THEME_COLOR_META_TAG = `#6cc644` +; Max size of files to be displayed (default is 8MiB) +MAX_DISPLAY_FILE_SIZE = 8388608 +; Whether the email of the user should be shown in the Explore Users page +SHOW_USER_EMAIL = true +; Set the default theme for the Gitea install +DEFAULT_THEME = gitea +; All available themes. Allow users select personalized themes regardless of the value of `DEFAULT_THEME`. +THEMES = gitea,arc-green +;All available reactions users can choose on issues/prs and comments. +;Values can be emoji alias (:smile:) or a unicode emoji. +;For custom reactions, add a tightly cropped square image to public/emoji/img/reaction_name.png +REACTIONS = +1, -1, laugh, hooray, confused, heart, rocket, eyes +; Whether the full name of the users should be shown where possible. If the full name isn't set, the username will be used. +DEFAULT_SHOW_FULL_NAME = false +; Whether to search within description at repository search on explore page. +SEARCH_REPO_DESCRIPTION = true +; Whether to enable a Service Worker to cache frontend assets +USE_SERVICE_WORKER = true + +[ui.admin] +; Number of users that are displayed on one page +USER_PAGING_NUM = 50 +; Number of repos that are displayed on one page +REPO_PAGING_NUM = 50 +; Number of notices that are displayed on one page +NOTICE_PAGING_NUM = 25 +; Number of organizations that are displayed on one page +ORG_PAGING_NUM = 50 + +[ui.user] +; Number of repos that are displayed on one page +REPO_PAGING_NUM = 15 + +[ui.meta] +AUTHOR = Gitea - Git with a cup of tea +DESCRIPTION = Gitea (Git with a cup of tea) is a painless self-hosted Git service written in Go +KEYWORDS = go,git,self-hosted,gitea + +[ui.notification] +; Control how often the notification endpoint is polled to update the notification +; The timeout will increase to MAX_TIMEOUT in TIMEOUT_STEPs if the notification count is unchanged +; Set MIN_TIMEOUT to 0 to turn off +MIN_TIMEOUT = 10s +MAX_TIMEOUT = 60s +TIMEOUT_STEP = 10s +; This setting determines how often the db is queried to get the latest notification counts. +; If the browser client supports EventSource and SharedWorker, a SharedWorker will be used in preference to polling notification. Set to -1 to disable the EventSource +EVENT_SOURCE_UPDATE_TIME = 10s + +[markdown] +; Render soft line breaks as hard line breaks, which means a single newline character between +; paragraphs will cause a line break and adding trailing whitespace to paragraphs is not +; necessary to force a line break. +; Render soft line breaks as hard line breaks for comments +ENABLE_HARD_LINE_BREAK_IN_COMMENTS = true +; Render soft line breaks as hard line breaks for markdown documents +ENABLE_HARD_LINE_BREAK_IN_DOCUMENTS = false +; Comma separated list of custom URL-Schemes that are allowed as links when rendering Markdown +; for example git,magnet,ftp (more at https://en.wikipedia.org/wiki/List_of_URI_schemes) +; URLs starting with http and https are always displayed, whatever is put in this entry. +CUSTOM_URL_SCHEMES = +; List of file extensions that should be rendered/edited as Markdown +; Separate the extensions with a comma. To render files without any extension as markdown, just put a comma +FILE_EXTENSIONS = .md,.markdown,.mdown,.mkd + +[server] +; The protocol the server listens on. One of 'http', 'https', 'unix' or 'fcgi'. +PROTOCOL = http +DOMAIN = localhost +ROOT_URL = %(PROTOCOL)s://%(DOMAIN)s:%(HTTP_PORT)s/ +; when STATIC_URL_PREFIX is empty it will follow ROOT_URL +STATIC_URL_PREFIX = +; The address to listen on. Either a IPv4/IPv6 address or the path to a unix socket. +HTTP_ADDR = 0.0.0.0 +; The port to listen on. Leave empty when using a unix socket. +HTTP_PORT = 3000 +; If REDIRECT_OTHER_PORT is true, and PROTOCOL is set to https an http server +; will be started on PORT_TO_REDIRECT and it will redirect plain, non-secure http requests to the main +; ROOT_URL. Defaults are false for REDIRECT_OTHER_PORT and 80 for +; PORT_TO_REDIRECT. +REDIRECT_OTHER_PORT = false +PORT_TO_REDIRECT = 80 +; Permission for unix socket +UNIX_SOCKET_PERMISSION = 666 +; Local (DMZ) URL for Gitea workers (such as SSH update) accessing web service. +; In most cases you do not need to change the default value. +; Alter it only if your SSH server node is not the same as HTTP node. +; Do not set this variable if PROTOCOL is set to 'unix'. +LOCAL_ROOT_URL = %(PROTOCOL)s://%(HTTP_ADDR)s:%(HTTP_PORT)s/ +; Disable SSH feature when not available +DISABLE_SSH = false +; Whether to use the builtin SSH server or not. +START_SSH_SERVER = false +; Username to use for the builtin SSH server. If blank, then it is the value of RUN_USER. +BUILTIN_SSH_SERVER_USER = +; Domain name to be exposed in clone URL +SSH_DOMAIN = %(DOMAIN)s +; The network interface the builtin SSH server should listen on +SSH_LISTEN_HOST = +; Port number to be exposed in clone URL +SSH_PORT = 22 +; The port number the builtin SSH server should listen on +SSH_LISTEN_PORT = %(SSH_PORT)s +; Root path of SSH directory, default is '~/.ssh', but you have to use '/home/git/.ssh'. +SSH_ROOT_PATH = +; Gitea will create a authorized_keys file by default when it is not using the internal ssh server +; If you intend to use the AuthorizedKeysCommand functionality then you should turn this off. +SSH_CREATE_AUTHORIZED_KEYS_FILE = true +; For the built-in SSH server, choose the ciphers to support for SSH connections, +; for system SSH this setting has no effect +SSH_SERVER_CIPHERS = aes128-ctr, aes192-ctr, aes256-ctr, aes128-gcm@openssh.com, arcfour256, arcfour128 +; For the built-in SSH server, choose the key exchange algorithms to support for SSH connections, +; for system SSH this setting has no effect +SSH_SERVER_KEY_EXCHANGES = diffie-hellman-group1-sha1, diffie-hellman-group14-sha1, ecdh-sha2-nistp256, ecdh-sha2-nistp384, ecdh-sha2-nistp521, curve25519-sha256@libssh.org +; For the built-in SSH server, choose the MACs to support for SSH connections, +; for system SSH this setting has no effect +SSH_SERVER_MACS = hmac-sha2-256-etm@openssh.com, hmac-sha2-256, hmac-sha1, hmac-sha1-96 +; Directory to create temporary files in when testing public keys using ssh-keygen, +; default is the system temporary directory. +SSH_KEY_TEST_PATH = +; Path to ssh-keygen, default is 'ssh-keygen' which means the shell is responsible for finding out which one to call. +SSH_KEYGEN_PATH = ssh-keygen +; Enable SSH Authorized Key Backup when rewriting all keys, default is true +SSH_BACKUP_AUTHORIZED_KEYS = true +; Enable exposure of SSH clone URL to anonymous visitors, default is false +SSH_EXPOSE_ANONYMOUS = false +; Indicate whether to check minimum key size with corresponding type +MINIMUM_KEY_SIZE_CHECK = false +; Disable CDN even in "prod" mode +OFFLINE_MODE = false +DISABLE_ROUTER_LOG = false +; Generate steps: +; $ ./gitea cert -ca=true -duration=8760h0m0s -host=myhost.example.com +; +; Or from a .pfx file exported from the Windows certificate store (do +; not forget to export the private key): +; $ openssl pkcs12 -in cert.pfx -out cert.pem -nokeys +; $ openssl pkcs12 -in cert.pfx -out key.pem -nocerts -nodes +; Paths are relative to CUSTOM_PATH +CERT_FILE = https/cert.pem +KEY_FILE = https/key.pem +; Root directory containing templates and static files. +; default is the path where Gitea is executed +STATIC_ROOT_PATH = +; Default path for App data +APP_DATA_PATH = data +; Application level GZIP support +ENABLE_GZIP = false +; Application profiling (memory and cpu) +; For "web" command it listens on localhost:6060 +; For "serve" command it dumps to disk at PPROF_DATA_PATH as (cpuprofile|memprofile)__ +ENABLE_PPROF = false +; PPROF_DATA_PATH, use an absolute path when you start gitea as service +PPROF_DATA_PATH = data/tmp/pprof +; Landing page, can be "home", "explore", "organizations" or "login" +; The "login" choice is not a security measure but just a UI flow change, use REQUIRE_SIGNIN_VIEW to force users to log in. +LANDING_PAGE = home +; Enables git-lfs support. true or false, default is false. +LFS_START_SERVER = false +; Where your lfs files reside, default is data/lfs. +LFS_CONTENT_PATH = data/lfs +; LFS authentication secret, change this yourself +LFS_JWT_SECRET = +; LFS authentication validity period (in time.Duration), pushes taking longer than this may fail. +LFS_HTTP_AUTH_EXPIRY = 20m +; Maximum allowed LFS file size in bytes (Set to 0 for no limit). +LFS_MAX_FILE_SIZE = 0 +; Maximum number of locks returned per page +LFS_LOCKS_PAGING_NUM = 50 +; Allow graceful restarts using SIGHUP to fork +ALLOW_GRACEFUL_RESTARTS = true +; After a restart the parent will finish ongoing requests before +; shutting down. Force shutdown if this process takes longer than this delay. +; set to a negative value to disable +GRACEFUL_HAMMER_TIME = 60s +; Allows the setting of a startup timeout and waithint for Windows as SVC service +; 0 disables this. +STARTUP_TIMEOUT = 0 +; Static resources, includes resources on custom/, public/ and all uploaded avatars web browser cache time, default is 6h +STATIC_CACHE_TIME = 6h + +; Define allowed algorithms and their minimum key length (use -1 to disable a type) +[ssh.minimum_key_sizes] +ED25519 = 256 +ECDSA = 256 +RSA = 2048 +DSA = 1024 + +[database] +; Database to use. Either "mysql", "postgres", "mssql" or "sqlite3". +DB_TYPE = mysql +HOST = 127.0.0.1:3306 +NAME = gitea +USER = root +; Use PASSWD = `your password` for quoting if you use special characters in the password. +PASSWD = +; For Postgres, schema to use if different from "public". The schema must exist beforehand, +; the user must have creation privileges on it, and the user search path must be set +; to the look into the schema first. e.g.:ALTER USER user SET SEARCH_PATH = schema_name,"$user",public; +SCHEMA = +; For Postgres, either "disable" (default), "require", or "verify-full" +; For MySQL, either "false" (default), "true", or "skip-verify" +SSL_MODE = disable +; For MySQL only, either "utf8" or "utf8mb4", default is "utf8mb4". +; NOTICE: for "utf8mb4" you must use MySQL InnoDB > 5.6. Gitea is unable to check this. +CHARSET = utf8mb4 +; For "sqlite3" and "tidb", use an absolute path when you start gitea as service +PATH = data/gitea.db +; For "sqlite3" only. Query timeout +SQLITE_TIMEOUT = 500 +; For iterate buffer, default is 50 +ITERATE_BUFFER_SIZE = 50 +; Show the database generated SQL +LOG_SQL = true +; Maximum number of DB Connect retries +DB_RETRIES = 10 +; Backoff time per DB retry (time.Duration) +DB_RETRY_BACKOFF = 3s +; Max idle database connections on connnection pool, default is 2 +MAX_IDLE_CONNS = 2 +; Database connection max life time, default is 0 or 3s mysql (See #6804 & #7071 for reasoning) +CONN_MAX_LIFETIME = 3s +; Database maximum number of open connections, default is 0 meaning no maximum +MAX_OPEN_CONNS = 0 + +[indexer] +; Issue indexer type, currently support: bleve, db or elasticsearch, default is bleve +ISSUE_INDEXER_TYPE = bleve +; Issue indexer connection string, available when ISSUE_INDEXER_TYPE is elasticsearch +ISSUE_INDEXER_CONN_STR = http://elastic:changeme@localhost:9200 +; Issue indexer name, available when ISSUE_INDEXER_TYPE is elasticsearch +ISSUE_INDEXER_NAME = gitea_issues +; Issue indexer storage path, available when ISSUE_INDEXER_TYPE is bleve +ISSUE_INDEXER_PATH = indexers/issues.bleve +; Issue indexer queue, currently support: channel, levelqueue or redis, default is levelqueue +ISSUE_INDEXER_QUEUE_TYPE = levelqueue +; When ISSUE_INDEXER_QUEUE_TYPE is levelqueue, this will be the queue will be saved path, +; default is indexers/issues.queue +ISSUE_INDEXER_QUEUE_DIR = indexers/issues.queue +; When `ISSUE_INDEXER_QUEUE_TYPE` is `redis`, this will store the redis connection string. +ISSUE_INDEXER_QUEUE_CONN_STR = "addrs=127.0.0.1:6379 db=0" +; Batch queue number, default is 20 +ISSUE_INDEXER_QUEUE_BATCH_NUMBER = 20 +; Timeout the indexer if it takes longer than this to start. +; Set to zero to disable timeout. +STARTUP_TIMEOUT=30s + +; repo indexer by default disabled, since it uses a lot of disk space +REPO_INDEXER_ENABLED = false +REPO_INDEXER_PATH = indexers/repos.bleve +UPDATE_BUFFER_LEN = 20 +MAX_FILE_SIZE = 1048576 +; A comma separated list of glob patterns (see https://github.com/gobwas/glob) to include +; in the index; default is empty +REPO_INDEXER_INCLUDE = +; A comma separated list of glob patterns to exclude from the index; ; default is empty +REPO_INDEXER_EXCLUDE = + +[queue] +; Specific queues can be individually configured with [queue.name]. [queue] provides defaults +; +; General queue queue type, currently support: persistable-channel, channel, level, redis, dummy +; default to persistable-channel +TYPE = persistable-channel +; data-dir for storing persistable queues and level queues, individual queues will be named by their type +DATADIR = queues/ +; Default queue length before a channel queue will block +LENGTH = 20 +; Batch size to send for batched queues +BATCH_LENGTH = 20 +; Connection string for redis queues this will store the redis connection string. +CONN_STR = "addrs=127.0.0.1:6379 db=0" +; Provide the suffix of the default redis queue name - specific queues can be overriden within in their [queue.name] sections. +QUEUE_NAME = "_queue" +; If the queue cannot be created at startup - level queues may need a timeout at startup - wrap the queue: +WRAP_IF_NECESSARY = true +; Attempt to create the wrapped queue at max +MAX_ATTEMPTS = 10 +; Timeout queue creation +TIMEOUT = 15m30s +; Create a pool with this many workers +WORKERS = 1 +; Dynamically scale the worker pool to at this many workers +MAX_WORKERS = 10 +; Add boost workers when the queue blocks for BLOCK_TIMEOUT +BLOCK_TIMEOUT = 1s +; Remove the boost workers after BOOST_TIMEOUT +BOOST_TIMEOUT = 5m +; During a boost add BOOST_WORKERS +BOOST_WORKERS = 5 + +[admin] +; Disallow regular (non-admin) users from creating organizations. +DISABLE_REGULAR_ORG_CREATION = false +; Default configuration for email notifications for users (user configurable). Options: enabled, onmention, disabled +DEFAULT_EMAIL_NOTIFICATIONS = enabled + +[security] +; Whether the installer is disabled +INSTALL_LOCK = false +; !!CHANGE THIS TO KEEP YOUR USER DATA SAFE!! +SECRET_KEY = !#@FDEWREWR&*( +; How long to remember that a user is logged in before requiring relogin (in days) +LOGIN_REMEMBER_DAYS = 7 +COOKIE_USERNAME = gitea_awesome +COOKIE_REMEMBER_NAME = gitea_incredible +; Reverse proxy authentication header name of user name +REVERSE_PROXY_AUTHENTICATION_USER = X-WEBAUTH-USER +REVERSE_PROXY_AUTHENTICATION_EMAIL = X-WEBAUTH-EMAIL +; The minimum password length for new Users +MIN_PASSWORD_LENGTH = 6 +; Set to true to allow users to import local server paths +IMPORT_LOCAL_PATHS = false +; Set to true to prevent all users (including admin) from creating custom git hooks +DISABLE_GIT_HOOKS = false +; Set to false to allow pushes to gitea repositories despite having an incomplete environment - NOT RECOMMENDED +ONLY_ALLOW_PUSH_IF_GITEA_ENVIRONMENT_SET = true +;Comma separated list of character classes required to pass minimum complexity. +;If left empty or no valid values are specified, the default is off (no checking) +;Classes include "lower,upper,digit,spec" +PASSWORD_COMPLEXITY = off +; Password Hash algorithm, either "pbkdf2", "argon2", "scrypt" or "bcrypt" +PASSWORD_HASH_ALGO = pbkdf2 +; Set false to allow JavaScript to read CSRF cookie +CSRF_COOKIE_HTTP_ONLY = true + +[openid] +; +; OpenID is an open, standard and decentralized authentication protocol. +; Your identity is the address of a webpage you provide, which describes +; how to prove you are in control of that page. +; +; For more info: https://en.wikipedia.org/wiki/OpenID +; +; Current implementation supports OpenID-2.0 +; +; Tested to work providers at the time of writing: +; - Any GNUSocial node (your.hostname.tld/username) +; - Any SimpleID provider (http://simpleid.koinic.net) +; - http://openid.org.cn/ +; - openid.stackexchange.com +; - login.launchpad.net +; - .livejournal.com +; +; Whether to allow signin in via OpenID +ENABLE_OPENID_SIGNIN = true +; Whether to allow registering via OpenID +; Do not include to rely on rhw DISABLE_REGISTRATION setting +;ENABLE_OPENID_SIGNUP = true +; Allowed URI patterns (POSIX regexp). +; Space separated. +; Only these would be allowed if non-blank. +; Example value: trusted.domain.org trusted.domain.net +WHITELISTED_URIS = +; Forbidden URI patterns (POSIX regexp). +; Space separated. +; Only used if WHITELISTED_URIS is blank. +; Example value: loadaverage.org/badguy stackexchange.com/.*spammer +BLACKLISTED_URIS = + +[service] +; Time limit to confirm account/email registration +ACTIVE_CODE_LIVE_MINUTES = 180 +; Time limit to perform the reset of a forgotten password +RESET_PASSWD_CODE_LIVE_MINUTES = 180 +; Whether a new user needs to confirm their email when registering. +REGISTER_EMAIL_CONFIRM = false +; List of domain names that are allowed to be used to register on a Gitea instance +; gitea.io,example.com +EMAIL_DOMAIN_WHITELIST= +; Disallow registration, only allow admins to create accounts. +DISABLE_REGISTRATION = false +; Allow registration only using third-party services, it works only when DISABLE_REGISTRATION is false +ALLOW_ONLY_EXTERNAL_REGISTRATION = false +; User must sign in to view anything. +REQUIRE_SIGNIN_VIEW = false +; Mail notification +ENABLE_NOTIFY_MAIL = false +; This setting enables gitea to be signed in with HTTP BASIC Authentication using the user's password +; If you set this to false you will not be able to access the tokens endpoints on the API with your password +; Please note that setting this to false will not disable OAuth Basic or Basic authentication using a token +ENABLE_BASIC_AUTHENTICATION = true +; More detail: https://github.com/gogits/gogs/issues/165 +ENABLE_REVERSE_PROXY_AUTHENTICATION = false +ENABLE_REVERSE_PROXY_AUTO_REGISTRATION = false +ENABLE_REVERSE_PROXY_EMAIL = false +; Enable captcha validation for registration +ENABLE_CAPTCHA = false +; Type of captcha you want to use. Options: image, recaptcha +CAPTCHA_TYPE = image +; Enable recaptcha to use Google's recaptcha service +; Go to https://www.google.com/recaptcha/admin to sign up for a key +RECAPTCHA_SECRET = +RECAPTCHA_SITEKEY = +; Change this to use recaptcha.net or other recaptcha service +RECAPTCHA_URL = https://www.google.com/recaptcha/ +; Default value for KeepEmailPrivate +; Each new user will get the value of this setting copied into their profile +DEFAULT_KEEP_EMAIL_PRIVATE = false +; Default value for AllowCreateOrganization +; Every new user will have rights set to create organizations depending on this setting +DEFAULT_ALLOW_CREATE_ORGANIZATION = true +; Either "public", "limited" or "private", default is "public" +; Limited is for signed user only +; Private is only for member of the organization +; Public is for everyone +DEFAULT_ORG_VISIBILITY = public +; Default value for DefaultOrgMemberVisible +; True will make the membership of the users visible when added to the organisation +DEFAULT_ORG_MEMBER_VISIBLE = false +; Default value for EnableDependencies +; Repositories will use dependencies by default depending on this setting +DEFAULT_ENABLE_DEPENDENCIES = true +; Dependencies can be added from any repository where the user is granted access or only from the current repository depending on this setting. +ALLOW_CROSS_REPOSITORY_DEPENDENCIES = true +; Enable heatmap on users profiles. +ENABLE_USER_HEATMAP = true +; Enable Timetracking +ENABLE_TIMETRACKING = true +; Default value for EnableTimetracking +; Repositories will use timetracking by default depending on this setting +DEFAULT_ENABLE_TIMETRACKING = true +; Default value for AllowOnlyContributorsToTrackTime +; Only users with write permissions can track time if this is true +DEFAULT_ALLOW_ONLY_CONTRIBUTORS_TO_TRACK_TIME = true +; Default value for the domain part of the user's email address in the git log +; if he has set KeepEmailPrivate to true. The user's email will be replaced with a +; concatenation of the user name in lower case, "@" and NO_REPLY_ADDRESS. +NO_REPLY_ADDRESS = noreply.%(DOMAIN)s +; Show Registration button +SHOW_REGISTRATION_BUTTON = true +; Show milestones dashboard page - a view of all the user's milestones +SHOW_MILESTONES_DASHBOARD_PAGE = true +; Default value for AutoWatchNewRepos +; When adding a repo to a team or creating a new repo all team members will watch the +; repo automatically if enabled +AUTO_WATCH_NEW_REPOS = true +; Default value for AutoWatchOnChanges +; Make the user watch a repository When they commit for the first time +AUTO_WATCH_ON_CHANGES = false + +[webhook] +; Hook task queue length, increase if webhook shooting starts hanging +QUEUE_LENGTH = 1000 +; Deliver timeout in seconds +DELIVER_TIMEOUT = 5 +; Allow insecure certification +SKIP_TLS_VERIFY = false +; Number of history information in each page +PAGING_NUM = 10 +; Proxy server URL, support http://, https//, socks://, blank will follow environment http_proxy/https_proxy +PROXY_URL = +; Comma separated list of host names requiring proxy. Glob patterns (*) are accepted; use ** to match all hosts. +PROXY_HOSTS = + +[mailer] +ENABLED = false +; Buffer length of channel, keep it as it is if you don't know what it is. +SEND_BUFFER_LEN = 100 +; Prefix displayed before subject in mail +SUBJECT_PREFIX = +; Mail server +; Gmail: smtp.gmail.com:587 +; QQ: smtp.qq.com:465 +; Using STARTTLS on port 587 is recommended per RFC 6409. +; Note, if the port ends with "465", SMTPS will be used. +HOST = +; Disable HELO operation when hostnames are different. +DISABLE_HELO = +; Custom hostname for HELO operation, if no value is provided, one is retrieved from system. +HELO_HOSTNAME = +; Whether or not to skip verification of certificates; `true` to disable verification. This option is unsafe. Consider adding the certificate to the system trust store instead. +SKIP_VERIFY = false +; Use client certificate +USE_CERTIFICATE = false +CERT_FILE = custom/mailer/cert.pem +KEY_FILE = custom/mailer/key.pem +; Should SMTP connect with TLS, (if port ends with 465 TLS will always be used.) +; If this is false but STARTTLS is supported the connection will be upgraded to TLS opportunistically. +IS_TLS_ENABLED = false +; Mail from address, RFC 5322. This can be just an email address, or the `"Name" ` format +FROM = +; Mailer user name and password +; Please Note: Authentication is only supported when the SMTP server communication is encrypted with TLS (this can be via STARTTLS) or `HOST=localhost`. +USER = +; Use PASSWD = `your password` for quoting if you use special characters in the password. +PASSWD = +; Send mails as plain text +SEND_AS_PLAIN_TEXT = false +; Set Mailer Type (either SMTP, sendmail or dummy to just send to the log) +MAILER_TYPE = smtp +; Specify an alternative sendmail binary +SENDMAIL_PATH = sendmail +; Specify any extra sendmail arguments +SENDMAIL_ARGS = +; Timeout for Sendmail +SENDMAIL_TIMEOUT = 5m + +[cache] +; if the cache enabled +ENABLED = true +; Either "memory", "redis", or "memcache", default is "memory" +ADAPTER = memory +; For "memory" only, GC interval in seconds, default is 60 +INTERVAL = 60 +; For "redis" and "memcache", connection host address +; redis: network=tcp,addr=:6379,password=macaron,db=0,pool_size=100,idle_timeout=180 +; memcache: `127.0.0.1:11211` +HOST = +; Time to keep items in cache if not used, default is 16 hours. +; Setting it to 0 disables caching +ITEM_TTL = 16h + +; Last commit cache +[cache.last_commit] +; if the cache enabled +ENABLED = true +; Time to keep items in cache if not used, default is 8760 hours. +; Setting it to 0 disables caching +ITEM_TTL = 8760h +; Only enable the cache when repository's commits count great than +COMMITS_COUNT = 1000 + +[session] +; Either "memory", "file", or "redis", default is "memory" +PROVIDER = memory +; Provider config options +; memory: doesn't have any config yet +; file: session file path, e.g. `data/sessions` +; redis: network=tcp,addr=:6379,password=macaron,db=0,pool_size=100,idle_timeout=180 +; mysql: go-sql-driver/mysql dsn config string, e.g. `root:password@/session_table` +PROVIDER_CONFIG = data/sessions +; Session cookie name +COOKIE_NAME = i_like_gitea +; If you use session in https only, default is false +COOKIE_SECURE = false +; Enable set cookie, default is true +ENABLE_SET_COOKIE = true +; Session GC time interval in seconds, default is 86400 (1 day) +GC_INTERVAL_TIME = 86400 +; Session life time in seconds, default is 86400 (1 day) +SESSION_LIFE_TIME = 86400 + +[picture] +AVATAR_UPLOAD_PATH = data/avatars +REPOSITORY_AVATAR_UPLOAD_PATH = data/repo-avatars +; How Gitea deals with missing repository avatars +; none = no avatar will be displayed; random = random avatar will be displayed; image = default image will be used +REPOSITORY_AVATAR_FALLBACK = none +REPOSITORY_AVATAR_FALLBACK_IMAGE = /img/repo_default.png +; Max Width and Height of uploaded avatars. +; This is to limit the amount of RAM used when resizing the image. +AVATAR_MAX_WIDTH = 4096 +AVATAR_MAX_HEIGHT = 3072 +; Maximum alloved file size for uploaded avatars. +; This is to limit the amount of RAM used when resizing the image. +AVATAR_MAX_FILE_SIZE = 1048576 +; Chinese users can choose "duoshuo" +; or a custom avatar source, like: http://cn.gravatar.com/avatar/ +GRAVATAR_SOURCE = gravatar +; This value will always be true in offline mode. +DISABLE_GRAVATAR = false +; Federated avatar lookup uses DNS to discover avatar associated +; with emails, see https://www.libravatar.org +; This value will always be false in offline mode or when Gravatar is disabled. +ENABLE_FEDERATED_AVATAR = false + +[attachment] +; Whether attachments are enabled. Defaults to `true` +ENABLED = true + +; One or more allowed types, e.g. "image/jpeg|image/png". Use "*/*" for all types. +ALLOWED_TYPES = image/jpeg|image/png|application/zip|application/gzip +; Max size of each file. Defaults to 4MB +MAX_SIZE = 4 +; Max number of files per upload. Defaults to 5 +MAX_FILES = 5 +; Storage type for attachments, `local` for local disk or `minio` for s3 compatible +; object storage service, default is `local`. +STORE_TYPE = local +; Allows the storage driver to redirect to authenticated URLs to serve files directly +; Currently, only `minio` is supported. +SERVE_DIRECT = false +; Path for attachments. Defaults to `data/attachments` only available when STORE_TYPE is `local` +PATH = data/attachments +; Minio endpoint to connect only available when STORE_TYPE is `minio` +MINIO_ENDPOINT = localhost:9000 +; Minio accessKeyID to connect only available when STORE_TYPE is `minio` +MINIO_ACCESS_KEY_ID = +; Minio secretAccessKey to connect only available when STORE_TYPE is `minio` +MINIO_SECRET_ACCESS_KEY = +; Minio bucket to store the attachments only available when STORE_TYPE is `minio` +MINIO_BUCKET = gitea +; Minio location to create bucket only available when STORE_TYPE is `minio` +MINIO_LOCATION = us-east-1 +; Minio base path on the bucket only available when STORE_TYPE is `minio` +MINIO_BASE_PATH = attachments/ +; Minio enabled ssl only available when STORE_TYPE is `minio` +MINIO_USE_SSL = false + +[time] +; Specifies the format for fully outputted dates. Defaults to RFC1123 +; Special supported values are ANSIC, UnixDate, RubyDate, RFC822, RFC822Z, RFC850, RFC1123, RFC1123Z, RFC3339, RFC3339Nano, Kitchen, Stamp, StampMilli, StampMicro and StampNano +; For more information about the format see http://golang.org/pkg/time/#pkg-constants +FORMAT = +; Location the UI time display i.e. Asia/Shanghai +; Empty means server's location setting +DEFAULT_UI_LOCATION = + +[log] +ROOT_PATH = +; Either "console", "file", "conn", "smtp" or "database", default is "console" +; Use comma to separate multiple modes, e.g. "console, file" +MODE = console +; Buffer length of the channel, keep it as it is if you don't know what it is. +BUFFER_LEN = 10000 +REDIRECT_MACARON_LOG = false +MACARON = file +; Either "Trace", "Debug", "Info", "Warn", "Error", "Critical", default is "Info" +ROUTER_LOG_LEVEL = Info +ROUTER = console +ENABLE_ACCESS_LOG = false +ACCESS_LOG_TEMPLATE = {{.Ctx.RemoteAddr}} - {{.Identity}} {{.Start.Format "[02/Jan/2006:15:04:05 -0700]" }} "{{.Ctx.Req.Method}} {{.Ctx.Req.RequestURI}} {{.Ctx.Req.Proto}}" {{.ResponseWriter.Status}} {{.ResponseWriter.Size}} "{{.Ctx.Req.Referer}}\" \"{{.Ctx.Req.UserAgent}}" +ACCESS = file +; Either "Trace", "Debug", "Info", "Warn", "Error", "Critical", default is "Trace" +LEVEL = Info +; Either "Trace", "Debug", "Info", "Warn", "Error", "Critical", default is "None" +STACKTRACE_LEVEL = None + +; Generic log modes +[log.x] +FLAGS = stdflags +EXPRESSION = +PREFIX = +COLORIZE = false + +; For "console" mode only +[log.console] +LEVEL = +STDERR = false + +; For "file" mode only +[log.file] +LEVEL = +; Set the file_name for the logger. If this is a relative path this +; will be relative to ROOT_PATH +FILE_NAME = +; This enables automated log rotate(switch of following options), default is true +LOG_ROTATE = true +; Max number of lines in a single file, default is 1000000 +MAX_LINES = 1000000 +; Max size shift of a single file, default is 28 means 1 << 28, 256MB +MAX_SIZE_SHIFT = 28 +; Segment log daily, default is true +DAILY_ROTATE = true +; delete the log file after n days, default is 7 +MAX_DAYS = 7 +; compress logs with gzip +COMPRESS = true +; compression level see godoc for compress/gzip +COMPRESSION_LEVEL = -1 + +; For "conn" mode only +[log.conn] +LEVEL = +; Reconnect host for every single message, default is false +RECONNECT_ON_MSG = false +; Try to reconnect when connection is lost, default is false +RECONNECT = false +; Either "tcp", "unix" or "udp", default is "tcp" +PROTOCOL = tcp +; Host address +ADDR = + +; For "smtp" mode only +[log.smtp] +LEVEL = +; Name displayed in mail title, default is "Diagnostic message from server" +SUBJECT = Diagnostic message from server +; Mail server +HOST = +; Mailer user name and password +USER = +; Use PASSWD = `your password` for quoting if you use special characters in the password. +PASSWD = +; Receivers, can be one or more, e.g. 1@example.com,2@example.com +RECEIVERS = + +[cron] +; Enable running cron tasks periodically. +ENABLED = true +; Run cron tasks when Gitea starts. +RUN_AT_START = false + +; Update mirrors +[cron.update_mirrors] +SCHEDULE = @every 10m + +; Repository health check +[cron.repo_health_check] +SCHEDULE = @every 24h +TIMEOUT = 60s +; Arguments for command 'git fsck', e.g. "--unreachable --tags" +; see more on http://git-scm.com/docs/git-fsck +ARGS = + +; Check repository statistics +[cron.check_repo_stats] +RUN_AT_START = true +SCHEDULE = @every 24h + +; Clean up old repository archives +[cron.archive_cleanup] +; Whether to enable the job +ENABLED = true +; Whether to always run at least once at start up time (if ENABLED) +RUN_AT_START = true +; Time interval for job to run +SCHEDULE = @every 24h +; Archives created more than OLDER_THAN ago are subject to deletion +OLDER_THAN = 24h + +; Synchronize external user data (only LDAP user synchronization is supported) +[cron.sync_external_users] +; Synchronize external user data when starting server (default false) +RUN_AT_START = false +; Interval as a duration between each synchronization (default every 24h) +SCHEDULE = @every 24h +; Create new users, update existing user data and disable users that are not in external source anymore (default) +; or only create new users if UPDATE_EXISTING is set to false +UPDATE_EXISTING = true + +; Update migrated repositories' issues and comments' posterid, it will always attempt synchronization when the instance starts. +[cron.update_migration_poster_id] +; Interval as a duration between each synchronization. (default every 24h) +SCHEDULE = @every 24h + +[git] +; The path of git executable. If empty, Gitea searches through the PATH environment. +PATH = +; Disables highlight of added and removed changes +DISABLE_DIFF_HIGHLIGHT = false +; Max number of lines allowed in a single file in diff view +MAX_GIT_DIFF_LINES = 1000 +; Max number of allowed characters in a line in diff view +MAX_GIT_DIFF_LINE_CHARACTERS = 5000 +; Max number of files shown in diff view +MAX_GIT_DIFF_FILES = 100 +; Arguments for command 'git gc', e.g. "--aggressive --auto" +; see more on http://git-scm.com/docs/git-gc/ +GC_ARGS = +; If use git wire protocol version 2 when git version >= 2.18, default is true, set to false when you always want git wire protocol version 1 +ENABLE_AUTO_GIT_WIRE_PROTOCOL = true +; Respond to pushes to a non-default branch with a URL for creating a Pull Request (if the repository has them enabled) +PULL_REQUEST_PUSH_MESSAGE = true + +; Operation timeout in seconds +[git.timeout] +DEFAULT = 360 +MIGRATE = 600 +MIRROR = 300 +CLONE = 300 +PULL = 300 +GC = 60 + +[mirror] +; Default interval as a duration between each check +DEFAULT_INTERVAL = 8h +; Min interval as a duration must be > 1m +MIN_INTERVAL = 10m + +[api] +; Enables Swagger. True or false; default is true. +ENABLE_SWAGGER = true +; Max number of items in a page +MAX_RESPONSE_ITEMS = 50 +; Default paging number of api +DEFAULT_PAGING_NUM = 30 +; Default and maximum number of items per page for git trees api +DEFAULT_GIT_TREES_PER_PAGE = 1000 +; Default size of a blob returned by the blobs API (default is 10MiB) +DEFAULT_MAX_BLOB_SIZE = 10485760 + +[oauth2] +; Enables OAuth2 provider +ENABLE = true +; Lifetime of an OAuth2 access token in seconds +ACCESS_TOKEN_EXPIRATION_TIME=3600 +; Lifetime of an OAuth2 access token in hours +REFRESH_TOKEN_EXPIRATION_TIME=730 +; Check if refresh token got already used +INVALIDATE_REFRESH_TOKENS=false +; OAuth2 authentication secret for access and refresh tokens, change this yourself to a unique string. CLI generate option is helpful in this case. https://docs.gitea.io/en-us/command-line/#generate +JWT_SECRET= +; Maximum length of oauth2 token/cookie stored on server +MAX_TOKEN_LENGTH=32767 + +[i18n] +LANGS = en-US,zh-CN,zh-HK,zh-TW,de-DE,fr-FR,nl-NL,lv-LV,ru-RU,uk-UA,ja-JP,es-ES,pt-BR,pt-PT,pl-PL,bg-BG,it-IT,fi-FI,tr-TR,cs-CZ,sr-SP,sv-SE,ko-KR +NAMES = English,简体中文,繁體中文(香港),繁體中文(台灣),Deutsch,français,Nederlands,latviešu,русский,Українська,日本語,español,português do Brasil,Português de Portugal,polski,български,italiano,suomi,Türkçe,čeština,српски,svenska,한국어 + +[U2F] +; NOTE: THE DEFAULT VALUES HERE WILL NEED TO BE CHANGED +; Two Factor authentication with security keys +; https://developers.yubico.com/U2F/App_ID.html +;APP_ID = http://localhost:3000/ +; Comma separated list of trusted facets +;TRUSTED_FACETS = http://localhost:3000/ + +; Extension mapping to highlight class +; e.g. .toml=ini +[highlight.mapping] + +[other] +SHOW_FOOTER_BRANDING = false +; Show version information about Gitea and Go in the footer +SHOW_FOOTER_VERSION = true +; Show template execution time in the footer +SHOW_FOOTER_TEMPLATE_LOAD_TIME = true + +[markup.sanitizer.1] +; The following keys can appear once to define a sanitation policy rule. +; This section can appear multiple times by adding a unique alphanumeric suffix to define multiple rules. +; e.g., [markup.sanitizer.1] -> [markup.sanitizer.2] -> [markup.sanitizer.TeX] +;ELEMENT = span +;ALLOW_ATTR = class +;REGEXP = ^(info|warning|error)$ + +[markup.asciidoc] +ENABLED = false +; List of file extensions that should be rendered by an external command +FILE_EXTENSIONS = .adoc,.asciidoc +; External command to render all matching extensions +RENDER_COMMAND = "asciidoc --out-file=- -" +; Don't pass the file on STDIN, pass the filename as argument instead. +IS_INPUT_FILE = false + +[metrics] +; Enables metrics endpoint. True or false; default is false. +ENABLED = false +; If you want to add authorization, specify a token here +TOKEN = + +[task] +; Task queue type, could be `channel` or `redis`. +QUEUE_TYPE = channel +; Task queue length, available only when `QUEUE_TYPE` is `channel`. +QUEUE_LENGTH = 1000 +; Task queue connection string, available only when `QUEUE_TYPE` is `redis`. +; If there is a password of redis, use `addrs=127.0.0.1:6379 password=123 db=0`. +QUEUE_CONN_STR = "addrs=127.0.0.1:6379 db=0" + +[migrations] +; Max attempts per http/https request on migrations. +MAX_ATTEMPTS = 3 +; Backoff time per http/https request retry (seconds) +RETRY_BACKOFF = 3 \ No newline at end of file diff --git a/test/fixture/config.json b/test/fixture/config.json new file mode 100644 index 0000000..86a672f --- /dev/null +++ b/test/fixture/config.json @@ -0,0 +1,16 @@ +{ + "app": { + "name": { + "var": [ + "name" + ], + "title": "config title", + "timeout": "1m", + "success": true + } + }, + "cfg": { + "duration": 1260000000000, + "enabled": true + } +} \ No newline at end of file diff --git a/test/fixture/config.toml b/test/fixture/config.toml new file mode 100644 index 0000000..493429e --- /dev/null +++ b/test/fixture/config.toml @@ -0,0 +1,31 @@ +title = "TOML Example" + +[owner] +name = "Tom Preston-Werner" +dob = 1979-05-27T07:32:00-08:00 # First class dates + +[database] +server = "192.168.1.1" +ports = [ 8001, 8001, 8002 ] +connection_max = 5000 +enabled = true + +[servers] + + # Indentation (tabs and/or spaces) is allowed but not required + [servers.alpha] + ip = "10.0.0.1" + dc = "eqdc10" + + [servers.beta] + ip = "10.0.0.2" + dc = "eqdc10" + +[clients] +data = [ ["gamma", "delta"], [1, 2] ] + +# Line breaks are OK when inside arrays +hosts = [ + "alpha", + "omega" +] \ No newline at end of file diff --git a/test/fixture/config.yaml b/test/fixture/config.yaml new file mode 100644 index 0000000..4ee47a0 --- /dev/null +++ b/test/fixture/config.yaml @@ -0,0 +1,12 @@ +app: + name: + var: + - test + bool_var: true +duration_var: 21m +empty_var: +url_var: "http://google.com/" +time_var: "2020-01-02T15:04:05Z" +cfg: + duration: 21m + enabled: true diff --git a/test/helpers.go b/test/helpers.go new file mode 100644 index 0000000..979b354 --- /dev/null +++ b/test/helpers.go @@ -0,0 +1,17 @@ +package test + +import ( + "path/filepath" + "runtime" +) + +func FixturePath(file string) string { + path := "fixture/" + + _, filename, _, ok := runtime.Caller(0) + if ok { + path = filepath.Dir(filename) + "/" + path + } + + return path + file +} diff --git a/test/ini.go b/test/ini.go new file mode 100644 index 0000000..89e3f3d --- /dev/null +++ b/test/ini.go @@ -0,0 +1,16 @@ +package test + +import ( + "log" + + "gopkg.in/ini.v1" +) + +func NewINI() *ini.File { + f, err := ini.Load(FixturePath("config.ini")) + if err != nil { + log.Fatal(err) + } + + return f +} diff --git a/test/json.go b/test/json.go new file mode 100644 index 0000000..dbed18f --- /dev/null +++ b/test/json.go @@ -0,0 +1,15 @@ +package test + +import ( + "io/ioutil" + "log" +) + +func ReadFile(file string) []byte { + data, err := ioutil.ReadFile(FixturePath(file)) + if err != nil { + log.Fatal(err) + } + + return data +} diff --git a/test/provider_suite.go b/test/provider_suite.go new file mode 100644 index 0000000..7635c79 --- /dev/null +++ b/test/provider_suite.go @@ -0,0 +1,150 @@ +package test + +import ( + "context" + "io/ioutil" + "path/filepath" + "testing" + "time" + + "github.com/stretchr/testify/require" + "github.com/stretchr/testify/suite" + "gitoa.ru/go-4devs/config" +) + +const ( + DSN = "pgsql://user@pass:127.0.0.1:5432" + Namespace = "fdevs" + AppName = "config" +) + +func Run(t *testing.T, provider config.Provider, read []Read) { + t.Helper() + + prov := &ProviderSuite{ + provider: provider, + read: read, + } + suite.Run(t, prov) +} + +type ProviderSuite struct { + suite.Suite + provider config.Provider + read []Read +} + +type Read struct { + Key config.Key + Assert func(t *testing.T, v config.Value) +} + +const ConfigJSON = `{"duration":1260000000000,"enabled":true}` + +type Config struct { + Duration time.Duration + Enabled bool +} + +func NewReadConfig(key string) Read { + ex := &Config{ + Duration: 21 * time.Minute, + Enabled: true, + } + + return NewReadUnmarshal(key, ex, &Config{}) +} + +func NewReadUnmarshal(key string, expected, target interface{}) Read { + return Read{ + Key: config.Key{ + Namespace: "fdevs", + AppName: "config", + Name: key, + }, + Assert: func(t *testing.T, v config.Value) { + t.Helper() + require.NoErrorf(t, v.Unmarshal(target), "unmarshal") + require.Equal(t, expected, target, "unmarshal") + }, + } +} + +func Time(value string) time.Time { + t, _ := time.Parse(time.RFC3339, value) + + return t +} + +// nolint: cyclop +func NewRead(key string, expected interface{}) Read { + return Read{ + Key: config.Key{ + Namespace: "fdevs", + AppName: "config", + Name: key, + }, + Assert: func(t *testing.T, v config.Value) { + t.Helper() + var ( + val interface{} + err error + short interface{} + ) + switch expected.(type) { + case bool: + val, err = v.ParseBool() + short = v.Bool() + case int: + val, err = v.ParseInt() + short = v.Int() + case int64: + val, err = v.ParseInt64() + short = v.Int64() + case uint: + val, err = v.ParseUint() + short = v.Uint() + case uint64: + val, err = v.ParseUint64() + short = v.Uint64() + case string: + val, err = v.ParseString() + short = v.String() + case float64: + val, err = v.ParseFloat64() + short = v.Float64() + case time.Duration: + val, err = v.ParseDuration() + short = v.Duration() + case time.Time: + val, err = v.ParseTime() + short = v.Time() + default: + require.Fail(t, "unexpected type", "type:%+T", expected) + } + + require.Equalf(t, val, short, "type:%T", expected) + require.NoErrorf(t, err, "type:%T", expected) + require.Equalf(t, expected, val, "type:%T", expected) + }, + } +} + +func (ps *ProviderSuite) TestReadKeys() { + ctx := context.Background() + + for _, read := range ps.read { + val, err := ps.provider.Read(ctx, read.Key) + require.NoError(ps.T(), err, read.Key.String()) + read.Assert(ps.T(), val.Value) + } +} + +func LoadConfig(t *testing.T, path string) []byte { + t.Helper() + + file, err := ioutil.ReadFile(filepath.Clean(path)) + require.NoError(t, err) + + return file +} diff --git a/test/vault.go b/test/vault.go new file mode 100644 index 0000000..fd29a50 --- /dev/null +++ b/test/vault.go @@ -0,0 +1,89 @@ +package test + +import ( + "bytes" + "context" + "encoding/json" + "net/http" + "os" + + "github.com/hashicorp/vault/api" +) + +const token = "dev" + +func NewVault() (*api.Client, error) { + address, ok := os.LookupEnv("VAULT_DEV_LISTEN_ADDRESS") + if !ok { + address = "http://127.0.0.1:8200" + } + + tokenID, ok := os.LookupEnv("VAULT_DEV_ROOT_TOKEN_ID") + if !ok { + tokenID = token + } + + cl, err := api.NewClient(&api.Config{ + Address: address, + }) + if err != nil { + return nil, err + } + + cl.SetToken(tokenID) + + values := map[string]map[string]interface{}{ + "database": { + "duration": 1260000000000, + "enabled": true, + }, + "db": { + "dsn": DSN, + "timeout": "60s", + }, + "example": { + "dsn": DSN, + "timeout": "60s", + }, + } + + for name, val := range values { + if err := create(address, tokenID, name, val); err != nil { + return nil, err + } + } + + return cl, nil +} + +func create(host, token, path string, data map[string]interface{}) error { + type Req struct { + Data interface{} `json:"data"` + } + + b, err := json.Marshal(Req{Data: data}) + if err != nil { + return err + } + + body := bytes.NewBuffer(b) + + req, err := http.NewRequestWithContext( + context.Background(), + http.MethodPost, + host+"/v1/secret/data/fdevs/config/"+path, + body, + ) + if err != nil { + return err + } + + req.Header.Set("X-Vault-Token", token) + + res, err := http.DefaultClient.Do(req) + if err != nil { + return err + } + + return res.Body.Close() +} diff --git a/value.go b/value.go new file mode 100644 index 0000000..8d9e86e --- /dev/null +++ b/value.go @@ -0,0 +1,39 @@ +package config + +import ( + "time" +) + +type Value interface { + ReadValue + ParseValue + UnmarshalValue +} + +type UnmarshalValue interface { + Unmarshal(val interface{}) error +} + +type ReadValue interface { + String() string + Int() int + Int64() int64 + Uint() uint + Uint64() uint64 + Float64() float64 + Bool() bool + Duration() time.Duration + Time() time.Time +} + +type ParseValue interface { + ParseString() (string, error) + ParseInt() (int, error) + ParseInt64() (int64, error) + ParseUint() (uint, error) + ParseUint64() (uint64, error) + ParseFloat64() (float64, error) + ParseBool() (bool, error) + ParseDuration() (time.Duration, error) + ParseTime() (time.Time, error) +} diff --git a/value/decode.go b/value/decode.go new file mode 100644 index 0000000..6c30114 --- /dev/null +++ b/value/decode.go @@ -0,0 +1,109 @@ +package value + +import ( + "time" + + "gitoa.ru/go-4devs/config" +) + +var _ config.Value = (*Decode)(nil) + +type Decode func(v interface{}) error + +func (s Decode) Unmarshal(v interface{}) error { + return s(v) +} + +func (s Decode) ParseInt() (v int, err error) { + return v, s.Unmarshal(&v) +} + +func (s Decode) ParseInt64() (v int64, err error) { + return v, s.Unmarshal(&v) +} + +func (s Decode) ParseUint() (v uint, err error) { + return v, s.Unmarshal(&v) +} + +func (s Decode) ParseUint64() (v uint64, err error) { + return v, s.Unmarshal(&v) +} + +func (s Decode) ParseFloat64() (v float64, err error) { + return v, s.Unmarshal(&v) +} + +func (s Decode) ParseString() (v string, err error) { + return v, s.Unmarshal(&v) +} + +func (s Decode) ParseDuration() (v time.Duration, err error) { + return v, s.Unmarshal(&v) +} + +func (s Decode) ParseTime() (v time.Time, err error) { + return v, s.Unmarshal(&v) +} + +func (s Decode) Int() int { + in, _ := s.ParseInt() + + return in +} + +func (s Decode) Int64() int64 { + in, _ := s.ParseInt64() + + return in +} + +func (s Decode) Uint() uint { + in, _ := s.ParseUint() + + return in +} + +func (s Decode) Uint64() uint64 { + in, _ := s.ParseUint64() + + return in +} + +func (s Decode) Float64() float64 { + in, _ := s.ParseFloat64() + + return in +} + +func (s Decode) Bytes() []byte { + return []byte(s.String()) +} + +func (s Decode) String() string { + v, _ := s.ParseString() + + return v +} + +func (s Decode) Bool() bool { + in, _ := s.ParseBool() + + return in +} + +func (s Decode) ParseBool() (v bool, err error) { + return v, s.Unmarshal(&v) +} + +func (s Decode) Duration() time.Duration { + in, _ := s.ParseDuration() + + return in +} + +func (s Decode) Time() time.Time { + in, _ := s.ParseTime() + + return in +} diff --git a/value/empty.go b/value/empty.go new file mode 100644 index 0000000..dac3e27 --- /dev/null +++ b/value/empty.go @@ -0,0 +1,85 @@ +package value + +import ( + "time" +) + +type Empty struct { + Err error +} + +func (e Empty) Unmarshal(val interface{}) error { + return e.Err +} + +func (e Empty) ParseString() (string, error) { + return "", e.Err +} + +func (e Empty) ParseInt() (int, error) { + return 0, e.Err +} + +func (e Empty) ParseInt64() (int64, error) { + return 0, e.Err +} + +func (e Empty) ParseUint() (uint, error) { + return 0, e.Err +} + +func (e Empty) ParseUint64() (uint64, error) { + return 0, e.Err +} + +func (e Empty) ParseFloat64() (float64, error) { + return 0, e.Err +} + +func (e Empty) ParseBool() (bool, error) { + return false, e.Err +} + +func (e Empty) ParseDuration() (time.Duration, error) { + return 0, e.Err +} + +func (e Empty) ParseTime() (time.Time, error) { + return time.Time{}, e.Err +} + +func (e Empty) String() string { + return "" +} + +func (e Empty) Int() int { + return 0 +} + +func (e Empty) Int64() int64 { + return 0 +} + +func (e Empty) Uint() uint { + return 0 +} + +func (e Empty) Uint64() uint64 { + return 0 +} + +func (e Empty) Float64() float64 { + return 0 +} + +func (e Empty) Bool() bool { + return false +} + +func (e Empty) Duration() time.Duration { + return 0 +} + +func (e Empty) Time() time.Time { + return time.Time{} +} diff --git a/value/helpers.go b/value/helpers.go new file mode 100644 index 0000000..e03bed7 --- /dev/null +++ b/value/helpers.go @@ -0,0 +1,81 @@ +package value + +import ( + "encoding/json" + "fmt" + "strconv" + "time" + + "gitoa.ru/go-4devs/config" +) + +func ParseDuration(raw string) (time.Duration, error) { + d, err := time.ParseDuration(raw) + if err != nil { + return 0, fmt.Errorf("%w: %s", config.ErrInvalidValue, err) + } + + return d, nil +} + +func ParseInt(s string) (int64, error) { + i, err := strconv.ParseInt(s, 10, 64) + if err != nil { + return 0, fmt.Errorf("%w: %s", config.ErrInvalidValue, err) + } + + return i, nil +} + +func ParseUint(s string) (uint64, error) { + i, err := strconv.ParseUint(s, 10, 64) + if err != nil { + return 0, fmt.Errorf("%w: %s", config.ErrInvalidValue, err) + } + + return i, nil +} + +func Atoi(s string) (int, error) { + i, err := strconv.Atoi(s) + if err != nil { + return 0, fmt.Errorf("%w: %s", config.ErrInvalidValue, err) + } + + return i, nil +} + +func ParseTime(s string) (time.Time, error) { + i, err := time.Parse(time.RFC3339, s) + if err != nil { + return time.Time{}, fmt.Errorf("%w: %s", config.ErrInvalidValue, err) + } + + return i, nil +} + +func ParseFloat(s string) (float64, error) { + f, err := strconv.ParseFloat(s, 64) + if err != nil { + return 0, fmt.Errorf("%w: %s", config.ErrInvalidValue, err) + } + + return f, nil +} + +func ParseBool(s string) (bool, error) { + b, err := strconv.ParseBool(s) + if err != nil { + return false, fmt.Errorf("%w: %s", config.ErrInvalidValue, err) + } + + return b, nil +} + +func JUnmarshal(b []byte, v interface{}) error { + if err := json.Unmarshal(b, v); err != nil { + return fmt.Errorf("%w: %s", config.ErrInvalidValue, err) + } + + return nil +} diff --git a/value/jbytes.go b/value/jbytes.go new file mode 100644 index 0000000..d500db3 --- /dev/null +++ b/value/jbytes.go @@ -0,0 +1,112 @@ +package value + +import ( + "time" + + "gitoa.ru/go-4devs/config" +) + +var _ config.Value = (*JBytes)(nil) + +type JBytes []byte + +func (s JBytes) Unmarshal(v interface{}) error { + return JUnmarshal(s.Bytes(), v) +} + +func (s JBytes) ParseString() (string, error) { + return s.String(), nil +} + +func (s JBytes) ParseInt() (int, error) { + return Atoi(s.String()) +} + +func (s JBytes) ParseInt64() (int64, error) { + return ParseInt(s.String()) +} + +func (s JBytes) ParseUint() (uint, error) { + u64, err := ParseUint(s.String()) + if err != nil { + return 0, err + } + + return uint(u64), nil +} + +func (s JBytes) ParseUint64() (uint64, error) { + return ParseUint(s.String()) +} + +func (s JBytes) ParseFloat64() (float64, error) { + return ParseFloat(s.String()) +} + +func (s JBytes) ParseBool() (bool, error) { + return ParseBool(s.String()) +} + +func (s JBytes) ParseDuration() (time.Duration, error) { + return ParseDuration(s.String()) +} + +func (s JBytes) ParseTime() (time.Time, error) { + return ParseTime(s.String()) +} + +func (s JBytes) Bytes() []byte { + return []byte(s) +} + +func (s JBytes) String() string { + return string(s) +} + +func (s JBytes) Int() int { + in, _ := s.ParseInt() + + return in +} + +func (s JBytes) Int64() int64 { + in, _ := s.ParseInt64() + + return in +} + +func (s JBytes) Uint() uint { + in, _ := s.ParseUint() + + return in +} + +func (s JBytes) Uint64() uint64 { + in, _ := s.ParseUint64() + + return in +} + +func (s JBytes) Float64() float64 { + in, _ := s.ParseFloat64() + + return in +} + +func (s JBytes) Bool() bool { + in, _ := s.ParseBool() + + return in +} + +func (s JBytes) Duration() time.Duration { + in, _ := s.ParseDuration() + + return in +} + +func (s JBytes) Time() time.Time { + in, _ := s.ParseTime() + + return in +} diff --git a/value/jstring.go b/value/jstring.go new file mode 100644 index 0000000..fa80cb7 --- /dev/null +++ b/value/jstring.go @@ -0,0 +1,112 @@ +package value + +import ( + "time" + + "gitoa.ru/go-4devs/config" +) + +var _ config.Value = (*JString)(nil) + +type JString string + +func (s JString) Unmarshal(v interface{}) error { + return JUnmarshal(s.Bytes(), v) +} + +func (s JString) ParseString() (string, error) { + return s.String(), nil +} + +func (s JString) ParseInt() (int, error) { + return Atoi(s.String()) +} + +func (s JString) ParseInt64() (int64, error) { + return ParseInt(s.String()) +} + +func (s JString) ParseUint() (uint, error) { + u64, err := ParseUint(s.String()) + if err != nil { + return 0, err + } + + return uint(u64), nil +} + +func (s JString) ParseUint64() (uint64, error) { + return ParseUint(s.String()) +} + +func (s JString) ParseFloat64() (float64, error) { + return ParseFloat(s.String()) +} + +func (s JString) ParseBool() (bool, error) { + return ParseBool(s.String()) +} + +func (s JString) ParseDuration() (time.Duration, error) { + return ParseDuration(s.String()) +} + +func (s JString) ParseTime() (time.Time, error) { + return ParseTime(s.String()) +} + +func (s JString) Bytes() []byte { + return []byte(s) +} + +func (s JString) String() string { + return string(s) +} + +func (s JString) Int() int { + in, _ := s.ParseInt() + + return in +} + +func (s JString) Int64() int64 { + in, _ := s.ParseInt64() + + return in +} + +func (s JString) Uint() uint { + in, _ := s.ParseUint() + + return in +} + +func (s JString) Uint64() uint64 { + in, _ := s.ParseUint64() + + return in +} + +func (s JString) Float64() float64 { + in, _ := s.ParseFloat64() + + return in +} + +func (s JString) Bool() bool { + in, _ := s.ParseBool() + + return in +} + +func (s JString) Duration() time.Duration { + in, _ := s.ParseDuration() + + return in +} + +func (s JString) Time() time.Time { + in, _ := s.ParseTime() + + return in +} diff --git a/value/jstring_test.go b/value/jstring_test.go new file mode 100644 index 0000000..f43820a --- /dev/null +++ b/value/jstring_test.go @@ -0,0 +1,37 @@ +package value_test + +import ( + "errors" + "testing" + "time" + + "github.com/stretchr/testify/require" + "gitoa.ru/go-4devs/config" + "gitoa.ru/go-4devs/config/value" +) + +func TestStringDuration(t *testing.T) { + t.Parallel() + + tests := map[string]struct { + raw value.JString + exp time.Duration + err error + }{ + "1m": { + raw: value.JString("1m"), + exp: time.Minute, + }, + "number error": { + raw: value.JString("100000000"), + err: config.ErrInvalidValue, + }, + } + + for name, data := range tests { + require.Equal(t, data.exp, data.raw.Duration(), name) + d, err := data.raw.ParseDuration() + require.Truef(t, errors.Is(err, data.err), "%[1]s: expect:%#[2]v, got:%#[3]v", name, data.err, err) + require.Equal(t, data.exp, d, name) + } +} diff --git a/value/value.go b/value/value.go new file mode 100644 index 0000000..ac0f24b --- /dev/null +++ b/value/value.go @@ -0,0 +1,158 @@ +package value + +import ( + "encoding/json" + "fmt" + "time" + + "gitoa.ru/go-4devs/config" +) + +var _ config.Value = (*Value)(nil) + +type Value struct { + Val interface{} +} + +func (s Value) Int() int { + v, _ := s.ParseInt() + + return v +} + +func (s Value) Int64() int64 { + v, _ := s.ParseInt64() + + return v +} + +func (s Value) Uint() uint { + v, _ := s.ParseUint() + + return v +} + +func (s Value) Uint64() uint64 { + v, _ := s.ParseUint64() + + return v +} + +func (s Value) Float64() float64 { + in, _ := s.ParseFloat64() + + return in +} + +func (s Value) String() string { + v, _ := s.ParseString() + + return v +} + +func (s Value) Bool() bool { + v, _ := s.ParseBool() + + return v +} + +func (s Value) Duration() time.Duration { + v, _ := s.ParseDuration() + + return v +} + +func (s Value) Raw() interface{} { + return s.Val +} + +func (s Value) Time() time.Time { + v, _ := s.ParseTime() + + return v +} + +func (s Value) Unmarshal(target interface{}) error { + if v, ok := s.Raw().([]byte); ok { + err := json.Unmarshal(v, target) + if err != nil { + return fmt.Errorf("%w: %s", config.ErrInvalidValue, err) + } + + return nil + } + + return config.ErrInvalidValue +} + +func (s Value) ParseInt() (int, error) { + if r, ok := s.Raw().(int); ok { + return r, nil + } + + return 0, config.ErrInvalidValue +} + +func (s Value) ParseInt64() (int64, error) { + if r, ok := s.Raw().(int64); ok { + return r, nil + } + + return 0, config.ErrInvalidValue +} + +func (s Value) ParseUint() (uint, error) { + if r, ok := s.Raw().(uint); ok { + return r, nil + } + + return 0, config.ErrInvalidValue +} + +func (s Value) ParseUint64() (uint64, error) { + if r, ok := s.Raw().(uint64); ok { + return r, nil + } + + return 0, config.ErrInvalidValue +} + +func (s Value) ParseFloat64() (float64, error) { + if r, ok := s.Raw().(float64); ok { + return r, nil + } + + return 0, config.ErrInvalidValue +} + +func (s Value) ParseString() (string, error) { + if r, ok := s.Raw().(string); ok { + return r, nil + } + + return "", config.ErrInvalidValue +} + +func (s Value) ParseBool() (bool, error) { + if b, ok := s.Raw().(bool); ok { + return b, nil + } + + return false, config.ErrInvalidValue +} + +func (s Value) ParseDuration() (time.Duration, error) { + if b, ok := s.Raw().(time.Duration); ok { + return b, nil + } + + return 0, config.ErrInvalidValue +} + +func (s Value) ParseTime() (time.Time, error) { + if b, ok := s.Raw().(time.Time); ok { + return b, nil + } + + return time.Time{}, config.ErrInvalidValue +} diff --git a/variable.go b/variable.go new file mode 100644 index 0000000..ae31d3d --- /dev/null +++ b/variable.go @@ -0,0 +1,11 @@ +package config + +type Variable struct { + Name string + Provider string + Value Value +} + +func (v Variable) IsEquals(n Variable) bool { + return n.Name == v.Name && n.Provider == v.Provider && n.Value.String() == v.Value.String() +}