settings section

This commit is contained in:
2026-07-04 18:34:30 +05:00
parent bbe5d219ad
commit 0c717101da
2867 changed files with 1118596 additions and 1 deletions

4
vendor/github.com/ilyakaznacheev/cleanenv/.gitignore generated vendored Normal file
View File

@@ -0,0 +1,4 @@
.*
!.travis.yml
!.github
!.gitignore

View File

@@ -0,0 +1,56 @@
# Contributing to Cleanenv
Thank you for your interest in contributing to Cleanenv!
## How to Contribute
Contributions can take many forms, including bug reports, feature requests, documentation improvements, and code changes. We welcome all contributions that align with the goals of the project.
Please keep in mind that this project is designed to be minimalistic, obvious, and as simple as possible.
We prioritize clear and easy-to-understand code over complex or "magical" solutions.
If you're considering making a code change that might be considered overcomplicated or not in line with the project's goals,
we recommend opening an issue to discuss the change before submitting a pull request.
#### Note on environment variables names
Cleanenv strives to be as explicit and as obvious as possible, and as such,
we decided to write environment variable in config struct tags *as is*.
It was done for purpose. This decision guarantees that programmer can *always* find environment variable by its name in code.
It may not sound pretty useful for such a limitation, but in my own experience, it is.
So you always will be able to find environment variable by its whole name in code,
which makes writing complex nested config structures a bit more difficult.
By the same reason, any contribution changing this behavior will be rejected.
Please not add any prefixes or suffixes to environment variables names, we will just not approve such PRs.
Thanks for understanding.
### Reporting Bugs and Requesting Features
If you've found a bug or have an idea for a new feature, please open an issue on our GitHub repository. Be sure to include as much detail as possible, including steps to reproduce the issue, expected behavior, and actual behavior.
### Contributing Code Changes
If you would like to contribute code changes to the project, please follow these steps:
1. Fork the repository to your own GitHub account.
2. Create a new branch for your changes.
3. Make your changes and test them thoroughly.
4. Submit a pull request (PR) with your changes.
5. Wait for a project maintainer to review your PR. The review process may take some time, so please be patient.
6. Respond to any feedback and make any necessary changes to your code.
7. Once your PR has been approved, it will be merged into the main branch of the repository.
### Code Style and Standards
Try to stick to the existing code style of the project.
### Testing
We rely on unit tests to ensure the quality of our code.
Before submitting a PR, please make sure your changes include appropriate tests.
The number indicating the test code coverage should not decrease.
## Getting Help
If you need help with the project, please don't hesitate to ask.
You can get in touch with the project maintainers by opening an issue on the GitHub repository.

9
vendor/github.com/ilyakaznacheev/cleanenv/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,9 @@
MIT License
Copyright (c) 2019 Ilya Kaznacheev
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 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.

323
vendor/github.com/ilyakaznacheev/cleanenv/README.md generated vendored Normal file
View File

@@ -0,0 +1,323 @@
![Clean Env](logo.svg)
# Clean Env
Minimalistic configuration reader
[![Mentioned in Awesome Go](https://awesome.re/mentioned-badge.svg)](https://github.com/avelino/awesome-go)
[![GoDoc](https://godoc.org/github.com/ilyakaznacheev/cleanenv?status.svg)](https://godoc.org/github.com/ilyakaznacheev/cleanenv)
[![Go Report Card](https://goreportcard.com/badge/github.com/ilyakaznacheev/cleanenv)](https://goreportcard.com/report/github.com/ilyakaznacheev/cleanenv)
[![Coverage Status](https://codecov.io/github/ilyakaznacheev/cleanenv/coverage.svg?branch=master)](https://codecov.io/gh/ilyakaznacheev/cleanenv)
[![Build Status](https://img.shields.io/github/actions/workflow/status/ilyakaznacheev/cleanenv/test.yml)](https://github.com/ilyakaznacheev/cleanenv/actions)
[![Release](https://img.shields.io/github/release/ilyakaznacheev/cleanenv.svg)](https://github.com/ilyakaznacheev/cleanenv/releases/)
[![License](https://img.shields.io/github/license/ilyakaznacheev/cleanenv.svg)](https://github.com/ilyakaznacheev/cleanenv/blob/master/LICENSE)
## Overview
This is a simple configuration reading tool. It just does the following:
- reads and parses configuration structure from the file
- reads and overwrites configuration structure from environment variables
- writes a detailed variable list to help output
## Content
- [Installation](#installation)
- [Usage](#usage)
- [Read Configuration](#read-configuration)
- [Read Environment Variables Only](#read-environment-variables-only)
- [Update Environment Variables](#update-environment-variables)
- [Description](#description)
- [Model Format](#model-format)
- [Supported types](#supported-types)
- [Custom Functions](#custom-functions)
- [Custom Value Setter](#custom-value-setter)
- [Custom Value Update](#custom-value-update)
- [Supported File Formats](#supported-file-formats)
- [Integration](#integration)
- [Flag](#flag)
- [Examples](#examples)
- [Contribution](#contribution)
- [Thanks](#thanks)
## Installation
To install the package run
```bash
go get -u github.com/ilyakaznacheev/cleanenv
```
## Usage
The package is oriented to be simple in use and explicitness.
The main idea is to use a structured configuration variable instead of any sort of dynamic set of configuration fields like some libraries does, to avoid unnecessary type conversions and move the configuration through the program as a simple structure, not as an object with complex behavior.
There are just several actions you can do with this tool and probably only things you want to do with your config if your application is not too complicated.
- read configuration file
- read environment variables
- read some environment variables again
### Read Configuration
You can read a configuration file and environment variables in a single function call.
```go
import "github.com/ilyakaznacheev/cleanenv"
type ConfigDatabase struct {
Port string `yaml:"port" env:"PORT" env-default:"5432"`
Host string `yaml:"host" env:"HOST" env-default:"localhost"`
Name string `yaml:"name" env:"NAME" env-default:"postgres"`
User string `yaml:"user" env:"USER" env-default:"user"`
Password string `yaml:"password" env:"PASSWORD"`
}
var cfg ConfigDatabase
err := cleanenv.ReadConfig("config.yml", &cfg)
if err != nil {
...
}
```
This will do the following:
1. parse configuration file according to YAML format (`yaml` tag in this case);
1. reads environment variables and overwrites values from the file with the values which was found in the environment (`env` tag);
1. if no value was found on the first two steps, the field will be filled with the default value (`env-default` tag) if it is set.
### Read Environment Variables Only
Sometimes you don't want to use configuration files at all, or you may want to use `.env` file format instead. Thus, you can limit yourself with only reading environment variables:
```go
import "github.com/ilyakaznacheev/cleanenv"
type ConfigDatabase struct {
Port string `env:"PORT" env-default:"5432"`
Host string `env:"HOST" env-default:"localhost"`
Name string `env:"NAME" env-default:"postgres"`
User string `env:"USER" env-default:"user"`
Password string `env:"PASSWORD"`
}
var cfg ConfigDatabase
err := cleanenv.ReadEnv(&cfg)
if err != nil {
...
}
```
### Update Environment Variables
Some environment variables may change during the application run. To get the new values you need to mark these variables as updatable with the tag `env-upd` and then run the update function:
```go
import "github.com/ilyakaznacheev/cleanenv"
type ConfigRemote struct {
Port string `env:"PORT" env-upd`
Host string `env:"HOST" env-upd`
UserName string `env:"USERNAME"`
}
var cfg ConfigRemote
cleanenv.ReadEnv(&cfg)
// ... some actions in-between
err := cleanenv.UpdateEnv(&cfg)
if err != nil {
...
}
```
Here remote host and port may change in a distributed system architecture. Fields `cfg.Port` and `cfg.Host` can be updated in the runtime from corresponding environment variables. You can update them before the remote service call. Field `cfg.UserName` will not be changed after the initial read, though.
### Description
You can get descriptions of all environment variables to use them in the help documentation.
```go
import "github.com/ilyakaznacheev/cleanenv"
type ConfigServer struct {
Port string `env:"PORT" env-description:"server port"`
Host string `env:"HOST" env-description:"server host"`
}
var cfg ConfigRemote
help, err := cleanenv.GetDescription(&cfg, nil)
if err != nil {
...
}
```
You will get the following:
```
Environment variables:
PORT server port
HOST server host
```
## Model Format
Library uses tags to configure the model of configuration structure. There are the following tags:
- `env="<name>"` - environment variable name (e.g. `env="PORT"`);
- `env-upd` - flag to mark a field as updatable. Run `UpdateEnv(&cfg)` to refresh updatable variables from environment;
- `env-required` - flag to mark a field as required. If set will return an error during environment parsing when the flagged as required field is empty (default Go value). Tag `env-default` is ignored in this case;
- `env-default="<value>"` - default value. If the field wasn't filled from the environment variable default value will be used instead;
- `env-separator="<value>"` - custom list and map separator. If not set, the default separator `,` will be used;
- `env-description="<value>"` - environment variable description;
- `env-layout="<value>"` - parsing layout (for types like `time.Time`);
- `env-prefix="<value>"` - prefix for all fields of nested structure (only for nested structures);
## Supported types
There are following supported types:
- `int` (any kind);
- `float` (any kind);
- `string`;
- `boolean`;
- slices (of any other supported type);
- maps (of any other supported type);
- `time.Duration`;
- `time.Time` (layout by default is RFC3339, may be overridden by `env-layout`);
- `*time.Location` (time zone parsing [depends](https://pkg.go.dev/time#LoadLocation) on running machine);
- any type that implements `encoding.TextUnmarshaler`;
- any type implementing `cleanenv.Setter` interface.
## Custom Functions
To enhance package abilities you can use some custom functions.
### Custom Value Setter
To make custom type allows to set the value from the environment variable, you need to implement the `Setter` interface on the field level:
```go
type MyField string
func (f *MyField) SetValue(s string) error {
if s == "" {
return fmt.Errorf("field value can't be empty")
}
*f = MyField("my field is: "+ s)
return nil
}
type Config struct {
Field MyField `env="MY_VALUE"`
}
```
`SetValue` method should implement conversion logic from string to custom type.
### Custom Value Update
You may need to execute some custom field update logic, e.g. for remote config load.
Thus, you need to implement the `Updater` interface on the structure level:
```go
type Config struct {
Field string
}
func (c *Config) Update() error {
newField, err := SomeCustomUpdate()
f.Field = newField
return err
}
```
## Supported File Formats
There are several most popular config file formats supported:
- YAML (`.yaml`, `.yml`)
- JSON (`.json`)
- TOML (`.toml`)
- EDN (`.edn`)
- ENV (`.env`)
**Note**:
- while using `.env` file the library will set corresponding data to process environment variables.
It will override existing variables with the same keys in the process environment.
## Integration
The package can be used with many other solutions. To make it more useful, we made some helpers.
### Flag
You can use the cleanenv help together with Golang `flag` package.
```go
// create some config structure
var cfg config
// create flag set using `flag` package
fset := flag.NewFlagSet("Example", flag.ContinueOnError)
// get config usage with wrapped flag usage
fset.Usage = cleanenv.FUsage(fset.Output(), &cfg, nil, fset.Usage)
fset.Parse(os.Args[1:])
```
## Examples
```go
type Config struct {
Port string `yaml:"port" env:"PORT" env-default:"8080"`
Host string `yaml:"host" env:"HOST" env-default:"localhost"`
}
var cfg Config
err := ReadConfig("config.yml", &cfg)
if err != nil {
...
}
```
This code will try to read and parse the configuration file `config.yml` as the structure is described in the `Config` structure. Then it will overwrite fields from available environment variables (`PORT`, `HOST`).
For more details check the [example](/example) directory.
## Version Support Policy
We support the last 7 versions of Golang. E.g. if the current version is 1.19, we test compatibility with all versions from 1.19 to 1.13.
If you use an older version of Golang in your project, please use an older library version.
## Contribution
The tool is open-sourced under the [MIT](LICENSE) license.
If you find some error, want to add something or ask a question - feel free to create an issue and/or make a pull request.
Guidelines for contribution may be found in [CONTRIBUTING.md](CONTRIBUTING.md).
Any contribution is welcome.
## Thanks
Big thanks to a project [kelseyhightower/envconfig](https://github.com/kelseyhightower/envconfig) for inspiration.
The logo was made by [alexchoffy](https://www.instagram.com/alexchoffy/).
## Blog Posts
[Clean Configuration Management in Golang](https://dev.to/ilyakaznacheev/clean-configuration-management-in-golang-1c89).

639
vendor/github.com/ilyakaznacheev/cleanenv/cleanenv.go generated vendored Normal file
View File

@@ -0,0 +1,639 @@
package cleanenv
import (
"encoding"
"encoding/json"
"flag"
"fmt"
"io"
"net/url"
"os"
"path/filepath"
"reflect"
"sort"
"strconv"
"strings"
"time"
"github.com/BurntSushi/toml"
"github.com/joho/godotenv"
"gopkg.in/yaml.v3"
"olympos.io/encoding/edn"
)
const (
// DefaultSeparator is a default list and map separator character
DefaultSeparator = ","
)
// Supported tags
const (
// TagEnv name of the environment variable or a list of names
TagEnv = "env"
// TagEnvLayout value parsing layout (for types like time.Time)
TagEnvLayout = "env-layout"
// TagEnvDefault default value
TagEnvDefault = "env-default"
// TagEnvSeparator custom list and map separator
TagEnvSeparator = "env-separator"
// TagEnvDescription environment variable description
TagEnvDescription = "env-description"
// TagEnvUpd flag to mark a field as updatable
TagEnvUpd = "env-upd"
// TagEnvRequired flag to mark a field as required
TagEnvRequired = "env-required"
// TagEnvPrefix аlag to specify prefix for structure fields
TagEnvPrefix = "env-prefix"
)
// Setter is an interface for a custom value setter.
//
// To implement a custom value setter you need to add a SetValue function to your type that will receive a string raw value:
//
// type MyField string
//
// func (f *MyField) SetValue(s string) error {
// if s == "" {
// return fmt.Errorf("field value can't be empty")
// }
// *f = MyField("my field is: " + s)
// return nil
// }
type Setter interface {
SetValue(string) error
}
// Updater gives an ability to implement custom update function for a field or a whole structure
type Updater interface {
Update() error
}
// ReadConfig reads configuration file and parses it depending on tags in structure provided.
// Then it reads and parses
//
// Example:
//
// type ConfigDatabase struct {
// Port string `yaml:"port" env:"PORT" env-default:"5432"`
// Host string `yaml:"host" env:"HOST" env-default:"localhost"`
// Name string `yaml:"name" env:"NAME" env-default:"postgres"`
// User string `yaml:"user" env:"USER" env-default:"user"`
// Password string `yaml:"password" env:"PASSWORD"`
// }
//
// var cfg ConfigDatabase
//
// err := cleanenv.ReadConfig("config.yml", &cfg)
// if err != nil {
// ...
// }
func ReadConfig(path string, cfg interface{}) error {
err := parseFile(path, cfg)
if err != nil {
return err
}
return readEnvVars(cfg, false)
}
// ReadEnv reads environment variables into the structure.
func ReadEnv(cfg interface{}) error {
return readEnvVars(cfg, false)
}
// UpdateEnv rereads (updates) environment variables in the structure.
func UpdateEnv(cfg interface{}) error {
return readEnvVars(cfg, true)
}
// parseFile parses configuration file according to it's extension
//
// Currently following file extensions are supported:
//
// - yaml
//
// - json
//
// - toml
//
// - env
//
// - edn
func parseFile(path string, cfg interface{}) error {
// open the configuration file
f, err := os.OpenFile(path, os.O_RDONLY|os.O_SYNC, 0)
if err != nil {
return err
}
defer f.Close()
// parse the file depending on the file type
switch ext := strings.ToLower(filepath.Ext(path)); ext {
case ".yaml", ".yml":
err = ParseYAML(f, cfg)
case ".json":
err = ParseJSON(f, cfg)
case ".toml":
err = ParseTOML(f, cfg)
case ".edn":
err = parseEDN(f, cfg)
case ".env":
err = parseENV(f, cfg)
default:
return fmt.Errorf("file format '%s' doesn't supported by the parser", ext)
}
if err != nil {
return fmt.Errorf("config file parsing error: %s", err.Error())
}
return nil
}
// ParseYAML parses YAML from reader to data structure
func ParseYAML(r io.Reader, str interface{}) error {
return yaml.NewDecoder(r).Decode(str)
}
// ParseJSON parses JSON from reader to data structure
func ParseJSON(r io.Reader, str interface{}) error {
return json.NewDecoder(r).Decode(str)
}
// ParseTOML parses TOML from reader to data structure
func ParseTOML(r io.Reader, str interface{}) error {
_, err := toml.NewDecoder(r).Decode(str)
return err
}
// parseEDN parses EDN from reader to data structure
func parseEDN(r io.Reader, str interface{}) error {
return edn.NewDecoder(r).Decode(str)
}
// parseENV, in fact, doesn't fill the structure with environment variable values.
// It just parses ENV file and sets all variables to the environment.
// Thus, the structure should be filled at the next steps.
func parseENV(r io.Reader, _ interface{}) error {
vars, err := godotenv.Parse(r)
if err != nil {
return err
}
for env, val := range vars {
if err = os.Setenv(env, val); err != nil {
return fmt.Errorf("set environment: %w", err)
}
}
return nil
}
// parseSlice parses value into a slice of given type
func parseSlice(valueType reflect.Type, value string, sep string, layout *string) (*reflect.Value, error) {
sliceValue := reflect.MakeSlice(valueType, 0, 0)
if valueType.Elem().Kind() == reflect.Uint8 {
sliceValue = reflect.ValueOf([]byte(value))
} else if len(strings.TrimSpace(value)) != 0 {
values := strings.Split(value, sep)
sliceValue = reflect.MakeSlice(valueType, len(values), len(values))
for i, val := range values {
if err := parseValue(sliceValue.Index(i), val, sep, layout); err != nil {
return nil, err
}
}
}
return &sliceValue, nil
}
// parseMap parses value into a map of given type
func parseMap(valueType reflect.Type, value string, sep string, layout *string) (*reflect.Value, error) {
mapValue := reflect.MakeMap(valueType)
if len(strings.TrimSpace(value)) != 0 {
pairs := strings.Split(value, sep)
for _, pair := range pairs {
kvPair := strings.SplitN(pair, ":", 2)
if len(kvPair) != 2 {
return nil, fmt.Errorf("invalid map item: %q", pair)
}
k := reflect.New(valueType.Key()).Elem()
err := parseValue(k, kvPair[0], sep, layout)
if err != nil {
return nil, err
}
v := reflect.New(valueType.Elem()).Elem()
err = parseValue(v, kvPair[1], sep, layout)
if err != nil {
return nil, err
}
mapValue.SetMapIndex(k, v)
}
}
return &mapValue, nil
}
// structMeta is a structure metadata entity
type structMeta struct {
envList []string
fieldName string
fieldValue reflect.Value
defValue *string
layout *string
separator string
description string
updatable bool
required bool
}
// isFieldValueZero determines if fieldValue empty or not
func (sm *structMeta) isFieldValueZero() bool {
return sm.fieldValue.IsZero()
}
// parseFunc custom value parser function
type parseFunc func(*reflect.Value, string, *string) error
// Any specific supported struct can be added here
var validStructs = map[reflect.Type]parseFunc{
reflect.TypeOf(time.Time{}): func(field *reflect.Value, value string, layout *string) error {
var l string
if layout != nil {
l = *layout
} else {
l = time.RFC3339
}
val, err := time.Parse(l, value)
if err != nil {
return err
}
field.Set(reflect.ValueOf(val))
return nil
},
reflect.TypeOf(url.URL{}): func(field *reflect.Value, value string, _ *string) error {
val, err := url.Parse(value)
if err != nil {
return err
}
field.Set(reflect.ValueOf(*val))
return nil
},
reflect.TypeOf(&time.Location{}): func(field *reflect.Value, value string, _ *string) error {
loc, err := time.LoadLocation(value)
if err != nil {
return err
}
field.Set(reflect.ValueOf(loc))
return nil
},
}
// readStructMetadata reads structure metadata (types, tags, etc.)
func readStructMetadata(cfgRoot interface{}) ([]structMeta, error) {
type cfgNode struct {
Val interface{}
Prefix string
}
cfgStack := []cfgNode{{cfgRoot, ""}}
metas := make([]structMeta, 0)
for i := 0; i < len(cfgStack); i++ {
s := reflect.ValueOf(cfgStack[i].Val)
sPrefix := cfgStack[i].Prefix
// unwrap pointer
if s.Kind() == reflect.Ptr {
s = s.Elem()
}
// process only structures
if s.Kind() != reflect.Struct {
return nil, fmt.Errorf("wrong type %v", s.Kind())
}
typeInfo := s.Type()
// read tags
for idx := 0; idx < s.NumField(); idx++ {
fType := typeInfo.Field(idx)
var (
defValue *string
layout *string
separator string
)
// process nested structure (except of supported ones)
if fld := s.Field(idx); fld.Kind() == reflect.Struct {
//skip unexported
if !fld.CanInterface() {
continue
}
// add structure to parsing stack
if _, found := validStructs[fld.Type()]; !found {
prefix, _ := fType.Tag.Lookup(TagEnvPrefix)
cfgStack = append(cfgStack, cfgNode{fld.Addr().Interface(), sPrefix + prefix})
continue
}
// process time.Time
if l, ok := fType.Tag.Lookup(TagEnvLayout); ok {
layout = &l
}
}
// check is the field value can be changed
if !s.Field(idx).CanSet() {
continue
}
if def, ok := fType.Tag.Lookup(TagEnvDefault); ok {
defValue = &def
}
if sep, ok := fType.Tag.Lookup(TagEnvSeparator); ok {
separator = sep
} else {
separator = DefaultSeparator
}
_, upd := fType.Tag.Lookup(TagEnvUpd)
_, required := fType.Tag.Lookup(TagEnvRequired)
envList := make([]string, 0)
if envs, ok := fType.Tag.Lookup(TagEnv); ok && len(envs) != 0 {
envList = strings.Split(envs, DefaultSeparator)
if sPrefix != "" {
for i := range envList {
envList[i] = sPrefix + envList[i]
}
}
}
metas = append(metas, structMeta{
envList: envList,
fieldName: s.Type().Field(idx).Name,
fieldValue: s.Field(idx),
defValue: defValue,
layout: layout,
separator: separator,
description: fType.Tag.Get(TagEnvDescription),
updatable: upd,
required: required,
})
}
}
return metas, nil
}
// readEnvVars reads environment variables to the provided configuration structure
func readEnvVars(cfg interface{}, update bool) error {
metaInfo, err := readStructMetadata(cfg)
if err != nil {
return err
}
if updater, ok := cfg.(Updater); ok {
if err := updater.Update(); err != nil {
return err
}
}
for _, meta := range metaInfo {
// update only updatable fields
if update && !meta.updatable {
continue
}
var rawValue *string
for _, env := range meta.envList {
if value, ok := os.LookupEnv(env); ok {
rawValue = &value
break
}
}
if rawValue == nil && meta.required && meta.isFieldValueZero() {
return fmt.Errorf(
"field %q is required but the value is not provided",
meta.fieldName,
)
}
if rawValue == nil && meta.isFieldValueZero() {
rawValue = meta.defValue
}
if rawValue == nil {
continue
}
var envName string
if len(meta.envList) > 0 {
envName = meta.envList[0]
}
if err := parseValue(meta.fieldValue, *rawValue, meta.separator, meta.layout); err != nil {
return fmt.Errorf("parsing field %v env %v: %v", meta.fieldName, envName, err)
}
}
return nil
}
// parseValue parses value into the corresponding field.
// In case of maps and slices it uses provided separator to split raw value string
func parseValue(field reflect.Value, value, sep string, layout *string) error {
// TODO: simplify recursion
valueType := field.Type()
// look for supported struct parser
// parsing of struct must be done before checking the implementation `encoding.TextUnmarshaler`
// standard struct types already have the implementation `encoding.TextUnmarshaler` (for example `time.Time`)
if structParser, found := validStructs[valueType]; found {
return structParser(&field, value, layout)
}
if field.CanInterface() {
if ct, ok := field.Interface().(encoding.TextUnmarshaler); ok {
return ct.UnmarshalText([]byte(value))
} else if ctp, ok := field.Addr().Interface().(encoding.TextUnmarshaler); ok {
return ctp.UnmarshalText([]byte(value))
}
if cs, ok := field.Interface().(Setter); ok {
return cs.SetValue(value)
} else if csp, ok := field.Addr().Interface().(Setter); ok {
return csp.SetValue(value)
}
}
switch valueType.Kind() {
// parse string value
case reflect.String:
field.SetString(value)
// parse boolean value
case reflect.Bool:
b, err := strconv.ParseBool(value)
if err != nil {
return err
}
field.SetBool(b)
// parse integer
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32:
number, err := strconv.ParseInt(value, 0, valueType.Bits())
if err != nil {
return err
}
field.SetInt(number)
case reflect.Int64:
if valueType == reflect.TypeOf(time.Duration(0)) {
// try to parse time
d, err := time.ParseDuration(value)
if err != nil {
return err
}
field.SetInt(int64(d))
} else {
// parse regular integer
number, err := strconv.ParseInt(value, 0, valueType.Bits())
if err != nil {
return err
}
field.SetInt(number)
}
// parse unsigned integer value
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
number, err := strconv.ParseUint(value, 0, valueType.Bits())
if err != nil {
return err
}
field.SetUint(number)
// parse floating point value
case reflect.Float32, reflect.Float64:
number, err := strconv.ParseFloat(value, valueType.Bits())
if err != nil {
return err
}
field.SetFloat(number)
// parse sliced value
case reflect.Slice:
sliceValue, err := parseSlice(valueType, value, sep, layout)
if err != nil {
return err
}
field.Set(*sliceValue)
// parse mapped value
case reflect.Map:
mapValue, err := parseMap(valueType, value, sep, layout)
if err != nil {
return err
}
field.Set(*mapValue)
default:
return fmt.Errorf("unsupported type %s.%s", valueType.PkgPath(), valueType.Name())
}
return nil
}
// GetDescription returns a description of environment variables.
// You can provide a custom header text.
func GetDescription(cfg interface{}, headerText *string) (string, error) {
meta, err := readStructMetadata(cfg)
if err != nil {
return "", err
}
var header string
if headerText != nil {
header = *headerText
} else {
header = "Environment variables:"
}
description := make([]string, 0)
for _, m := range meta {
if len(m.envList) == 0 {
continue
}
for idx, env := range m.envList {
elemDescription := fmt.Sprintf("\n %s %s", env, m.fieldValue.Kind())
if idx > 0 {
elemDescription += fmt.Sprintf(" (alternative to %s)", m.envList[0])
}
elemDescription += fmt.Sprintf("\n \t%s", m.description)
if m.defValue != nil {
elemDescription += fmt.Sprintf(" (default %q)", *m.defValue)
}
description = append(description, elemDescription)
}
}
if len(description) == 0 {
return "", nil
}
sort.Strings(description)
return header + strings.Join(description, ""), nil
}
// Usage returns a configuration usage help.
// Other usage instructions can be wrapped in and executed before this usage function.
// The default output is STDERR.
func Usage(cfg interface{}, headerText *string, usageFuncs ...func()) func() {
return FUsage(os.Stderr, cfg, headerText, usageFuncs...)
}
// FUsage prints configuration help into the custom output.
// Other usage instructions can be wrapped in and executed before this usage function
func FUsage(w io.Writer, cfg interface{}, headerText *string, usageFuncs ...func()) func() {
return func() {
for _, fn := range usageFuncs {
fn()
}
_ = flag.Usage
text, err := GetDescription(cfg, headerText)
if err != nil {
return
}
if len(usageFuncs) > 0 {
fmt.Fprintln(w)
}
fmt.Fprintln(w, text)
}
}

View File

@@ -0,0 +1,9 @@
comment: # this is a top-level key
layout: "reach, diff, flags, files"
behavior: default
require_changes: false # if true: only post the comment if coverage changes
require_base: no # [yes :: must have a base report to post]
require_head: yes # [yes :: must have a head report to post]
coverage:
status:
patch: no

63
vendor/github.com/ilyakaznacheev/cleanenv/docs.go generated vendored Normal file
View File

@@ -0,0 +1,63 @@
/*
Package cleanenv gives you a single tool to read application configuration from several sources with ease.
Features
- read from several file formats (YAML, JSON, TOML, ENV, EDN) and parse into the internal structure;
- read environment variables into the internal structure;
- output environment variable list with descriptions into help output;
- custom variable readers (e.g. if you want to read from remote config server, etc).
Usage
You can just prepare the config structure and fill it from the config file and environment variables.
type Config struct {
Port string `yaml:"port" env:"PORT" env-default:"8080"`
Host string `yaml:"host" env:"HOST" env-default:"localhost"`
}
var cfg Config
ReadConfig("config.yml", &cfg)
Help output
You can list all of your environment variables by means of help output:
type ConfigServer struct {
Port string `env:"PORT" env-description:"server port"`
Host string `env:"HOST" env-description:"server host"`
}
var cfg ConfigRemote
help, err := cleanenv.GetDescription(&cfg, nil)
if err != nil {
...
}
// setup help output
f := flag.NewFlagSet("Example app", 1)
fu := f.Usage
f.Usage = func() {
fu()
envHelp, _ := cleanenv.GetDescription(&cfg, nil)
fmt.Fprintln(f.Output())
fmt.Fprintln(f.Output(), envHelp)
}
f.Parse(os.Args[1:])
Then run go run main.go -h and the output will include:
Environment variables:
PORT server port
HOST server host
For more detailed information check examples and example tests.
*/
package cleanenv

137
vendor/github.com/ilyakaznacheev/cleanenv/logo.svg generated vendored Normal file

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 416 KiB