├── .gitignore
├── testdata
├── invalid
│ ├── bad.json
│ ├── bad.toml
│ ├── bad.yaml
│ ├── list.hcl
│ ├── pod.yaml
│ ├── pod.toml
│ └── pod.json
└── valid
│ ├── server.yaml
│ ├── server.toml
│ ├── server.json
│ ├── pod.yaml
│ ├── pod.toml
│ └── pod.json
├── examples
├── required
│ ├── config.json
│ └── required_test.go
├── custom
│ ├── config.yaml
│ └── custom_test.go
├── env
│ ├── config.yaml
│ └── env_test.go
└── config
│ ├── config.yaml
│ └── config_test.go
├── img
└── fig.logo.png
├── Makefile
├── tools
├── go.mod
├── go.sum
└── tools.go
├── go.mod
├── error_test.go
├── .github
└── workflows
│ └── lint-and-test.yml
├── error.go
├── .golangci.yml
├── util.go
├── go.sum
├── README.md
├── util_test.go
├── option.go
├── field_test.go
├── field.go
├── doc.go
├── LICENSE
├── fig.go
└── fig_test.go
/.gitignore:
--------------------------------------------------------------------------------
1 | .idea/
--------------------------------------------------------------------------------
/testdata/invalid/bad.json:
--------------------------------------------------------------------------------
1 | }
--------------------------------------------------------------------------------
/testdata/invalid/bad.toml:
--------------------------------------------------------------------------------
1 | }
--------------------------------------------------------------------------------
/testdata/invalid/bad.yaml:
--------------------------------------------------------------------------------
1 | }
--------------------------------------------------------------------------------
/examples/required/config.json:
--------------------------------------------------------------------------------
1 | {
2 |
3 | }
--------------------------------------------------------------------------------
/testdata/invalid/list.hcl:
--------------------------------------------------------------------------------
1 | foo = [1, 2, "foo"]
--------------------------------------------------------------------------------
/img/fig.logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kkyr/fig/HEAD/img/fig.logo.png
--------------------------------------------------------------------------------
/testdata/valid/server.yaml:
--------------------------------------------------------------------------------
1 | host: "0.0.0.0"
2 |
3 | logger:
4 | log_level: "debug"
--------------------------------------------------------------------------------
/testdata/valid/server.toml:
--------------------------------------------------------------------------------
1 | host = "0.0.0.0"
2 |
3 | [logger]
4 | log_level = "debug"
5 |
--------------------------------------------------------------------------------
/testdata/valid/server.json:
--------------------------------------------------------------------------------
1 | {
2 | "host": "0.0.0.0",
3 | "logger": {
4 | "log_level": "debug"
5 | }
6 | }
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | .PHONY: test
2 | test:
3 | go test -v ./...
4 |
5 | .PHONY: lint
6 | lint:
7 | ./build/lint.sh ./...
--------------------------------------------------------------------------------
/examples/custom/config.yaml:
--------------------------------------------------------------------------------
1 | app:
2 | environment: dev
3 |
4 | server:
5 | port: 443
6 | read_timeout: 1m
7 |
8 |
--------------------------------------------------------------------------------
/examples/env/config.yaml:
--------------------------------------------------------------------------------
1 | database:
2 | host: "localhost"
3 | port: 5432
4 | db: "users"
5 | username: ""
6 | password: ""
--------------------------------------------------------------------------------
/tools/go.mod:
--------------------------------------------------------------------------------
1 | module github.com/kkyr/fig/tools
2 |
3 | go 1.20
4 |
5 | require github.com/golangci/golangci-lint v1.51.0 // indirect
6 |
--------------------------------------------------------------------------------
/go.mod:
--------------------------------------------------------------------------------
1 | module github.com/kkyr/fig
2 |
3 | go 1.21
4 |
5 | require (
6 | github.com/mitchellh/mapstructure v1.5.0
7 | github.com/pelletier/go-toml/v2 v2.1.0
8 | gopkg.in/yaml.v3 v3.0.1
9 | )
10 |
--------------------------------------------------------------------------------
/tools/go.sum:
--------------------------------------------------------------------------------
1 | github.com/golangci/golangci-lint v1.51.0 h1:M1bpDymgdaPKNzPwQdebCGki/nzvVkr2f/eUfk9C9oU=
2 | github.com/golangci/golangci-lint v1.51.0/go.mod h1:7taIMcmZ5ksCuRruCV/mm8Ir3sE+bIuOHVCvt1B4hi4=
3 |
--------------------------------------------------------------------------------
/examples/config/config.yaml:
--------------------------------------------------------------------------------
1 | app:
2 | environment: dev
3 |
4 | server:
5 | port: 443
6 | read_timeout: 1m
7 |
8 | logger:
9 | level: debug
10 | pattern: '[a-z]+'
11 |
12 | certificate:
13 | version: 1
14 | expiration: 2020-12-01
15 |
--------------------------------------------------------------------------------
/tools/tools.go:
--------------------------------------------------------------------------------
1 | //go:build never
2 | // +build never
3 |
4 | // Package tools is used to track binary dependencies with go modules
5 | // https://github.com/golang/go/wiki/Modules#how-can-i-track-tool-dependencies-for-a-module
6 | package tools
7 |
8 | import (
9 | _ "github.com/golangci/golangci-lint/cmd/golangci-lint"
10 | )
11 |
--------------------------------------------------------------------------------
/error_test.go:
--------------------------------------------------------------------------------
1 | package fig
2 |
3 | import (
4 | "fmt"
5 | "testing"
6 | )
7 |
8 | func Test_fieldErrors_Error(t *testing.T) {
9 | fe := make(fieldErrors)
10 |
11 | fe["B"] = fmt.Errorf("berr")
12 | fe["A"] = fmt.Errorf("aerr")
13 |
14 | got := fe.Error()
15 |
16 | if want := "A: aerr, B: berr"; want != got {
17 | t.Fatalf("want %q, got %q", want, got)
18 | }
19 |
20 | fe = make(fieldErrors)
21 | got = fe.Error()
22 |
23 | if got != "" {
24 | t.Fatalf("empty errors returned non-empty string: %s", got)
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/.github/workflows/lint-and-test.yml:
--------------------------------------------------------------------------------
1 | name: Build, lint and test
2 |
3 | on:
4 | push:
5 | tags:
6 | - v*
7 | branches:
8 | - master
9 | pull_request:
10 |
11 | env:
12 | GO_VERSION: "1.20"
13 |
14 | jobs:
15 | lint:
16 | runs-on: ubuntu-24.04
17 | steps:
18 | - name: Setup Go
19 | uses: actions/setup-go@v3
20 | with:
21 | go-version: ${{ env.GO_VERSION }}
22 | - name: Checkout repository
23 | uses: actions/checkout@v3
24 | - name: Run linter
25 | run: make lint
26 | - name: Run tests
27 | run: make test
28 |
--------------------------------------------------------------------------------
/examples/required/required_test.go:
--------------------------------------------------------------------------------
1 | package required
2 |
3 | import (
4 | "fmt"
5 | "time"
6 |
7 | "github.com/kkyr/fig"
8 | )
9 |
10 | type Config struct {
11 | Cache struct {
12 | Size int `conf:"size" default:"10000"`
13 | CleanupInterval time.Duration `conf:"cleanup_interval" validate:"required"`
14 | } `conf:"cache"`
15 | Tags []string `conf:"tags" validate:"required"`
16 | }
17 |
18 | func ExampleLoad() {
19 | var cfg Config
20 | err := fig.Load(&cfg, fig.File("config.json"), fig.Tag("conf"))
21 | fmt.Println(err)
22 |
23 | // Output:
24 | // cache.cleanup_interval: required validation failed, tags: required validation failed
25 | }
26 |
--------------------------------------------------------------------------------
/testdata/invalid/pod.yaml:
--------------------------------------------------------------------------------
1 | apiVersion:
2 | metadata:
3 | name: redis
4 | spec:
5 | containers:
6 | - name: redis
7 | command:
8 | - redis-server
9 | - "/redis-master/redis.conf"
10 | env:
11 | - name: MASTER
12 | value: "true"
13 | ports:
14 | - containerPort: 6379
15 | resources:
16 | limits:
17 | cpu: "0.1"
18 | volumeMounts:
19 | - mountPath: /redis-master-data
20 | name: data
21 | - mountPath: /redis-master
22 | name: config
23 | args:
24 | "-w":
25 | value: ""
26 | "-o":
27 | value:
28 | volumes:
29 | - name: data
30 | configMap:
31 | name: example-data
32 | - configMap:
33 | name: example-redis-config
34 | items:
35 | - key: redis-config
36 | path: redis.conf
--------------------------------------------------------------------------------
/error.go:
--------------------------------------------------------------------------------
1 | package fig
2 |
3 | import (
4 | "fmt"
5 | "sort"
6 | "strings"
7 | )
8 |
9 | // ErrFileNotFound is returned as a wrapped error by `Load` when the config file is
10 | // not found in the given search dirs.
11 | var ErrFileNotFound = fmt.Errorf("file not found")
12 |
13 | // fieldErrors collects errors for fields of config struct.
14 | type fieldErrors map[string]error
15 |
16 | // Error formats all fields errors into a single string.
17 | func (fe fieldErrors) Error() string {
18 | keys := make([]string, 0, len(fe))
19 | for key := range fe {
20 | keys = append(keys, key)
21 | }
22 | sort.Strings(keys)
23 |
24 | var sb strings.Builder
25 | sb.Grow(len(keys) * 10)
26 |
27 | for _, key := range keys {
28 | sb.WriteString(key)
29 | sb.WriteString(": ")
30 | sb.WriteString(fe[key].Error())
31 | sb.WriteString(", ")
32 | }
33 |
34 | return strings.TrimSuffix(sb.String(), ", ")
35 | }
36 |
--------------------------------------------------------------------------------
/.golangci.yml:
--------------------------------------------------------------------------------
1 | linters:
2 | enable-all: true
3 | disable:
4 | - wsl
5 | - gomnd
6 | - testpackage
7 | - goerr113
8 | - exhaustive
9 | - funlen
10 | - varnamelen
11 | - gci
12 | - wrapcheck
13 | - exhaustruct
14 | - exhaustivestruct
15 | - cyclop
16 | - gofumpt
17 | - typecheck
18 | - ireturn
19 | - nlreturn
20 | - errname
21 | - nonamedreturns
22 | - tagalign
23 | - depguard
24 |
25 | issues:
26 | exclude-rules:
27 | - path: _test\.go
28 | linters:
29 | - gocyclo
30 | - errcheck
31 | - dupl
32 | - goconst
33 | - funlen
34 | - scopelint
35 | - gocognit
36 | - paralleltest
37 | - errorlint
38 | - forcetypeassert
39 | - cyclop
40 | - maintidx
41 | - path: doc\.go
42 | linters:
43 | - lll
44 | - gofmt
45 | - goimports
--------------------------------------------------------------------------------
/testdata/valid/pod.yaml:
--------------------------------------------------------------------------------
1 | apiVersion:
2 | kind: Pod
3 | metadata:
4 | name: redis
5 | master: true
6 | spec:
7 | containers:
8 | - name: redis
9 | image: redis:5.0.4
10 | command:
11 | - redis-server
12 | - "/redis-master/redis.conf"
13 | env:
14 | - name: MASTER
15 | value: "true"
16 | ports:
17 | - containerPort: 6379
18 | resources:
19 | limits:
20 | cpu: "0.1"
21 | volumeMounts:
22 | - mountPath: /redis-master-data
23 | name: data
24 | - mountPath: /redis-master
25 | name: config
26 | args:
27 | "-w":
28 | value: "true"
29 | "--mem":
30 | value: "low"
31 | volumes:
32 | - name: data
33 | - name: config
34 | configMap:
35 | name: example-redis-config
36 | items:
37 | - key: redis-config
38 | path: redis.conf
--------------------------------------------------------------------------------
/testdata/invalid/pod.toml:
--------------------------------------------------------------------------------
1 | [metadata]
2 | name = "redis"
3 |
4 | [spec]
5 |
6 | [[spec.containers]]
7 | name = "redis"
8 | command = [
9 | "redis-server",
10 | "/redis-master/redis.conf"
11 | ]
12 |
13 | [spec.containers.resources]
14 |
15 | [spec.containers.resources.limits]
16 | cpu = "0.1"
17 |
18 | [[spec.containers.env]]
19 | name = "MASTER"
20 | value = "true"
21 |
22 | [[spec.containers.ports]]
23 | containerPort = 6379.0
24 |
25 | [[spec.containers.volumeMounts]]
26 | mountPath = "/redis-master-data"
27 | name = "data"
28 |
29 | [[spec.containers.volumeMounts]]
30 | mountPath = "/redis-master"
31 | name = "config"
32 |
33 | [spec.containers.args]
34 | "-w" = { value = "" }
35 | "-o" = { }
36 |
37 | [[spec.volumes]]
38 | name = "data"
39 |
40 | [spec.volumes.configMap]
41 | name = "example-data"
42 |
43 | [[spec.volumes]]
44 |
45 | [spec.volumes.configMap]
46 | name = "example-redis-config"
47 |
48 | [[spec.volumes.configMap.items]]
49 | key = "redis-config"
50 | path = "redis.conf"
--------------------------------------------------------------------------------
/testdata/valid/pod.toml:
--------------------------------------------------------------------------------
1 | kind = "Pod"
2 |
3 | [metadata]
4 | name = "redis"
5 | master = true
6 |
7 | [spec]
8 |
9 | [[spec.containers]]
10 | name = "redis"
11 | image = "redis:5.0.4"
12 | command = [
13 | "redis-server",
14 | "/redis-master/redis.conf"
15 | ]
16 |
17 | [spec.containers.resources]
18 |
19 | [spec.containers.resources.limits]
20 | cpu = "0.1"
21 |
22 | [[spec.containers.env]]
23 | name = "MASTER"
24 | value = "true"
25 |
26 | [[spec.containers.ports]]
27 | containerPort = 6379.0
28 |
29 | [[spec.containers.volumeMounts]]
30 | mountPath = "/redis-master-data"
31 | name = "data"
32 |
33 | [[spec.containers.volumeMounts]]
34 | mountPath = "/redis-master"
35 | name = "config"
36 |
37 | [spec.containers.args]
38 | "-w" = { value = "true" }
39 | "--mem" = { value = "low" }
40 |
41 | [[spec.volumes]]
42 | name = "data"
43 |
44 | [[spec.volumes]]
45 | name = "config"
46 |
47 | [spec.volumes.configMap]
48 | name = "example-redis-config"
49 |
50 | [[spec.volumes.configMap.items]]
51 | key = "redis-config"
52 | path = "redis.conf"
--------------------------------------------------------------------------------
/testdata/invalid/pod.json:
--------------------------------------------------------------------------------
1 | {
2 | "apiVersion": null,
3 | "metadata": {
4 | "name": "redis"
5 | },
6 | "spec": {
7 | "containers": [
8 | {
9 | "name": "redis",
10 | "command": [
11 | "redis-server",
12 | "/redis-master/redis.conf"
13 | ],
14 | "env": [
15 | {
16 | "name": "MASTER",
17 | "value": "true"
18 | }
19 | ],
20 | "ports": [
21 | {
22 | "containerPort": 6379
23 | }
24 | ],
25 | "resources": {
26 | "limits": {
27 | "cpu": "0.1"
28 | }
29 | },
30 | "volumeMounts": [
31 | {
32 | "mountPath": "/redis-master-data",
33 | "name": "data"
34 | },
35 | {
36 | "mountPath": "/redis-master",
37 | "name": "config"
38 | }
39 | ],
40 | "args": {
41 | "-w": {
42 | "value": ""
43 | },
44 | "-o": {
45 | }
46 | }
47 | }
48 | ],
49 | "volumes": [
50 | {
51 | "name": "data",
52 | "configMap": {
53 | "name": "example-data"
54 | }
55 | },
56 | {
57 | "configMap": {
58 | "name": "example-redis-config",
59 | "items": [
60 | {
61 | "key": "redis-config",
62 | "path": "redis.conf"
63 | }
64 | ]
65 | }
66 | }
67 | ]
68 | }
69 | }
--------------------------------------------------------------------------------
/examples/env/env_test.go:
--------------------------------------------------------------------------------
1 | package env
2 |
3 | import (
4 | "fmt"
5 | "os"
6 |
7 | "github.com/kkyr/fig"
8 | )
9 |
10 | type Config struct {
11 | Database struct {
12 | Host string `validate:"required"`
13 | Port int `validate:"required"`
14 | Database string `validate:"required" fig:"db"`
15 | Username string `validate:"required"`
16 | Password string `validate:"required"`
17 | }
18 | Container struct {
19 | Args []string `default:"[/bin/sh]"`
20 | }
21 | }
22 |
23 | func ExampleLoad() {
24 | os.Clearenv()
25 | check(os.Setenv("APP_DATABASE_HOST", "pg.internal.corp"))
26 | check(os.Setenv("APP_DATABASE_USERNAME", "mickey"))
27 | check(os.Setenv("APP_DATABASE_PASSWORD", "mouse"))
28 | check(os.Setenv("APP_CONTAINER_ARGS", "[-p,5050:5050]"))
29 |
30 | var cfg Config
31 | err := fig.Load(&cfg, fig.UseEnv("app"))
32 | check(err)
33 |
34 | fmt.Println(cfg.Database.Host)
35 | fmt.Println(cfg.Database.Port)
36 | fmt.Println(cfg.Database.Database)
37 | fmt.Println(cfg.Database.Username)
38 | fmt.Println(cfg.Database.Password)
39 | fmt.Println(cfg.Container.Args)
40 |
41 | // Output:
42 | // pg.internal.corp
43 | // 5432
44 | // users
45 | // mickey
46 | // mouse
47 | // [-p 5050:5050]
48 | }
49 |
50 | func check(err error) {
51 | if err != nil {
52 | panic(err)
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/testdata/valid/pod.json:
--------------------------------------------------------------------------------
1 | {
2 | "apiVersion": null,
3 | "kind": "Pod",
4 | "metadata": {
5 | "name": "redis",
6 | "master": true
7 | },
8 | "spec": {
9 | "containers": [
10 | {
11 | "name": "redis",
12 | "image": "redis:5.0.4",
13 | "command": [
14 | "redis-server",
15 | "/redis-master/redis.conf"
16 | ],
17 | "env": [
18 | {
19 | "name": "MASTER",
20 | "value": "true"
21 | }
22 | ],
23 | "ports": [
24 | {
25 | "containerPort": 6379
26 | }
27 | ],
28 | "resources": {
29 | "limits": {
30 | "cpu": "0.1"
31 | }
32 | },
33 | "volumeMounts": [
34 | {
35 | "mountPath": "/redis-master-data",
36 | "name": "data"
37 | },
38 | {
39 | "mountPath": "/redis-master",
40 | "name": "config"
41 | }
42 | ],
43 | "args": {
44 | "-w": {
45 | "value": "true"
46 | },
47 | "--mem": {
48 | "value": "low"
49 | }
50 | }
51 | }
52 | ],
53 | "volumes": [
54 | {
55 | "name": "data"
56 | },
57 | {
58 | "name": "config",
59 | "configMap": {
60 | "name": "example-redis-config",
61 | "items": [
62 | {
63 | "key": "redis-config",
64 | "path": "redis.conf"
65 | }
66 | ]
67 | }
68 | }
69 | ]
70 | }
71 | }
--------------------------------------------------------------------------------
/util.go:
--------------------------------------------------------------------------------
1 | package fig
2 |
3 | import (
4 | "os"
5 | "reflect"
6 | "strings"
7 | "time"
8 | )
9 |
10 | // stringSlice converts a Go slice represented as a string
11 | // into an actual slice. The enclosing square brackets
12 | // are not necessary.
13 | // fields should be separated by a comma.
14 | //
15 | // "[1,2,3]" ---> []string{"1", "2", "3"}
16 | // " foo , bar" ---> []string{" foo ", " bar"}
17 | func stringSlice(s string) []string {
18 | s = strings.TrimSuffix(strings.TrimPrefix(s, "["), "]")
19 | return strings.Split(s, ",")
20 | }
21 |
22 | // fileExists returns true if the file exists and is not a
23 | // directory.
24 | func fileExists(filename string) bool {
25 | info, err := os.Stat(filename)
26 | if os.IsNotExist(err) {
27 | return false
28 | }
29 | return !info.IsDir()
30 | }
31 |
32 | // isStructPtr reports whether i is a pointer to a struct.
33 | func isStructPtr(i interface{}) bool {
34 | v := reflect.ValueOf(i)
35 | return v.Kind() == reflect.Ptr && v.Elem().Kind() == reflect.Struct
36 | }
37 |
38 | // isZero reports whether v is its zero value for its type.
39 | func isZero(v reflect.Value) bool {
40 | switch v.Kind() {
41 | case reflect.Ptr, reflect.Interface:
42 | return v.IsNil()
43 | case reflect.Slice, reflect.Array:
44 | return v.Len() == 0
45 | case reflect.Struct:
46 | if t, ok := v.Interface().(time.Time); ok {
47 | return t.IsZero()
48 | }
49 | return false
50 | case reflect.Invalid:
51 | return true
52 | default:
53 | return v.IsZero()
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/examples/custom/custom_test.go:
--------------------------------------------------------------------------------
1 | package custom
2 |
3 | import (
4 | "fmt"
5 | "strings"
6 |
7 | "github.com/kkyr/fig"
8 | )
9 |
10 | type ListenerType uint
11 |
12 | const (
13 | ListenerUnix ListenerType = iota
14 | ListenerTCP
15 | ListenerTLS
16 | )
17 |
18 | type Config struct {
19 | App struct {
20 | Environment string `fig:"environment" validate:"required"`
21 | } `fig:"app"`
22 | Server struct {
23 | Host string `fig:"host" default:"0.0.0.0"`
24 | Port int `fig:"port" default:"80"`
25 | Listener ListenerType `fig:"listener_type" default:"tcp"`
26 | } `fig:"server"`
27 | }
28 |
29 | func ExampleLoad() {
30 | var cfg Config
31 | err := fig.Load(&cfg)
32 | if err != nil {
33 | panic(err)
34 | }
35 |
36 | fmt.Println(cfg.App.Environment)
37 | fmt.Println(cfg.Server.Host)
38 | fmt.Println(cfg.Server.Port)
39 | fmt.Println(cfg.Server.Listener)
40 |
41 | // Output:
42 | // dev
43 | // 0.0.0.0
44 | // 443
45 | // tcp
46 | }
47 |
48 | func (l *ListenerType) UnmarshalString(v string) error {
49 | switch strings.ToLower(v) {
50 | case "unix":
51 | *l = ListenerUnix
52 | case "tcp":
53 | *l = ListenerTCP
54 | case "tls":
55 | *l = ListenerTLS
56 | default:
57 | return fmt.Errorf("unknown listener type: %s", v)
58 | }
59 | return nil
60 | }
61 |
62 | func (l ListenerType) String() string {
63 | switch l {
64 | case ListenerUnix:
65 | return "unix"
66 | case ListenerTCP:
67 | return "tcp"
68 | case ListenerTLS:
69 | return "tls"
70 | default:
71 | return "unknown"
72 | }
73 | }
74 |
--------------------------------------------------------------------------------
/examples/config/config_test.go:
--------------------------------------------------------------------------------
1 | package config
2 |
3 | import (
4 | "fmt"
5 | "regexp"
6 | "time"
7 |
8 | "github.com/kkyr/fig"
9 | )
10 |
11 | type Config struct {
12 | App struct {
13 | Environment string `fig:"environment" validate:"required"`
14 | } `fig:"app"`
15 | Server struct {
16 | Host string `fig:"host" default:"0.0.0.0"`
17 | Port int `fig:"port" default:"80"`
18 | ReadTimeout time.Duration `fig:"read_timeout" default:"30s"`
19 | WriteTimeout time.Duration `fig:"write_timeout" default:"30s"`
20 | } `fig:"server"`
21 | Logger struct {
22 | Level string `fig:"level" default:"info"`
23 | Pattern *regexp.Regexp `fig:"pattern" default:".*"`
24 | } `fig:"logger"`
25 | Certificate struct {
26 | Version int `fig:"version"`
27 | DNSNames []string `fig:"dns_names" default:"[kkyr,kkyr.io]"`
28 | Expiration time.Time `fig:"expiration" validate:"required"`
29 | } `fig:"certificate"`
30 | }
31 |
32 | func ExampleLoad() {
33 | var cfg Config
34 | err := fig.Load(&cfg, fig.TimeLayout("2006-01-02"))
35 | if err != nil {
36 | panic(err)
37 | }
38 |
39 | fmt.Println(cfg.App.Environment)
40 | fmt.Println(cfg.Server.Host)
41 | fmt.Println(cfg.Server.Port)
42 | fmt.Println(cfg.Server.ReadTimeout)
43 | fmt.Println(cfg.Server.WriteTimeout)
44 | fmt.Println(cfg.Logger.Level)
45 | fmt.Println(cfg.Logger.Pattern)
46 | fmt.Println(cfg.Certificate.Version)
47 | fmt.Println(cfg.Certificate.DNSNames)
48 | fmt.Println(cfg.Certificate.Expiration.Format("2006-01-02"))
49 |
50 | // Output:
51 | // dev
52 | // 0.0.0.0
53 | // 443
54 | // 1m0s
55 | // 30s
56 | // debug
57 | // [a-z]+
58 | // 1
59 | // [kkyr kkyr.io]
60 | // 2020-12-01
61 | }
62 |
--------------------------------------------------------------------------------
/go.sum:
--------------------------------------------------------------------------------
1 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
2 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
3 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
4 | github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
5 | github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
6 | github.com/pelletier/go-toml/v2 v2.1.0 h1:FnwAJ4oYMvbT/34k9zzHuZNrhlz48GB3/s6at6/MHO4=
7 | github.com/pelletier/go-toml/v2 v2.1.0/go.mod h1:tJU2Z3ZkXwnxa4DPO899bsyIoywizdUvyaeZurnPPDc=
8 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
9 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
10 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
11 | github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
12 | github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
13 | github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
14 | github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
15 | github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
16 | github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
17 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
18 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
19 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
20 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
21 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 | # fig
14 |
15 | fig is a tiny library for loading an application's configuration into a Go struct.
16 |
17 | ## Why fig?
18 |
19 | - 🛠️ Define your **configuration**, **validations** and **defaults** all within a single struct.
20 | - 🌍 Easily load your configuration from a **file**, the **environment**, or both.
21 | - ⏰ Decode strings into `Time`, `Duration`, `Regexp`, or any custom type that satisfies the `StringUnmarshaler` interface.
22 | - 🗂️ Compatible with `yaml`, `json`, and `toml` file formats.
23 | - 🧩 Only three external dependencies.
24 |
25 | ## Getting Started
26 |
27 | `$ go get -d github.com/kkyr/fig`
28 |
29 | Define your config file:
30 |
31 | ```yaml
32 | # config.yaml
33 |
34 | build: "2020-01-09T12:30:00Z"
35 |
36 | server:
37 | ports:
38 | - 8080
39 | cleanup: 1h
40 |
41 | logger:
42 | level: "warn"
43 | trace: true
44 | ```
45 |
46 | Define your struct along with _validations_ or _defaults_:
47 |
48 | ```go
49 | package main
50 |
51 | import (
52 | "fmt"
53 |
54 | "github.com/kkyr/fig"
55 | )
56 |
57 | type Config struct {
58 | Build time.Time `fig:"build" validate:"required"`
59 | Server struct {
60 | Host string `fig:"host" default:"127.0.0.1"`
61 | Ports []int `fig:"ports" default:"[80,443]"`
62 | Cleanup time.Duration `fig:"cleanup" default:"30m"`
63 | }
64 | Logger struct {
65 | Level string `fig:"level" default:"info"`
66 | Pattern *regexp.Regexp `fig:"pattern" default:".*"`
67 | Trace bool `fig:"trace"`
68 | }
69 | }
70 |
71 | func main() {
72 | var cfg Config
73 | err := fig.Load(&cfg)
74 | // error handling omitted
75 |
76 | fmt.Printf("%+v\n", cfg)
77 | // {Build:2019-12-25T00:00:00Z Server:{Host:127.0.0.1 Ports:[8080] Cleanup:1h0m0s} Logger:{Level:warn Pattern:.* Trace:true}}
78 | }
79 | ```
80 |
81 | Fields marked as _required_ are checked to ensure they're not empty, and _default_ values are applied to fill in those that are empty.
82 |
83 | ## Environment
84 |
85 | By default, fig will only look for values in a config file. To also include values from the environment, use the `UseEnv` option:
86 |
87 | ```go
88 | fig.Load(&cfg, fig.UseEnv("APP_PREFIX"))
89 | ```
90 |
91 | In case of conflicts, values from the environment take precedence.
92 |
93 | ## Usage
94 |
95 | See usage [examples](/examples).
96 |
97 | ## Documentation
98 |
99 | For detailed documentation, visit [go.dev](https://pkg.go.dev/github.com/kkyr/fig?tab=doc).
100 |
101 | ## Contributing
102 |
103 | PRs are welcome! Please explain your motivation for the change in your PR and ensure your change is properly tested and documented.
104 |
--------------------------------------------------------------------------------
/util_test.go:
--------------------------------------------------------------------------------
1 | package fig
2 |
3 | import (
4 | "path/filepath"
5 | "reflect"
6 | "regexp"
7 | "testing"
8 | "time"
9 | )
10 |
11 | func Test_stringSlice(t *testing.T) {
12 | for _, tc := range []struct {
13 | In string
14 | Want []string
15 | }{
16 | {
17 | In: "false",
18 | Want: []string{"false"},
19 | },
20 | {
21 | In: "1,5,2",
22 | Want: []string{"1", "5", "2"},
23 | },
24 | {
25 | In: "[hello , world]",
26 | Want: []string{"hello ", " world"},
27 | },
28 | {
29 | In: "[foo]",
30 | Want: []string{"foo"},
31 | },
32 | } {
33 | t.Run(tc.In, func(t *testing.T) {
34 | got := stringSlice(tc.In)
35 | if !reflect.DeepEqual(tc.Want, got) {
36 | t.Fatalf("want %+v, got %+v", tc.Want, got)
37 | }
38 | })
39 | }
40 | }
41 |
42 | func Test_fileExists(t *testing.T) {
43 | dir := filepath.Join("testdata", "valid")
44 | ok := fileExists(dir)
45 | if ok {
46 | t.Errorf("fileExists(dir) == true, expected false")
47 | }
48 |
49 | bad := "oompa-loompa"
50 | ok = fileExists(bad)
51 | if ok {
52 | t.Errorf("fileExists(bad) == true, expected false")
53 | }
54 |
55 | good := "fig.go"
56 | ok = fileExists(good)
57 | if !ok {
58 | t.Errorf("fileExists(good) == false, expected true")
59 | }
60 | }
61 |
62 | func Test_isStructPtr(t *testing.T) {
63 | type cfgType struct{}
64 |
65 | var cfg cfgType
66 | ok := isStructPtr(cfg)
67 | if ok {
68 | t.Errorf("isStructPtr(cfg) == true, expected false")
69 | }
70 |
71 | ok = isStructPtr(&cfg)
72 | if !ok {
73 | t.Errorf("isStructPtr(*cfg) == false, expected true")
74 | }
75 |
76 | var i int
77 | ok = isStructPtr(&i)
78 | if ok {
79 | t.Errorf("isStructPtr(*i) == true, expected false")
80 | }
81 | }
82 |
83 | func Test_isZero(t *testing.T) {
84 | t.Run("nil slice is zero", func(t *testing.T) {
85 | var s []string
86 | if isZero(reflect.ValueOf(s)) == false {
87 | t.Fatalf("isZero == false")
88 | }
89 | })
90 |
91 | t.Run("empty slice is zero", func(t *testing.T) {
92 | s := []string{}
93 | if isZero(reflect.ValueOf(s)) == false {
94 | t.Fatalf("isZero == false")
95 | }
96 | })
97 |
98 | t.Run("nil pointer is zero", func(t *testing.T) {
99 | var s *string
100 | if isZero(reflect.ValueOf(s)) == false {
101 | t.Fatalf("isZero == false")
102 | }
103 | })
104 |
105 | t.Run("non-nil pointer is not zero", func(t *testing.T) {
106 | var a *string
107 | b := "b"
108 | a = &b
109 |
110 | if isZero(reflect.ValueOf(a)) == true {
111 | t.Fatalf("isZero == true")
112 | }
113 | })
114 |
115 | t.Run("struct is not zero", func(t *testing.T) {
116 | a := struct {
117 | B string
118 | }{}
119 |
120 | if isZero(reflect.ValueOf(a)) == true {
121 | t.Fatalf("isZero == true")
122 | }
123 | })
124 |
125 | t.Run("zero time is zero", func(t *testing.T) {
126 | td := time.Time{}
127 |
128 | if isZero(reflect.ValueOf(td)) == false {
129 | t.Fatalf("isZero == false")
130 | }
131 | })
132 |
133 | t.Run("non-zero time is not zero", func(t *testing.T) {
134 | td := time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC)
135 |
136 | if isZero(reflect.ValueOf(td)) == true {
137 | t.Fatalf("isZero == true")
138 | }
139 | })
140 |
141 | t.Run("zero regexp is zero", func(t *testing.T) {
142 | var re *regexp.Regexp
143 |
144 | if isZero(reflect.ValueOf(re)) == false {
145 | t.Fatalf("isZero == false")
146 | }
147 | })
148 |
149 | t.Run("non-zero regexp is not zero", func(t *testing.T) {
150 | re := regexp.MustCompile(".*")
151 |
152 | if isZero(reflect.ValueOf(re)) == true {
153 | t.Fatalf("isZero == true")
154 | }
155 | })
156 |
157 | t.Run("reflect invalid is zero", func(t *testing.T) {
158 | var x interface{}
159 |
160 | if isZero(reflect.ValueOf(&x).Elem().Elem()) == false {
161 | t.Fatalf("isZero == false")
162 | }
163 | })
164 |
165 | t.Run("0 int is zero", func(t *testing.T) {
166 | x := 0
167 |
168 | if isZero(reflect.ValueOf(x)) == false {
169 | t.Fatalf("isZero == false")
170 | }
171 | })
172 |
173 | t.Run("5 int is not zero", func(t *testing.T) {
174 | x := 5
175 |
176 | if isZero(reflect.ValueOf(x)) == true {
177 | t.Fatalf("isZero == true")
178 | }
179 | })
180 | }
181 |
--------------------------------------------------------------------------------
/option.go:
--------------------------------------------------------------------------------
1 | package fig
2 |
3 | // Option configures how fig loads the configuration.
4 | type Option func(f *fig)
5 |
6 | // File returns an option that configures the filename that fig
7 | // looks for to provide the config values.
8 | //
9 | // The name must include the extension of the file. Supported
10 | // file types are `yaml`, `yml`, `json` and `toml`.
11 | //
12 | // fig.Load(&cfg, fig.File("config.toml"))
13 | //
14 | // If this option is not used then fig looks for a file with name `config.yaml`.
15 | func File(name string) Option {
16 | return func(f *fig) {
17 | f.filename = name
18 | }
19 | }
20 |
21 | // IgnoreFile returns an option which disables any file lookup.
22 | //
23 | // This option effectively renders any `File` and `Dir` options useless. This option
24 | // is most useful in conjunction with the `UseEnv` option when you want to provide
25 | // config values only via environment variables.
26 | //
27 | // fig.Load(&cfg, fig.IgnoreFile(), fig.UseEnv("my_app"))
28 | func IgnoreFile() Option {
29 | return func(f *fig) {
30 | f.ignoreFile = true
31 | }
32 | }
33 |
34 | // Dirs returns an option that configures the directories that fig searches
35 | // to find the configuration file.
36 | //
37 | // Directories are searched sequentially and the first one with a matching config file is used.
38 | //
39 | // This is useful when you don't know where exactly your configuration will be during run-time:
40 | //
41 | // fig.Load(&cfg, fig.Dirs(".", "/etc/myapp", "/home/user/myapp"))
42 | //
43 | // If this option is not used then fig looks in the directory it is run from.
44 | func Dirs(dirs ...string) Option {
45 | return func(f *fig) {
46 | f.dirs = dirs
47 | }
48 | }
49 |
50 | // Tag returns an option that configures the tag key that fig uses
51 | // when for the alt name struct tag key in fields.
52 | //
53 | // fig.Load(&cfg, fig.Tag("config"))
54 | //
55 | // If this option is not used then fig uses the tag `fig`.
56 | func Tag(tag string) Option {
57 | return func(f *fig) {
58 | f.tag = tag
59 | }
60 | }
61 |
62 | // TimeLayout returns an option that conmfigures the time layout that fig uses when
63 | // parsing a time in a config file or in the default tag for time.Time fields.
64 | //
65 | // fig.Load(&cfg, fig.TimeLayout("2006-01-02"))
66 | //
67 | // If this option is not used then fig parses times using `time.RFC3339` layout.
68 | func TimeLayout(layout string) Option {
69 | return func(f *fig) {
70 | f.timeLayout = layout
71 | }
72 | }
73 |
74 | // UseEnv returns an option that configures fig to additionally load values
75 | // from the environment.
76 | //
77 | // fig.Load(&cfg, fig.UseEnv("my_app"))
78 | //
79 | // Values loaded from the environment overwrite values loaded by the config file (if any).
80 | //
81 | // Fig looks for environment variables in the format PREFIX_FIELD_PATH or
82 | // FIELD_PATH if prefix is empty. Prefix is capitalised regardless of what
83 | // is provided. The field's path is formed by prepending its name with the
84 | // names of all surrounding fields up to the root struct. If a field has
85 | // an alternative name defined inside a struct tag then that name is
86 | // preferred.
87 | //
88 | // type Config struct {
89 | // Build time.Time
90 | // LogLevel string `fig:"log_level"`
91 | // Server struct {
92 | // Host string
93 | // }
94 | // }
95 | //
96 | // With the struct above and UseEnv("myapp") fig would search for the following
97 | // environment variables:
98 | //
99 | // MYAPP_BUILD
100 | // MYAPP_LOG_LEVEL
101 | // MYAPP_SERVER_HOST
102 | func UseEnv(prefix string) Option {
103 | return func(f *fig) {
104 | f.useEnv = true
105 | f.envPrefix = prefix
106 | }
107 | }
108 |
109 | // UseStrict returns an option that configures fig to return an error if
110 | // there exists additional fields in the config file that are not defined
111 | // in the config struct.
112 | //
113 | // fig.Load(&cfg, fig.UseStrict())
114 | //
115 | // If this option is not used then fig ignores any additional fields in the config file.
116 | func UseStrict() Option {
117 | return func(f *fig) {
118 | f.useStrict = true
119 | }
120 | }
121 |
122 | // AllowNoFile returns an option that configures fig to proceed even when no config
123 | // file is found. Loading defaults and values from environment variables will still
124 | // work as expected.
125 | //
126 | // fig.Load(&cfg, fig.AllowNoFile())
127 | //
128 | // If this option is not used then fig returns [ErrFileNotFound] as soon as none are
129 | // discovered.
130 | func AllowNoFile() Option {
131 | return func(f *fig) {
132 | f.allowNoFile = true
133 | }
134 | }
135 |
--------------------------------------------------------------------------------
/field_test.go:
--------------------------------------------------------------------------------
1 | package fig
2 |
3 | import (
4 | "reflect"
5 | "testing"
6 | )
7 |
8 | func Test_flattenCfg(t *testing.T) {
9 | type J struct {
10 | K bool `fig:"k"`
11 | }
12 | cfg := struct {
13 | A string
14 | B struct {
15 | C []struct {
16 | D *int
17 | }
18 | }
19 | E *struct {
20 | F []string
21 | } `fig:"e"`
22 | G *struct {
23 | H int
24 | }
25 | i int
26 | J
27 | }{}
28 | cfg.B.C = []struct{ D *int }{{}, {}}
29 | cfg.E = &struct{ F []string }{}
30 |
31 | fields := flattenCfg(&cfg, "fig")
32 | if len(fields) != 10 {
33 | t.Fatalf("len(fields) == %d, expected %d", len(fields), 10)
34 | }
35 | checkField(t, fields[0], "A", "A")
36 | checkField(t, fields[1], "B", "B")
37 | checkField(t, fields[2], "C", "B.C")
38 | checkField(t, fields[3], "D", "B.C[0].D")
39 | checkField(t, fields[4], "D", "B.C[1].D")
40 | checkField(t, fields[5], "e", "e")
41 | checkField(t, fields[6], "F", "e.F")
42 | checkField(t, fields[7], "G", "G")
43 | checkField(t, fields[8], "J", "J")
44 | checkField(t, fields[9], "k", "J.k")
45 | }
46 |
47 | func Test_flattenCfg_Map(t *testing.T) {
48 | type A struct {
49 | B string `fig:"b"`
50 | }
51 |
52 | cfg := struct {
53 | D map[string]A
54 | }{}
55 | cfg.D = map[string]A{
56 | "key1": {B: "b"},
57 | }
58 |
59 | fields := flattenCfg(&cfg, "fig")
60 | if len(fields) != 3 {
61 | t.Fatalf("len(fields) == %d, expected %d", len(fields), 3)
62 | }
63 | checkField(t, fields[0], "D", "D")
64 | checkField(t, fields[1], "[key1]", "D[key1]")
65 | checkField(t, fields[2], "b", "D[key1].b")
66 | }
67 |
68 | func Test_newStructField(t *testing.T) {
69 | cfg := struct {
70 | A int `fig:"a" default:"5" validate:"required"`
71 | }{}
72 | parent := &field{
73 | v: reflect.ValueOf(&cfg).Elem(),
74 | t: reflect.ValueOf(&cfg).Elem().Type(),
75 | sliceIdx: -1,
76 | }
77 |
78 | f := newStructField(parent, 0, "fig")
79 | if f.parent != parent {
80 | t.Errorf("f.parent == %p, expected %p", f.parent, f)
81 | }
82 | if f.sliceIdx != -1 {
83 | t.Errorf("f.sliceIdx == %d, expected %d", f.sliceIdx, -1)
84 | }
85 | if f.v.Kind() != reflect.Int {
86 | t.Errorf("f.v.Kind == %v, expected %v", f.v.Kind(), reflect.Int)
87 | }
88 | if f.v.Type() != reflect.TypeOf(cfg.A) {
89 | t.Errorf("f.v.Type == %v, expected %v", f.v.Kind(), reflect.TypeOf(cfg.A))
90 | }
91 | if f.altName != "a" {
92 | t.Errorf("f.altName == %s, expected %s", f.altName, "a")
93 | }
94 | if !f.required {
95 | t.Errorf("f.required == false")
96 | }
97 | if !f.setDefault {
98 | t.Errorf("f.setDefault == false")
99 | }
100 | if f.defaultVal != "5" {
101 | t.Errorf("f.defaultVal == %s, expected %s", f.defaultVal, "5")
102 | }
103 | }
104 |
105 | func Test_newSliceField(t *testing.T) {
106 | cfg := struct {
107 | A []struct {
108 | B int
109 | } `fig:"aaa"`
110 | }{}
111 | cfg.A = []struct {
112 | B int
113 | }{{B: 5}}
114 |
115 | parent := &field{
116 | v: reflect.ValueOf(&cfg).Elem().Field(0),
117 | t: reflect.ValueOf(&cfg).Elem().Field(0).Type(),
118 | st: reflect.ValueOf(&cfg).Elem().Type().Field(0),
119 | sliceIdx: -1,
120 | }
121 |
122 | f := newSliceField(parent, 0, "fig")
123 | if f.parent != parent {
124 | t.Errorf("f.parent == %p, expected %p", f.parent, f)
125 | }
126 | if f.sliceIdx != 0 {
127 | t.Errorf("f.sliceIdx == %d, expected %d", f.sliceIdx, 0)
128 | }
129 | if f.v.Kind() != reflect.Struct {
130 | t.Errorf("f.v.Kind == %v, expected %v", f.v.Kind(), reflect.Int)
131 | }
132 | if f.altName != "aaa" {
133 | t.Errorf("f.altName == %s, expected %s", f.altName, "a")
134 | }
135 | if f.required {
136 | t.Errorf("f.required == true")
137 | }
138 | if f.setDefault {
139 | t.Errorf("f.setDefault == true")
140 | }
141 | if f.defaultVal != "" {
142 | t.Errorf("f.defaultVal == %s, expected %s", f.defaultVal, "")
143 | }
144 | }
145 |
146 | func Test_parseTag(t *testing.T) {
147 | for _, tc := range []struct {
148 | tagVal string
149 | want structTag
150 | }{
151 | {
152 | tagVal: "",
153 | want: structTag{},
154 | },
155 | {
156 | tagVal: `fig:"a"`,
157 | want: structTag{altName: "a"},
158 | },
159 | {
160 | tagVal: `fig:"a,"`,
161 | want: structTag{altName: "a"},
162 | },
163 | {
164 | tagVal: `fig:"a" default:"go"`,
165 | want: structTag{altName: "a", setDefault: true, defaultVal: "go"},
166 | },
167 | {
168 | tagVal: `fig:"b" validate:"required"`,
169 | want: structTag{altName: "b", required: true},
170 | },
171 | {
172 | tagVal: `fig:"b" validate:"required" default:"go"`,
173 | want: structTag{altName: "b", required: true, setDefault: true, defaultVal: "go"},
174 | },
175 | {
176 | tagVal: `fig:"c,omitempty"`,
177 | want: structTag{altName: "c"},
178 | },
179 | } {
180 | t.Run(tc.tagVal, func(t *testing.T) {
181 | tag := parseTag(reflect.StructTag(tc.tagVal), "fig")
182 | if !reflect.DeepEqual(tc.want, tag) {
183 | t.Fatalf("parseTag() == %+v, expected %+v", tag, tc.want)
184 | }
185 | })
186 | }
187 | }
188 |
189 | func Test_squashPath(t *testing.T) {
190 | cfg := struct {
191 | Base struct {
192 | Env string
193 | ServiceName string
194 | Nested []struct{ Val string }
195 | Logging struct {
196 | Level int
197 | }
198 | } `fig:",squash"`
199 | App struct {
200 | Custom string
201 | }
202 | }{}
203 | cfg.Base.Nested = []struct{ Val string }{{}, {}}
204 |
205 | fields := flattenCfg(&cfg, "fig")
206 | if len(fields) != 10 {
207 | t.Fatalf("len(fields) == %d, expected %d", len(fields), 10)
208 | }
209 | checkField(t, fields[0], "Base", "")
210 | checkField(t, fields[1], "Env", "Env")
211 | checkField(t, fields[2], "ServiceName", "ServiceName")
212 | checkField(t, fields[3], "Nested", "Nested")
213 | checkField(t, fields[4], "Val", "Nested[0].Val")
214 | checkField(t, fields[5], "Val", "Nested[1].Val")
215 | checkField(t, fields[6], "Logging", "Logging")
216 | checkField(t, fields[7], "Level", "Logging.Level")
217 | checkField(t, fields[8], "App", "App")
218 | checkField(t, fields[9], "Custom", "App.Custom")
219 | }
220 |
221 | func checkField(t *testing.T, f *field, name, path string) {
222 | t.Helper()
223 | if f.name() != name {
224 | t.Errorf("f.name() == %s, expected %s", f.name(), name)
225 | }
226 | if f.path("fig") != path {
227 | t.Errorf("f.path() == %s, expected %s", f.path("fig"), path)
228 | }
229 | }
230 |
--------------------------------------------------------------------------------
/field.go:
--------------------------------------------------------------------------------
1 | package fig
2 |
3 | import (
4 | "fmt"
5 | "reflect"
6 | "strings"
7 | )
8 |
9 | // flattenCfg recursively flattens a cfg struct into
10 | // a slice of its constituent fields.
11 | func flattenCfg(cfg interface{}, tagKey string) []*field {
12 | root := &field{
13 | v: reflect.ValueOf(cfg).Elem(),
14 | t: reflect.ValueOf(cfg).Elem().Type(),
15 | sliceIdx: -1,
16 | }
17 | fs := make([]*field, 0)
18 | flattenField(root, &fs, tagKey)
19 | return fs
20 | }
21 |
22 | // flattenField recursively flattens a field into its
23 | // constituent fields, filling fs as it goes.
24 | func flattenField(f *field, fs *[]*field, tagKey string) {
25 | for (f.v.Kind() == reflect.Ptr || f.v.Kind() == reflect.Interface) && !f.v.IsNil() {
26 | f.v = f.v.Elem()
27 | f.t = f.v.Type()
28 | }
29 |
30 | switch f.v.Kind() {
31 | case reflect.Struct:
32 | for i := 0; i < f.t.NumField(); i++ {
33 | unexported := f.t.Field(i).PkgPath != ""
34 | embedded := f.t.Field(i).Anonymous
35 | if unexported && !embedded {
36 | continue
37 | }
38 | child := newStructField(f, i, tagKey)
39 | *fs = append(*fs, child)
40 | flattenField(child, fs, tagKey)
41 | }
42 |
43 | case reflect.Slice, reflect.Array:
44 | switch f.t.Elem().Kind() {
45 | case reflect.Struct, reflect.Slice, reflect.Array, reflect.Ptr, reflect.Interface:
46 | for i := 0; i < f.v.Len(); i++ {
47 | child := newSliceField(f, i, tagKey)
48 | flattenField(child, fs, tagKey)
49 | }
50 | }
51 |
52 | case reflect.Map:
53 | for _, key := range f.v.MapKeys() {
54 | child := newMapField(f, key, tagKey)
55 | *fs = append(*fs, child)
56 | flattenField(child, fs, tagKey)
57 | }
58 | }
59 | }
60 |
61 | // newStructField is a constructor for a field that is a struct
62 | // member. idx is the field's index in the struct. tagKey is the
63 | // key of the tag that contains the field alt name (if any).
64 | func newStructField(parent *field, idx int, tagKey string) *field {
65 | f := &field{
66 | parent: parent,
67 | v: parent.v.Field(idx),
68 | t: parent.v.Field(idx).Type(),
69 | st: parent.t.Field(idx),
70 | sliceIdx: -1, // not applicable for struct fields
71 | }
72 | f.structTag = parseTag(f.st.Tag, tagKey)
73 | return f
74 | }
75 |
76 | // newStructField is a constructor for a field that is a slice
77 | // member. idx is the field's index in the slice. tagKey is the
78 | // key of the tag that contains the field alt name (if any).
79 | func newSliceField(parent *field, idx int, tagKey string) *field {
80 | f := &field{
81 | parent: parent,
82 | v: parent.v.Index(idx),
83 | t: parent.v.Index(idx).Type(),
84 | st: parent.st,
85 | sliceIdx: idx,
86 | }
87 | f.structTag = parseTag(f.st.Tag, tagKey)
88 | return f
89 | }
90 |
91 | // newMapField is a constructor for a field that is a map entry.
92 | // key is the key of the map entry, and tagKey is the key of the
93 | // tag that contains the field alt name (if any).
94 | func newMapField(parent *field, key reflect.Value, tagKey string) *field {
95 | f := &field{
96 | parent: parent,
97 | v: parent.v.MapIndex(key),
98 | t: parent.v.MapIndex(key).Type(),
99 | st: parent.st,
100 | sliceIdx: -1, // not applicable for map entries
101 | mapKey: &key,
102 | }
103 | f.structTag = parseTag(f.st.Tag, tagKey)
104 | return f
105 | }
106 |
107 | // field is a settable field of a config object.
108 | type field struct {
109 | parent *field
110 |
111 | v reflect.Value
112 | t reflect.Type
113 | st reflect.StructField
114 |
115 | sliceIdx int // >=0 if this field is a member of a slice.
116 | mapKey *reflect.Value // key of the map entry if this field is a map entry, nil otherwise.
117 |
118 | structTag
119 | }
120 |
121 | // name is the name of the field. if the field contains an alt name
122 | // in the struct that name is used, else it falls back to
123 | // the field's name as defined in the struct.
124 | // if this field is a slice field, then its name is simply its
125 | // index in the slice.
126 | func (f *field) name() string {
127 | if f.sliceIdx >= 0 {
128 | return fmt.Sprintf("[%d]", f.sliceIdx)
129 | }
130 | if f.mapKey != nil {
131 | return fmt.Sprintf("[%s]", f.mapKey.String())
132 | }
133 | if f.altName != "" {
134 | return f.altName
135 | }
136 | return f.st.Name
137 | }
138 |
139 | // path is a dot separated path consisting of all the names of
140 | // the field's ancestors starting from the topmost parent all the
141 | // way down to the field itself.
142 | //
143 | // Squashed structs will omit themselves from the path
144 | func (f *field) path(tagKey string) (path string) {
145 | var visit func(f *field, squashed bool)
146 | visit = func(f *field, squashed bool) {
147 | if f.parent != nil {
148 | visit(f.parent, false)
149 |
150 | // Check if we are squashed or not
151 | //
152 | // type Base struct { Env string }
153 | // type Config struct { Base `fig:",squash"`}
154 | //
155 | // In the above example, path to 'env' should be 'Env', not 'Base.Env'
156 | if f.parent.t.Kind() == reflect.Struct {
157 | parentField, ok := f.parent.t.FieldByName(f.st.Name)
158 | squashed = ok && parentField.Tag.Get(tagKey) == ",squash"
159 | }
160 | }
161 | if !squashed {
162 | path += f.name()
163 | }
164 | // if it's a slice/array we don't want a dot before the slice indexer
165 | // e.g. we want A[0].B instead of A.[0].B
166 | if f.t.Kind() != reflect.Slice && f.t.Kind() != reflect.Array && f.t.Kind() != reflect.Map {
167 | path += "."
168 | }
169 | }
170 | visit(f, false)
171 | return strings.Trim(path, ".")
172 | }
173 |
174 | // parseTag parses a fields struct tags into a more easy to use structTag.
175 | // key is the key of the struct tag which contains the field's alt name.
176 | func parseTag(tag reflect.StructTag, key string) (st structTag) {
177 | if val, ok := tag.Lookup(key); ok {
178 | i := strings.Index(val, ",")
179 | if i == -1 {
180 | i = len(val)
181 | }
182 | st.altName = val[:i]
183 | }
184 |
185 | if val := tag.Get("validate"); val == "required" {
186 | st.required = true
187 | }
188 |
189 | if val, ok := tag.Lookup("default"); ok {
190 | st.setDefault = true
191 | st.defaultVal = val
192 | }
193 |
194 | return
195 | }
196 |
197 | // structTag contains information gathered from parsing a field's tags.
198 | type structTag struct {
199 | altName string // the alt name of the field as defined in the tag.
200 | required bool // true if the tag contained a required validation key.
201 | setDefault bool // true if tag contained a default key.
202 | defaultVal string // the value of the default key.
203 | }
204 |
--------------------------------------------------------------------------------
/doc.go:
--------------------------------------------------------------------------------
1 | /*
2 | Package fig loads configuration files and/or environment variables into Go structs with extra juice for validating fields and setting defaults.
3 |
4 | Config files may be defined in yaml, json or toml format.
5 |
6 | When you call `Load()`, fig takes the following steps:
7 |
8 | 1. Fills config struct from the config file (if enabled)
9 | 2. Fills config struct from the environment (if enabled)
10 | 3. Sets defaults (where applicable)
11 | 4. Validates required fields (where applicable)
12 |
13 | # Example
14 |
15 | Define your configuration file in the root of your project:
16 |
17 | # config.yaml
18 |
19 | build: "2020-01-09T12:30:00Z"
20 |
21 | server:
22 | ports:
23 | - 8080
24 | cleanup: 1h
25 |
26 | logger:
27 | level: "warn"
28 | trace: true
29 |
30 | Define your struct and load it:
31 |
32 | package main
33 |
34 | import (
35 | "fmt"
36 |
37 | "github.com/kkyr/fig"
38 | )
39 |
40 |
41 | type Config struct {
42 | Build time.Time `fig:"build" validate:"required"`
43 | Server struct {
44 | Host string `fig:"host" default:"127.0.0.1"`
45 | Ports []int `fig:"ports" default:"[80,443]"`
46 | Cleanup time.Duration `fig:"cleanup" default:"30m"`
47 | }
48 | Logger struct {
49 | Level string `fig:"level" default:"info"`
50 | Trace bool `fig:"trace"`
51 | }
52 | }
53 |
54 | func main() {
55 | var cfg Config
56 | _ = fig.Load(&cfg)
57 |
58 | fmt.Printf("%+v\n", cfg)
59 | // Output: {Build:2019-12-25 00:00:00 +0000 UTC Server:{Host:127.0.0.1 Ports:[8080] Cleanup:1h0m0s} Logger:{Level:warn Trace:true}}
60 | }
61 |
62 | # Configuration
63 |
64 | Pass options as additional parameters to `Load()` to configure fig's behaviour.
65 |
66 | # IgnoreFile
67 |
68 | Do not look for any configuration file with `IgnoreFile()`.
69 |
70 | fig.Load(&cfg, fig.IgnoreFile())
71 |
72 | If IgnoreFile is given then any other configuration file related options like `File` and `Dirs` are simply ignored.
73 |
74 | File & Dirs
75 |
76 | By default fig searches for a file named `config.yaml` in the directory it is run from. Change the file and directories fig
77 | searches in with `File()` and `Dirs()`.
78 |
79 | fig.Load(&cfg,
80 | fig.File("settings.json"),
81 | fig.Dirs(".", "home/user/myapp", "/opt/myapp"),
82 | )
83 |
84 | Fig searches for the file in dirs sequentially and uses the first matching file.
85 |
86 | The decoder (yaml/json/toml) used is picked based on the file's extension.
87 |
88 | # Tag
89 |
90 | The struct tag key tag fig looks for to find the field's alt name can be changed using `Tag()`.
91 |
92 | type Config struct {
93 | Host string `yaml:"host" validate:"required"`
94 | Level string `yaml:"level" default:"info"`
95 | }
96 |
97 | var cfg Config
98 | fig.Load(&cfg, fig.Tag("yaml"))
99 |
100 | By default fig uses the tag key `fig`.
101 |
102 | # Environment
103 |
104 | Fig can be configured to additionally set fields using the environment.
105 | This behaviour can be enabled using the option `UseEnv(prefix)`. If loading from file is also enabled then first the struct is loaded
106 | from a config file and thus any values found in the environment will overwrite existing values in the struct.
107 |
108 | Prefix is a string that will be prepended to the keys that are searched in the environment. Although discouraged, prefix may be left empty.
109 |
110 | Fig searches for keys in the form PREFIX_FIELD_PATH, or if prefix is left empty then FIELD_PATH.
111 |
112 | A field's path is formed by prepending its name with the names of all the surrounding structs up to the root struct, upper-cased and separated by an underscore.
113 |
114 | If a field has an alt name defined in its struct tag then that name is preferred over its struct name.
115 |
116 | type Config struct {
117 | Build time.Time
118 | LogLevel string `fig:"log_level"`
119 | Server struct {
120 | Host string
121 | }
122 | }
123 |
124 | With the struct above and `UseEnv("myapp")` fig would search for the following
125 | environment variables:
126 |
127 | MYAPP_BUILD
128 | MYAPP_LOG_LEVEL
129 | MYAPP_SERVER_HOST
130 |
131 | Fields contained in struct slices whose elements already exists can be also be set via the environment in the form PARENT_IDX_FIELD, where idx is the index of the field in the slice.
132 |
133 | type Config struct {
134 | Server []struct {
135 | Host string
136 | }
137 | }
138 |
139 | With the config above individual servers may be configured with the following environment variable:
140 |
141 | MYAPP_SERVER_0_HOST
142 | MYAPP_SERVER_1_HOST
143 | ...
144 |
145 | Note: the Server slice must already have members inside it (i.e. from loading of the configuration file) for the containing fields to be altered via the environment. Fig will not instantiate and insert elements into the slice.
146 |
147 | # Environment Limitations
148 |
149 | Maps and map values cannot be populated from the environment.
150 |
151 | # Squashing
152 |
153 | Fields to nested structs can be flattened by annotating with `fig:",squash"`. Fig
154 | treats values into these structs as if they were part of the parent.
155 |
156 | type Base struct {
157 | Env string `fig:"env"`
158 | Logging struct {
159 | Level string `fig:"level"`
160 | } `fig:"logging"`
161 | }
162 |
163 | type Config struct {
164 | Base `fig:",squash"`
165 | Addr string `fig:"addr"`
166 | }
167 |
168 | Using the above example, the configuration file would look like:
169 |
170 | env: prod
171 | logging:
172 | level: info
173 | addr: 0.0.0.0:8080
174 |
175 | And similarly, the corresponding environment variables:
176 |
177 | ENV=prod
178 | LOGGING_LEVEL=info
179 | ADDR=0.0.0.0:8080
180 |
181 | # Time
182 |
183 | Change the layout fig uses to parse times using `TimeLayout()`.
184 |
185 | type Config struct {
186 | Date time.Time `fig:"date" default:"12-25-2019"`
187 | }
188 |
189 | var cfg Config
190 | fig.Load(&cfg, fig.TimeLayout("01-02-2006"))
191 |
192 | fmt.Printf("%+v", cfg)
193 | // Output: {Date:2019-12-25 00:00:00 +0000 UTC}
194 |
195 | By default fig parses time using the `RFC.3339` layout (`2006-01-02T15:04:05Z07:00`).
196 |
197 | # Strict Parsing
198 |
199 | By default fig ignores any fields in the config file that are not present in the struct. This behaviour can be changed using `UseStrict()` to achieve strict parsing.
200 | When strict parsing is enabled, extra fields in the config file will cause an error.
201 |
202 | # Required
203 |
204 | A validate key with a required value in the field's struct tag makes fig check if the field has been set after it's been loaded. Required fields that are not set are returned as an error.
205 |
206 | type Config struct {
207 | Host string `fig:"host" validate:"required"` // or simply `validate:"required"`
208 | }
209 |
210 | Fig uses the following properties to check if a field is set:
211 |
212 | basic types: != to its zero value ("" for str, 0 for int, etc.)
213 | slices, arrays: len() > 0
214 | pointers*, interfaces: != nil
215 | structs: always true (use a struct pointer to check for struct presence)
216 | time.Time: !time.IsZero()
217 | time.Duration: != 0
218 |
219 | *pointers to non-struct types (with the exception of time.Time) are de-referenced if they are non-nil and then checked
220 |
221 | See example below to help understand:
222 |
223 | type Config struct {
224 | A string `validate:"required"`
225 | B *string `validate:"required"`
226 | C int `validate:"required"`
227 | D *int `validate:"required"`
228 | E []float32 `validate:"required"`
229 | F struct{} `validate:"required"`
230 | G *struct{} `validate:"required"`
231 | H struct {
232 | I interface{} `validate:"required"`
233 | J interface{} `validate:"required"`
234 | } `validate:"required"`
235 | K *[]bool `validate:"required"`
236 | L []uint `validate:"required"`
237 | M *time.Time `validate:"required"`
238 | N *regexp.Regexp `validate:"required"`
239 | }
240 |
241 | var cfg Config
242 |
243 | // simulate loading of config file
244 | b := ""
245 | cfg.B = &b
246 | cfg.H.I = 5.5
247 | cfg.K = &[]bool{}
248 | cfg.L = []uint{5}
249 | m := time.Time{}
250 | cfg.M = &m
251 |
252 | err := fig.Load(&cfg)
253 | fmt.Print(err)
254 | // A: required validation failed, B: required validation failed, C: required validation failed, D: required validation failed, E: required validation failed, G: required validation failed, H.J: required validation failed, K: required validation failed, M: required validation failed, N: required validation failed
255 |
256 | # Default
257 |
258 | A default key in the field tag makes fig fill the field with the value specified when the field is not otherwise set.
259 |
260 | Fig attempts to parse the value based on the field's type. If parsing fails then an error is returned.
261 |
262 | type Config struct {
263 | Port int `fig:"port" default:"8000"` // or simply `default:"8000"`
264 | }
265 |
266 | A default value can be set for the following types:
267 |
268 | all basic types except bool and complex
269 | time.Time
270 | time.Duration
271 | *regexp.Regexp
272 | slices (of above types)
273 |
274 | Successive elements of slice defaults should be separated by a comma. The entire slice can optionally be enclosed in square brackets:
275 |
276 | type Config struct {
277 | Durations []time.Duration `default:"[30m,1h,90m,2h]"` // or `default:"30m,1h,90m,2h"`
278 | }
279 |
280 | # Defaults Limitations
281 |
282 | 1. Boolean values:
283 | Fig cannot distinguish between false and an unset value for boolean types.
284 | As a result, default values for booleans are not currently supported.
285 |
286 | 2. Maps:
287 | Maps are not supported because providing a map in a string form would be complex and error-prone.
288 | Users are encouraged to use structs instead for more reliable and structured data handling.
289 |
290 | 3. Map values:
291 | Values retrieved from a map through reflection are not addressable.
292 | Therefore, setting default values for map values is not currently supported.
293 |
294 | # Mutual exclusion
295 |
296 | The required validation and the default field tags are mutually exclusive as they are contradictory.
297 |
298 | This is not allowed:
299 |
300 | type Config struct {
301 | Level string `validate:"required" default:"warn"` // will result in an error
302 | }
303 |
304 | # Errors
305 |
306 | A wrapped error `ErrFileNotFound` is returned when fig is not able to find a config file to load. This can be useful for instance to fallback to a different configuration loading mechanism.
307 |
308 | var cfg Config
309 | err := fig.Load(&cfg)
310 | if errors.Is(err, fig.ErrFileNotFound) {
311 | // load config from elsewhere
312 | }
313 | */
314 | package fig
315 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright 2020 Kyriacos Kyriacou
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/fig.go:
--------------------------------------------------------------------------------
1 | package fig
2 |
3 | import (
4 | "encoding/json"
5 | "errors"
6 | "fmt"
7 | "os"
8 | "path/filepath"
9 | "reflect"
10 | "regexp"
11 | "strconv"
12 | "strings"
13 | "time"
14 |
15 | "github.com/mitchellh/mapstructure"
16 | "github.com/pelletier/go-toml/v2"
17 | "gopkg.in/yaml.v3"
18 | )
19 |
20 | const (
21 | // DefaultFilename is the default filename of the config file that fig looks for.
22 | DefaultFilename = "config.yaml"
23 | // DefaultDir is the default directory that fig searches in for the config file.
24 | DefaultDir = "."
25 | // DefaultTag is the default struct tag key that fig uses to find the field's alt
26 | // name.
27 | DefaultTag = "fig"
28 | // DefaultTimeLayout is the default time layout that fig uses to parse times.
29 | DefaultTimeLayout = time.RFC3339
30 | )
31 |
32 | // StringUnmarshaler is an interface designed for custom string unmarshaling.
33 | //
34 | // This interface is used when a field of a custom type needs to define its own
35 | // method for unmarshaling from a string. This is particularly useful for handling
36 | // different string representations that need to be converted into a specific type.
37 | //
38 | // To use this, the custom type must implement this interface and a corresponding
39 | // string value should be provided in the configuration. Fig automatically detects
40 | // this and handles the rest.
41 | //
42 | // Example usage:
43 | //
44 | // type ListenerType uint
45 | //
46 | // const (
47 | // ListenerUnix ListenerType = iota
48 | // ListenerTCP
49 | // ListenerTLS
50 | // )
51 | //
52 | // func (l *ListenerType) UnmarshalType(v string) error {
53 | // switch strings.ToLower(v) {
54 | // case "unix":
55 | // *l = ListenerUnix
56 | // case "tcp":
57 | // *l = ListenerTCP
58 | // case "tls":
59 | // *l = ListenerTLS
60 | // default:
61 | // return fmt.Errorf("unknown listener type: %s", v)
62 | // }
63 | // return nil
64 | // }
65 | //
66 | // type Config struct {
67 | // Listener ListenerType `fig:"listener_type" default:"tcp"`
68 | // }
69 | type StringUnmarshaler interface {
70 | UnmarshalString(s string) error
71 | }
72 |
73 | // Load reads a configuration file and loads it into the given struct. The
74 | // parameter `cfg` must be a pointer to a struct.
75 | //
76 | // By default fig looks for a file `config.yaml` in the current directory and
77 | // uses the struct field tag `fig` for matching field names and validation.
78 | // To alter this behaviour pass additional parameters as options.
79 | //
80 | // A field can be marked as required by adding a `required` key in the field's struct tag.
81 | // If a required field is not set by the configuration file an error is returned.
82 | //
83 | // type Config struct {
84 | // Env string `fig:"env" validate:"required"` // or just `validate:"required"`
85 | // }
86 | //
87 | // A field can be configured with a default value by adding a `default` key in the
88 | // field's struct tag.
89 | // If a field is not set by the configuration file then the default value is set.
90 | //
91 | // type Config struct {
92 | // Level string `fig:"level" default:"info"` // or just `default:"info"`
93 | // }
94 | //
95 | // A single field may not be marked as both `required` and `default`.
96 | func Load(cfg interface{}, options ...Option) error {
97 | fig := defaultFig()
98 |
99 | for _, opt := range options {
100 | opt(fig)
101 | }
102 |
103 | return fig.Load(cfg)
104 | }
105 |
106 | func defaultFig() *fig {
107 | return &fig{
108 | filename: DefaultFilename,
109 | dirs: []string{DefaultDir},
110 | tag: DefaultTag,
111 | timeLayout: DefaultTimeLayout,
112 | }
113 | }
114 |
115 | type fig struct {
116 | filename string
117 | dirs []string
118 | tag string
119 | timeLayout string
120 | useEnv bool
121 | useStrict bool
122 | ignoreFile bool
123 | allowNoFile bool
124 | envPrefix string
125 | }
126 |
127 | func (f *fig) Load(cfg interface{}) error {
128 | if !isStructPtr(cfg) {
129 | return fmt.Errorf("cfg must be a pointer to a struct")
130 | }
131 |
132 | vals, err := f.valsFromFile()
133 | if err != nil {
134 | return err
135 | }
136 |
137 | if err := f.decodeMap(vals, cfg); err != nil {
138 | return err
139 | }
140 |
141 | return f.processCfg(cfg)
142 | }
143 |
144 | func (f *fig) valsFromFile() (map[string]interface{}, error) {
145 | vals := make(map[string]interface{})
146 | if f.ignoreFile {
147 | return vals, nil
148 | }
149 |
150 | file, err := f.findCfgFile()
151 | if errors.Is(err, ErrFileNotFound) && f.allowNoFile {
152 | return vals, nil
153 | }
154 | if err != nil {
155 | return nil, err
156 | }
157 |
158 | vals, err = f.decodeFile(file)
159 | if err != nil {
160 | return nil, err
161 | }
162 | return vals, nil
163 | }
164 |
165 | func (f *fig) findCfgFile() (path string, err error) {
166 | for _, dir := range f.dirs {
167 | path = filepath.Join(dir, f.filename)
168 | if fileExists(path) {
169 | return
170 | }
171 | }
172 | return "", fmt.Errorf("%s: %w", f.filename, ErrFileNotFound)
173 | }
174 |
175 | // decodeFile reads the file and unmarshalls it using a decoder based on the file extension.
176 | func (f *fig) decodeFile(file string) (map[string]interface{}, error) {
177 | fd, err := os.Open(file)
178 | if err != nil {
179 | return nil, err
180 | }
181 | defer fd.Close()
182 |
183 | vals := make(map[string]interface{})
184 |
185 | switch filepath.Ext(file) {
186 | case ".yaml", ".yml":
187 | if err := yaml.NewDecoder(fd).Decode(&vals); err != nil {
188 | return nil, err
189 | }
190 | case ".json":
191 | if err := json.NewDecoder(fd).Decode(&vals); err != nil {
192 | return nil, err
193 | }
194 | case ".toml":
195 | if err := toml.NewDecoder(fd).Decode(&vals); err != nil {
196 | return nil, err
197 | }
198 | default:
199 | return nil, fmt.Errorf("unsupported file extension %s", filepath.Ext(f.filename))
200 | }
201 |
202 | return vals, nil
203 | }
204 |
205 | // decodeMap decodes a map of values into result using the mapstructure library.
206 | func (f *fig) decodeMap(m map[string]interface{}, result interface{}) error {
207 | dec, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
208 | WeaklyTypedInput: true,
209 | Result: result,
210 | TagName: f.tag,
211 | ErrorUnused: f.useStrict,
212 | DecodeHook: mapstructure.ComposeDecodeHookFunc(
213 | mapstructure.StringToTimeDurationHookFunc(),
214 | mapstructure.StringToTimeHookFunc(f.timeLayout),
215 | stringToRegexpHookFunc(),
216 | stringToStringUnmarshalerHook(),
217 | ),
218 | })
219 | if err != nil {
220 | return err
221 | }
222 | return dec.Decode(m)
223 | }
224 |
225 | // stringToRegexpHookFunc returns a DecodeHookFunc that converts strings to regexp.Regexp.
226 | func stringToRegexpHookFunc() mapstructure.DecodeHookFunc {
227 | return func(
228 | f reflect.Type,
229 | t reflect.Type,
230 | data interface{},
231 | ) (interface{}, error) {
232 | if f.Kind() != reflect.String {
233 | return data, nil
234 | }
235 | if t != reflect.TypeOf(®exp.Regexp{}) {
236 | return data, nil
237 | }
238 | //nolint:forcetypeassert
239 | return regexp.Compile(data.(string))
240 | }
241 | }
242 |
243 | // stringToStringUnmarshalerHook returns a DecodeHookFunc that executes a custom method which
244 | // satisfies the StringUnmarshaler interface on custom types.
245 | func stringToStringUnmarshalerHook() mapstructure.DecodeHookFunc {
246 | return func(f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) {
247 | if f.Kind() != reflect.String {
248 | return data, nil
249 | }
250 |
251 | ds, ok := data.(string)
252 | if !ok {
253 | return data, nil
254 | }
255 |
256 | if reflect.PointerTo(t).Implements(reflect.TypeOf((*StringUnmarshaler)(nil)).Elem()) {
257 | val := reflect.New(t).Interface()
258 |
259 | if unmarshaler, ok := val.(StringUnmarshaler); ok {
260 | err := unmarshaler.UnmarshalString(ds)
261 | if err != nil {
262 | return nil, err
263 | }
264 |
265 | return reflect.ValueOf(val).Elem().Interface(), nil
266 | }
267 | }
268 |
269 | return data, nil
270 | }
271 | }
272 |
273 | // processCfg processes a cfg struct after it has been loaded from
274 | // the config file, by validating required fields and setting defaults
275 | // where applicable.
276 | func (f *fig) processCfg(cfg interface{}) error {
277 | fields := flattenCfg(cfg, f.tag)
278 | errs := make(fieldErrors)
279 |
280 | for _, field := range fields {
281 | if err := f.processField(field); err != nil {
282 | errs[field.path(f.tag)] = err
283 | }
284 | }
285 |
286 | if len(errs) > 0 {
287 | return errs
288 | }
289 |
290 | return nil
291 | }
292 |
293 | // processField processes a single field and is called by processCfg
294 | // for each field in cfg.
295 | func (f *fig) processField(field *field) error {
296 | if field.required && field.setDefault {
297 | return fmt.Errorf("field cannot have both a required validation and a default value")
298 | }
299 |
300 | if f.useEnv {
301 | if err := f.setFromEnv(field.v, field.path(f.tag)); err != nil {
302 | return fmt.Errorf("unable to set from env: %w", err)
303 | }
304 | }
305 |
306 | if field.required && isZero(field.v) {
307 | return fmt.Errorf("required validation failed")
308 | }
309 |
310 | if field.setDefault && isZero(field.v) {
311 | if err := f.setDefaultValue(field.v, field.defaultVal); err != nil {
312 | return fmt.Errorf("unable to set default: %w", err)
313 | }
314 | }
315 |
316 | return nil
317 | }
318 |
319 | func (f *fig) setFromEnv(fv reflect.Value, key string) error {
320 | key = f.formatEnvKey(key)
321 | if val, ok := os.LookupEnv(key); ok {
322 | return f.setValue(fv, val)
323 | }
324 | return nil
325 | }
326 |
327 | func (f *fig) formatEnvKey(key string) string {
328 | // loggers[0].level --> loggers_0_level
329 | key = strings.NewReplacer(".", "_", "[", "_", "]", "").Replace(key)
330 | if f.envPrefix != "" {
331 | key = fmt.Sprintf("%s_%s", f.envPrefix, key)
332 | }
333 | return strings.ToUpper(key)
334 | }
335 |
336 | // setDefaultValue calls setValue but disallows booleans from
337 | // being set.
338 | func (f *fig) setDefaultValue(fv reflect.Value, val string) error {
339 | if fv.Kind() == reflect.Bool {
340 | return fmt.Errorf("unsupported type: %v", fv.Kind())
341 | }
342 | return f.setValue(fv, val)
343 | }
344 |
345 | // setValue sets fv to val. it attempts to convert val to the correct
346 | // type based on the field's kind. if conversion fails an error is
347 | // returned. If fv satisfies the StringUnmarshaler interface it will
348 | // execute the corresponding StringUnmarshaler.UnmarshalString method
349 | // on the value.
350 | // fv must be settable else this panics.
351 | func (f *fig) setValue(fv reflect.Value, val string) error {
352 | if ok, err := trySetFromStringUnmarshaler(fv, val); err != nil {
353 | return err
354 | } else if ok {
355 | return nil
356 | }
357 |
358 | switch fv.Kind() {
359 | case reflect.Ptr:
360 | if fv.IsNil() {
361 | fv.Set(reflect.New(fv.Type().Elem()))
362 | }
363 | return f.setValue(fv.Elem(), val)
364 | case reflect.Slice:
365 | if err := f.setSlice(fv, val); err != nil {
366 | return err
367 | }
368 | case reflect.Bool:
369 | b, err := strconv.ParseBool(val)
370 | if err != nil {
371 | return err
372 | }
373 | fv.SetBool(b)
374 | case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
375 | if _, ok := fv.Interface().(time.Duration); ok {
376 | d, err := time.ParseDuration(val)
377 | if err != nil {
378 | return err
379 | }
380 | fv.Set(reflect.ValueOf(d))
381 | } else {
382 | i, err := strconv.ParseInt(val, 10, 64)
383 | if err != nil {
384 | return err
385 | }
386 | fv.SetInt(i)
387 | }
388 | case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
389 | i, err := strconv.ParseUint(val, 10, 64)
390 | if err != nil {
391 | return err
392 | }
393 | fv.SetUint(i)
394 | case reflect.Float32, reflect.Float64:
395 | f, err := strconv.ParseFloat(val, 64)
396 | if err != nil {
397 | return err
398 | }
399 | fv.SetFloat(f)
400 | case reflect.String:
401 | fv.SetString(val)
402 | case reflect.Struct: // struct is only allowed a default in the special case where it's a time.Time
403 | if _, ok := fv.Interface().(time.Time); ok {
404 | t, err := time.Parse(f.timeLayout, val)
405 | if err != nil {
406 | return err
407 | }
408 | fv.Set(reflect.ValueOf(t))
409 | } else if _, ok := fv.Interface().(regexp.Regexp); ok {
410 | re, err := regexp.Compile(val)
411 | if err != nil {
412 | return err
413 | }
414 | fv.Set(reflect.ValueOf(*re))
415 | } else {
416 | return fmt.Errorf("unsupported type %s", fv.Kind())
417 | }
418 | default:
419 | return fmt.Errorf("unsupported type %s", fv.Kind())
420 | }
421 | return nil
422 | }
423 |
424 | // setSlice val to sv. val should be a Go slice formatted as a string
425 | // (e.g. "[1,2]") and sv must be a slice value. if conversion of val
426 | // to a slice fails then an error is returned.
427 | // sv must be settable else this panics.
428 | func (f *fig) setSlice(sv reflect.Value, val string) error {
429 | ss := stringSlice(val)
430 | slice := reflect.MakeSlice(sv.Type(), len(ss), cap(ss))
431 | for i, s := range ss {
432 | if err := f.setValue(slice.Index(i), s); err != nil {
433 | return err
434 | }
435 | }
436 | sv.Set(slice)
437 | return nil
438 | }
439 |
440 | // trySetFromStringUnmarshaler takes a value fv which is expected to implement the
441 | // StringUnmarshaler interface and attempts to unmarshal the string val into the field.
442 | // If the value does not implement the interface, or an error occurs during the unmarshal,
443 | // then false and an error (if applicable) is returned. Otherwise, true and a nil error
444 | // is returned.
445 | func trySetFromStringUnmarshaler(fv reflect.Value, val string) (bool, error) {
446 | if fv.IsValid() && reflect.PointerTo(fv.Type()).Implements(reflect.TypeOf((*StringUnmarshaler)(nil)).Elem()) {
447 | vi := reflect.New(fv.Type()).Interface()
448 | if unmarshaler, ok := vi.(StringUnmarshaler); ok {
449 | err := unmarshaler.UnmarshalString(val)
450 | if err != nil {
451 | return false, fmt.Errorf("could not unmarshal string %q: %w", val, err)
452 | }
453 |
454 | fv.Set(reflect.ValueOf(vi).Elem())
455 | return true, nil
456 | }
457 |
458 | return false, fmt.Errorf("unable to type assert StringUnmarshaler from type %s", fv.Type().Name())
459 | }
460 |
461 | return false, nil
462 | }
463 |
--------------------------------------------------------------------------------
/fig_test.go:
--------------------------------------------------------------------------------
1 | package fig
2 |
3 | import (
4 | "errors"
5 | "fmt"
6 | "os"
7 | "path/filepath"
8 | "reflect"
9 | "regexp"
10 | "strings"
11 | "testing"
12 | "time"
13 |
14 | "github.com/mitchellh/mapstructure"
15 | )
16 |
17 | type Pod struct {
18 | APIVersion string `fig:"apiVersion" default:"v1"`
19 | Kind string `fig:"kind" validate:"required"`
20 | Metadata struct {
21 | Name string `fig:"name"`
22 | Environments []string `fig:"environments" default:"[dev,staging,prod]"`
23 | Master bool `fig:"master" validate:"required"`
24 | MaxPercentUtil *float64 `fig:"maxPercentUtil" default:"0.5"`
25 | Retry time.Duration `fig:"retry" default:"10s"`
26 | } `fig:"metadata"`
27 | Spec Spec `fig:"spec"`
28 | }
29 |
30 | type Spec struct {
31 | Containers []Container `fig:"containers"`
32 | Volumes []*Volume `fig:"volumes"`
33 | }
34 |
35 | type Arg struct {
36 | Value string `fig:"value" validate:"required"`
37 | }
38 |
39 | type Container struct {
40 | Name string `fig:"name" validate:"required"`
41 | Image string `fig:"image" validate:"required"`
42 | Command []string `fig:"command"`
43 | Env []Env `fig:"env"`
44 | Ports []Port `fig:"ports"`
45 | Args map[string]Arg `fig:"args" validate:"required"`
46 | Resources struct {
47 | Limits struct {
48 | CPU string `fig:"cpu"`
49 | } `fig:"limits"`
50 | Requests *struct {
51 | Memory string `fig:"memory" default:"64Mi"`
52 | CPU *string `fig:"cpu" default:"250m"`
53 | }
54 | } `fig:"resources"`
55 | VolumeMounts []VolumeMount `fig:"volumeMounts"`
56 | }
57 |
58 | type Env struct {
59 | Name string `fig:"name"`
60 | Value string `fig:"value"`
61 | }
62 |
63 | type Port struct {
64 | ContainerPort int `fig:"containerPort" validate:"required"`
65 | }
66 |
67 | type VolumeMount struct {
68 | MountPath string `fig:"mountPath" validate:"required"`
69 | Name string `fig:"name" validate:"required"`
70 | }
71 |
72 | type Volume struct {
73 | Name string `fig:"name" validate:"required"`
74 | ConfigMap *ConfigMap `fig:"configMap"`
75 | }
76 |
77 | type ConfigMap struct {
78 | Name string `fig:"name" validate:"required"`
79 | Items []Item `fig:"items" validate:"required"`
80 | }
81 |
82 | type Item struct {
83 | Key string `fig:"key" validate:"required"`
84 | Path string `fig:"path" validate:"required"`
85 | }
86 |
87 | type ListenerType uint
88 |
89 | const (
90 | ListenerUnix ListenerType = iota
91 | ListenerTCP
92 | ListenerTLS
93 | )
94 |
95 | func (l *ListenerType) UnmarshalString(v string) error {
96 | switch strings.ToLower(v) {
97 | case "unix":
98 | *l = ListenerUnix
99 | case "tcp":
100 | *l = ListenerTCP
101 | case "tls":
102 | *l = ListenerTLS
103 | default:
104 | return fmt.Errorf("unknown listener type: %s", v)
105 | }
106 | return nil
107 | }
108 |
109 | func validPodConfig() Pod {
110 | var pod Pod
111 |
112 | pod.APIVersion = "v1"
113 | pod.Kind = "Pod"
114 | pod.Metadata.Name = "redis"
115 | pod.Metadata.Environments = []string{"dev", "staging", "prod"}
116 | pod.Metadata.Master = true
117 | pod.Metadata.Retry = 10 * time.Second
118 | percentUtil := 0.5
119 | pod.Metadata.MaxPercentUtil = &percentUtil
120 | pod.Spec.Containers = []Container{
121 | {
122 | Name: "redis",
123 | Image: "redis:5.0.4",
124 | Command: []string{
125 | "redis-server",
126 | "/redis-master/redis.conf",
127 | },
128 | Env: []Env{
129 | {
130 | Name: "MASTER",
131 | Value: "true",
132 | },
133 | },
134 | Ports: []Port{
135 | {ContainerPort: 6379},
136 | },
137 | VolumeMounts: []VolumeMount{
138 | {
139 | MountPath: "/redis-master-data",
140 | Name: "data",
141 | },
142 | {
143 | MountPath: "/redis-master",
144 | Name: "config",
145 | },
146 | },
147 | Args: map[string]Arg{
148 | "-w": {
149 | Value: "true",
150 | },
151 | "--mem": {
152 | Value: "low",
153 | },
154 | },
155 | },
156 | }
157 | pod.Spec.Containers[0].Resources.Limits.CPU = "0.1"
158 | pod.Spec.Volumes = []*Volume{
159 | {Name: "data"},
160 | {
161 | Name: "config",
162 | ConfigMap: &ConfigMap{
163 | Name: "example-redis-config",
164 | Items: []Item{
165 | {
166 | Key: "redis-config",
167 | Path: "redis.conf",
168 | },
169 | },
170 | },
171 | },
172 | }
173 |
174 | return pod
175 | }
176 |
177 | func Test_fig_Load(t *testing.T) {
178 | for _, f := range []string{"pod.yaml", "pod.json", "pod.toml"} {
179 | t.Run(f, func(t *testing.T) {
180 | var cfg Pod
181 | err := Load(&cfg, File(f), Dirs(filepath.Join("testdata", "valid")))
182 | if err != nil {
183 | t.Fatalf("unexpected err: %v", err)
184 | }
185 |
186 | want := validPodConfig()
187 |
188 | if !reflect.DeepEqual(want, cfg) {
189 | t.Errorf("\nwant %+v\ngot %+v", want, cfg)
190 | }
191 | })
192 | }
193 | }
194 |
195 | func Test_fig_Load_FileNotFound(t *testing.T) {
196 | fig := defaultFig()
197 | fig.filename = "abrakadabra"
198 | var cfg Pod
199 | err := fig.Load(&cfg)
200 | if err == nil {
201 | t.Fatalf("expected err")
202 | }
203 | if !errors.Is(err, ErrFileNotFound) {
204 | t.Errorf("expected err %v, got %v", ErrFileNotFound, err)
205 | }
206 | }
207 |
208 | func Test_fig_Load_AllowNoFile(t *testing.T) {
209 | fig := defaultFig()
210 | fig.filename = "abrakadabra"
211 | fig.allowNoFile = true
212 | fig.useEnv = true
213 | fig.envPrefix = ""
214 |
215 | // Ensure that we still load values via env without a file
216 | expectedKind := "this is required"
217 | t.Setenv("KIND", expectedKind)
218 | t.Setenv("METADATA_MASTER", "true")
219 |
220 | var cfg Pod
221 | err := fig.Load(&cfg)
222 | if err != nil {
223 | t.Fatalf("expected no err, got %v", err)
224 | }
225 | if cfg.Kind != expectedKind {
226 | t.Fatalf("expected %q, got %q", expectedKind, cfg.Kind)
227 | }
228 | if cfg.Metadata.Master != true {
229 | t.Fatalf("expected %t, got %v", true, cfg.Metadata.Master)
230 | }
231 | }
232 |
233 | func Test_fig_Load_NonStructPtr(t *testing.T) {
234 | cfg := struct {
235 | X int
236 | }{}
237 | fig := defaultFig()
238 | err := fig.Load(cfg)
239 | if err == nil {
240 | t.Fatalf("fig.Load() returned nil error")
241 | }
242 | if !strings.Contains(err.Error(), "pointer") {
243 | t.Errorf("expected struct pointer err, got %v", err)
244 | }
245 | }
246 |
247 | func Test_fig_Load_Required(t *testing.T) {
248 | for _, f := range []string{"pod.yaml", "pod.json", "pod.toml"} {
249 | t.Run(f, func(t *testing.T) {
250 | var cfg Pod
251 | err := Load(&cfg, File(f), Dirs(filepath.Join("testdata", "invalid")))
252 | if err == nil {
253 | t.Fatalf("expected err")
254 | }
255 |
256 | want := []string{
257 | "kind",
258 | "metadata.master",
259 | "spec.containers[0].image",
260 | "spec.containers[0].args[-w].value",
261 | "spec.containers[0].args[-o].value",
262 | "spec.volumes[0].configMap.items",
263 | "spec.volumes[1].name",
264 | }
265 |
266 | fieldErrs := err.(fieldErrors)
267 |
268 | if len(want) != len(fieldErrs) {
269 | t.Fatalf("\nwant len(fieldErrs) == %d, got %d\nerrs: %+v\n", len(want), len(fieldErrs), fieldErrs)
270 | }
271 |
272 | for _, field := range want {
273 | if _, ok := fieldErrs[field]; !ok {
274 | t.Errorf("want %s in fieldErrs, got %+v", field, fieldErrs)
275 | }
276 | }
277 | })
278 | }
279 | }
280 |
281 | func Test_fig_Load_Defaults(t *testing.T) {
282 | t.Run("non-zero values are not overridden", func(t *testing.T) {
283 | for _, f := range []string{"server.yaml", "server.json", "server.toml"} {
284 | t.Run(f, func(t *testing.T) {
285 | type Server struct {
286 | Host string `fig:"host" default:"127.0.0.1"`
287 | Ports []int `fig:"ports" default:"[80,443]"`
288 | Logger struct {
289 | LogLevel string `fig:"log_level" default:"info"`
290 | Pattern *regexp.Regexp `fig:"pattern" default:".*"`
291 | Production bool `fig:"production"`
292 | Metadata struct {
293 | Keys []string `fig:"keys" default:"[ts]"`
294 | }
295 | }
296 | Application struct {
297 | BuildDate time.Time `fig:"build_date" default:"2020-01-01T12:00:00Z"`
298 | }
299 | Listener ListenerType `fig:"listener_type" default:"unix"`
300 | }
301 |
302 | var want Server
303 | want.Host = "0.0.0.0"
304 | want.Ports = []int{80, 443}
305 | want.Logger.LogLevel = "debug"
306 | want.Logger.Pattern = regexp.MustCompile(".*")
307 | want.Logger.Production = false
308 | want.Logger.Metadata.Keys = []string{"ts"}
309 | want.Application.BuildDate = time.Date(2020, 1, 1, 12, 0, 0, 0, time.UTC)
310 | want.Listener = ListenerUnix
311 |
312 | var cfg Server
313 | err := Load(&cfg, File(f), Dirs(filepath.Join("testdata", "valid")))
314 | if err != nil {
315 | t.Fatalf("unexpected err: %v", err)
316 | }
317 |
318 | if !reflect.DeepEqual(want, cfg) {
319 | t.Errorf("\nwant %+v\ngot %+v", want, cfg)
320 | }
321 | })
322 | }
323 | })
324 |
325 | t.Run("bad defaults reported as errors", func(t *testing.T) {
326 | for _, f := range []string{"server.yaml", "server.json", "server.toml"} {
327 | t.Run(f, func(t *testing.T) {
328 | type Server struct {
329 | Host string `fig:"host" default:"127.0.0.1"`
330 | Ports []int `fig:"ports" default:"[80,not-a-port]"`
331 | Logger struct {
332 | LogLevel string `fig:"log_level" default:"info"`
333 | Metadata struct {
334 | Keys []string `fig:"keys" validate:"required"`
335 | }
336 | }
337 | Application struct {
338 | BuildDate time.Time `fig:"build_date" default:"not-a-time"`
339 | }
340 | }
341 |
342 | var cfg Server
343 | err := Load(&cfg, File(f), Dirs(filepath.Join("testdata", "valid")))
344 | if err == nil {
345 | t.Fatalf("expected err")
346 | }
347 |
348 | want := []string{
349 | "ports",
350 | "Logger.Metadata.keys",
351 | "Application.build_date",
352 | }
353 |
354 | fieldErrs := err.(fieldErrors)
355 |
356 | if len(want) != len(fieldErrs) {
357 | t.Fatalf("\nlen(fieldErrs) != %d\ngot %+v\n", len(want), fieldErrs)
358 | }
359 |
360 | for _, field := range want {
361 | if _, ok := fieldErrs[field]; !ok {
362 | t.Errorf("want %s in fieldErrs, got %+v", field, fieldErrs)
363 | }
364 | }
365 | })
366 | }
367 | })
368 | }
369 |
370 | func Test_fig_Load_RequiredAndDefaults(t *testing.T) {
371 | for _, f := range []string{"server.yaml", "server.json", "server.toml"} {
372 | t.Run(f, func(t *testing.T) {
373 | type Server struct {
374 | Host string `fig:"host" default:"127.0.0.1"`
375 | Ports []int `fig:"ports" validate:"required"`
376 | Logger struct {
377 | LogLevel string `fig:"log_level" validate:"required"`
378 | Metadata struct {
379 | Keys []string `fig:"keys" validate:"required"`
380 | }
381 | }
382 | Application struct {
383 | BuildDate time.Time `fig:"build_date" default:"2020-01-01T12:00:00Z"`
384 | }
385 | }
386 |
387 | var cfg Server
388 | err := Load(&cfg, File(f), Dirs(filepath.Join("testdata", "valid")))
389 | if err == nil {
390 | t.Fatalf("expected err")
391 | }
392 |
393 | want := []string{
394 | "ports",
395 | "Logger.Metadata.keys",
396 | }
397 |
398 | fieldErrs := err.(fieldErrors)
399 |
400 | if len(want) != len(fieldErrs) {
401 | t.Fatalf("\nlen(fieldErrs) != %d\ngot %+v\n", len(want), fieldErrs)
402 | }
403 |
404 | for _, field := range want {
405 | if _, ok := fieldErrs[field]; !ok {
406 | t.Errorf("want %s in fieldErrs, got %+v", field, fieldErrs)
407 | }
408 | }
409 | })
410 | }
411 | }
412 |
413 | func Test_fig_Load_UseStrict(t *testing.T) {
414 | for _, f := range []string{"server.yaml", "server.json", "server.toml"} {
415 | t.Run(f, func(t *testing.T) {
416 | type Server struct {
417 | Host string `fig:"host"`
418 | }
419 |
420 | var cfg Server
421 | err := Load(&cfg, UseStrict(), File(f), Dirs(filepath.Join("testdata", "valid")))
422 | if err == nil {
423 | t.Fatalf("expected err")
424 | }
425 |
426 | want := []string{
427 | "has invalid keys: logger",
428 | }
429 |
430 | fieldErrs := err.(*mapstructure.Error)
431 |
432 | if len(want) != len(fieldErrs.Errors) {
433 | t.Fatalf("\nlen(fieldErrs) != %d\ngot %+v\n", len(want), fieldErrs)
434 | }
435 |
436 | for i, err := range fieldErrs.Errors {
437 | if !strings.Contains(err, want[i]) {
438 | t.Errorf("want %s in fieldErrs, got %+v", want[i], err)
439 | }
440 | }
441 | })
442 | }
443 | }
444 |
445 | func Test_fig_Load_WithOptions(t *testing.T) {
446 | for _, f := range []string{"server.yaml", "server.json", "server.toml"} {
447 | t.Run(f, func(t *testing.T) {
448 | type Server struct {
449 | Host string `custom:"host" default:"127.0.0.1"`
450 | Ports []int `custom:"ports" default:"[80,443]"`
451 | Logger struct {
452 | LogLevel string `custom:"log_level"`
453 | Metadata struct {
454 | Keys []string `custom:"keys" default:"ts"`
455 | Tag string `custom:"tag" validate:"required"`
456 | }
457 | }
458 | Cache struct {
459 | CleanupInterval time.Duration `custom:"cleanup_interval" validate:"required"`
460 | FillThreshold float32 `custom:"threshold" default:"0.9"`
461 | }
462 | Application struct {
463 | BuildDate time.Time `custom:"build_date" default:"12-25-2012"`
464 | Version int
465 | }
466 | }
467 |
468 | os.Clearenv()
469 | setenv(t, "MYAPP_LOGGER_METADATA_TAG", "errorLogger")
470 | setenv(t, "MYAPP_LOGGER_LOG_LEVEL", "error")
471 | setenv(t, "MYAPP_APPLICATION_VERSION", "1")
472 | setenv(t, "MYAPP_CACHE_CLEANUP_INTERVAL", "5m")
473 | setenv(t, "MYAPP_CACHE_THRESHOLD", "0.85")
474 |
475 | var want Server
476 | want.Host = "0.0.0.0"
477 | want.Ports = []int{80, 443}
478 | want.Logger.LogLevel = "error"
479 | want.Logger.Metadata.Keys = []string{"ts"}
480 | want.Application.BuildDate = time.Date(2012, 12, 25, 0, 0, 0, 0, time.UTC)
481 | want.Logger.Metadata.Tag = "errorLogger"
482 | want.Application.Version = 1
483 | want.Cache.CleanupInterval = 5 * time.Minute
484 | want.Cache.FillThreshold = 0.85
485 |
486 | var cfg Server
487 |
488 | err := Load(&cfg,
489 | File(f),
490 | Dirs(filepath.Join("testdata", "valid")),
491 | Tag("custom"),
492 | TimeLayout("01-02-2006"),
493 | UseEnv("myapp"),
494 | )
495 | if err != nil {
496 | t.Fatalf("unexpected err: %v", err)
497 | }
498 |
499 | if !reflect.DeepEqual(want, cfg) {
500 | t.Errorf("\nwant %+v\ngot %+v", want, cfg)
501 | }
502 | })
503 | }
504 | }
505 |
506 | func Test_fig_Load_IgnoreFile(t *testing.T) {
507 | type Server struct {
508 | Host string `custom:"host" default:"127.0.0.1"`
509 | Ports []int `custom:"ports" default:"[80,443]"`
510 | Logger struct {
511 | LogLevel string `custom:"log_level"`
512 | Metadata struct {
513 | Keys []string `custom:"keys" default:"ts"`
514 | Tag string `custom:"tag" validate:"required"`
515 | }
516 | }
517 | Cache struct {
518 | CleanupInterval time.Duration `custom:"cleanup_interval" validate:"required"`
519 | FillThreshold float32 `custom:"threshold" default:"0.9"`
520 | }
521 | Application struct {
522 | BuildDate time.Time `custom:"build_date" default:"12-25-2012"`
523 | Version int
524 | }
525 | }
526 |
527 | os.Clearenv()
528 | setenv(t, "MYAPP_HOST", "0.0.0.0")
529 | setenv(t, "MYAPP_PORTS", "[8888,443]")
530 | setenv(t, "MYAPP_LOGGER_METADATA_TAG", "errorLogger")
531 | setenv(t, "MYAPP_LOGGER_LOG_LEVEL", "error")
532 | setenv(t, "MYAPP_APPLICATION_VERSION", "1")
533 | setenv(t, "MYAPP_CACHE_CLEANUP_INTERVAL", "5m")
534 | setenv(t, "MYAPP_CACHE_THRESHOLD", "0.85")
535 |
536 | var want Server
537 | want.Host = "0.0.0.0"
538 | want.Ports = []int{8888, 443}
539 | want.Logger.LogLevel = "error"
540 | want.Logger.Metadata.Keys = []string{"ts"}
541 | want.Application.BuildDate = time.Date(2012, 12, 25, 0, 0, 0, 0, time.UTC)
542 | want.Logger.Metadata.Tag = "errorLogger"
543 | want.Application.Version = 1
544 | want.Cache.CleanupInterval = 5 * time.Minute
545 | want.Cache.FillThreshold = 0.85
546 |
547 | var cfg Server
548 |
549 | err := Load(&cfg,
550 | IgnoreFile(),
551 | Tag("custom"),
552 | TimeLayout("01-02-2006"),
553 | UseEnv("myapp"),
554 | )
555 | if err != nil {
556 | t.Fatalf("unexpected err: %v", err)
557 | }
558 |
559 | if !reflect.DeepEqual(want, cfg) {
560 | t.Errorf("\nwant %+v\ngot %+v", want, cfg)
561 | }
562 | }
563 |
564 | func Test_fig_findCfgFile(t *testing.T) {
565 | t.Run("finds existing file", func(t *testing.T) {
566 | fig := defaultFig()
567 | fig.filename = "pod.yaml"
568 | fig.dirs = []string{".", "testdata", filepath.Join("testdata", "valid")}
569 |
570 | file, err := fig.findCfgFile()
571 | if err != nil {
572 | t.Fatalf("unexpected err: %v", err)
573 | }
574 |
575 | want := filepath.Join("testdata", "valid", "pod.yaml")
576 | if want != file {
577 | t.Fatalf("want file %s, got %s", want, file)
578 | }
579 | })
580 |
581 | t.Run("non-existing file returns ErrFileNotFound", func(t *testing.T) {
582 | fig := defaultFig()
583 | fig.filename = "nope.nope"
584 | fig.dirs = []string{".", "testdata", filepath.Join("testdata", "valid")}
585 |
586 | file, err := fig.findCfgFile()
587 | if err == nil {
588 | t.Fatalf("expected err, got file %s", file)
589 | }
590 | if !errors.Is(err, ErrFileNotFound) {
591 | t.Errorf("expected err %v, got %v", ErrFileNotFound, err)
592 | }
593 | })
594 | }
595 |
596 | func Test_fig_decodeFile(t *testing.T) {
597 | fig := defaultFig()
598 |
599 | for _, f := range []string{"bad.yaml", "bad.json", "bad.toml"} {
600 | t.Run(f, func(t *testing.T) {
601 | file := filepath.Join("testdata", "invalid", f)
602 | if !fileExists(file) {
603 | t.Fatalf("test file %s does not exist", file)
604 | }
605 | _, err := fig.decodeFile(file)
606 | if err == nil {
607 | t.Errorf("received nil error")
608 | }
609 | })
610 | }
611 |
612 | t.Run("unsupported file extension", func(t *testing.T) {
613 | file := filepath.Join("testdata", "invalid", "list.hcl")
614 | if !fileExists(file) {
615 | t.Fatalf("test file %s does not exist", file)
616 | }
617 | _, err := fig.decodeFile(file)
618 | if err == nil {
619 | t.Fatal("received nil error")
620 | }
621 | if !strings.Contains(err.Error(), "unsupported") {
622 | t.Errorf("err == %v, expected unsupported file extension", err)
623 | }
624 | })
625 |
626 | t.Run("file does not exist", func(t *testing.T) {
627 | _, err := fig.decodeFile("casperthefriendlygho.st")
628 | if err == nil {
629 | t.Fatal("received nil error")
630 | }
631 | })
632 | }
633 |
634 | func Test_fig_decodeMap(t *testing.T) {
635 | fig := defaultFig()
636 | fig.tag = "fig"
637 |
638 | m := map[string]interface{}{
639 | "log_level": "debug",
640 | "severity": "5",
641 | "server": map[string]interface{}{
642 | "ports": []int{443, 80},
643 | "secure": 1,
644 | "listener_type": "tls",
645 | },
646 | }
647 |
648 | var cfg struct {
649 | Level string `fig:"log_level"`
650 | Severity int `fig:"severity" validate:"required"`
651 | Server struct {
652 | Ports []string `fig:"ports" default:"[443]"`
653 | Secure bool
654 | Listener ListenerType `fig:"listener_type" default:"unix"`
655 | } `fig:"server"`
656 | }
657 |
658 | if err := fig.decodeMap(m, &cfg); err != nil {
659 | t.Fatalf("unexpected err: %v", err)
660 | }
661 |
662 | if cfg.Level != "debug" {
663 | t.Errorf("cfg.Level: want %s, got %s", "debug", cfg.Level)
664 | }
665 |
666 | if cfg.Severity != 5 {
667 | t.Errorf("cfg.Severity: want %d, got %d", 5, cfg.Severity)
668 | }
669 |
670 | if reflect.DeepEqual([]int{443, 80}, cfg.Server.Ports) {
671 | t.Errorf("cfg.Server.Ports: want %+v, got %+v", []int{443, 80}, cfg.Server.Ports)
672 | }
673 |
674 | if cfg.Server.Secure == false {
675 | t.Error("cfg.Server.Secure == false")
676 | }
677 |
678 | if cfg.Server.Listener != ListenerTLS {
679 | t.Errorf("cfg.Server.Listener: want: %d, got: %d", ListenerTLS, cfg.Server.Listener)
680 | }
681 | }
682 |
683 | func Test_fig_processCfg(t *testing.T) {
684 | t.Run("slice elements set by env", func(t *testing.T) {
685 | fig := defaultFig()
686 | fig.tag = "fig"
687 | fig.useEnv = true
688 |
689 | os.Clearenv()
690 | setenv(t, "A_0_B", "b0")
691 | setenv(t, "A_1_B", "b1")
692 | setenv(t, "A_0_C", "9000")
693 |
694 | cfg := struct {
695 | A []struct {
696 | B string `validate:"required"`
697 | C int `default:"5"`
698 | }
699 | }{}
700 | cfg.A = []struct {
701 | B string `validate:"required"`
702 | C int `default:"5"`
703 | }{{B: "boo"}, {B: "boo"}}
704 |
705 | err := fig.processCfg(&cfg)
706 | if err != nil {
707 | t.Fatalf("processCfg() returned unexpected error: %v", err)
708 | }
709 | if cfg.A[0].B != "b0" {
710 | t.Errorf("cfg.A[0].B == %s, expected %s", cfg.A[0].B, "b0")
711 | }
712 | if cfg.A[1].B != "b1" {
713 | t.Errorf("cfg.A[1].B == %s, expected %s", cfg.A[1].B, "b1")
714 | }
715 | if cfg.A[0].C != 9000 {
716 | t.Errorf("cfg.A[0].C == %d, expected %d", cfg.A[0].C, 9000)
717 | }
718 | if cfg.A[1].C != 5 {
719 | t.Errorf("cfg.A[1].C == %d, expected %d", cfg.A[1].C, 5)
720 | }
721 | })
722 |
723 | t.Run("embedded struct set by env", func(t *testing.T) {
724 | fig := defaultFig()
725 | fig.useEnv = true
726 | fig.tag = "fig"
727 |
728 | type A struct {
729 | B string
730 | }
731 | type C struct {
732 | D *int
733 | }
734 | type F struct {
735 | A
736 | C `fig:"cc"`
737 | }
738 | cfg := F{}
739 |
740 | os.Clearenv()
741 | setenv(t, "A_B", "embedded")
742 | setenv(t, "CC_D", "7")
743 |
744 | err := fig.processCfg(&cfg)
745 | if err != nil {
746 | t.Fatalf("processCfg() returned unexpected error: %v", err)
747 | }
748 | if cfg.A.B != "embedded" {
749 | t.Errorf("cfg.A.B == %s, expected %s", cfg.A.B, "embedded")
750 | }
751 | if *cfg.C.D != 7 {
752 | t.Errorf("cfg.C.D == %d, expected %d", *cfg.C.D, 7)
753 | }
754 | })
755 | }
756 |
757 | func Test_fig_processField(t *testing.T) {
758 | fig := defaultFig()
759 | fig.tag = "fig"
760 |
761 | t.Run("field with default", func(t *testing.T) {
762 | cfg := struct {
763 | X int `fig:"y" default:"10"`
764 | }{}
765 | parent := &field{
766 | v: reflect.ValueOf(&cfg).Elem(),
767 | t: reflect.ValueOf(&cfg).Elem().Type(),
768 | sliceIdx: -1,
769 | }
770 |
771 | f := newStructField(parent, 0, fig.tag)
772 | err := fig.processField(f)
773 | if err != nil {
774 | t.Fatalf("processField() returned unexpected error: %v", err)
775 | }
776 | if cfg.X != 10 {
777 | t.Errorf("cfg.X == %d, expected %d", cfg.X, 10)
778 | }
779 | })
780 |
781 | t.Run("field with default does not overwrite", func(t *testing.T) {
782 | cfg := struct {
783 | X int `fig:"y" default:"10"`
784 | }{}
785 | cfg.X = 5
786 | parent := &field{
787 | v: reflect.ValueOf(&cfg).Elem(),
788 | t: reflect.ValueOf(&cfg).Elem().Type(),
789 | sliceIdx: -1,
790 | }
791 |
792 | f := newStructField(parent, 0, fig.tag)
793 | err := fig.processField(f)
794 | if err != nil {
795 | t.Fatalf("processField() returned unexpected error: %v", err)
796 | }
797 | if cfg.X != 5 {
798 | t.Errorf("cfg.X == %d, expected %d", cfg.X, 5)
799 | }
800 | })
801 |
802 | t.Run("field with bad default", func(t *testing.T) {
803 | cfg := struct {
804 | X int `fig:"y" default:"not-an-int"`
805 | }{}
806 | parent := &field{
807 | v: reflect.ValueOf(&cfg).Elem(),
808 | t: reflect.ValueOf(&cfg).Elem().Type(),
809 | sliceIdx: -1,
810 | }
811 |
812 | f := newStructField(parent, 0, fig.tag)
813 | err := fig.processField(f)
814 | if err == nil {
815 | t.Fatalf("processField() returned nil error")
816 | }
817 | })
818 |
819 | t.Run("field with required", func(t *testing.T) {
820 | cfg := struct {
821 | X int `fig:"y" validate:"required"`
822 | }{}
823 | cfg.X = 10
824 | parent := &field{
825 | v: reflect.ValueOf(&cfg).Elem(),
826 | t: reflect.ValueOf(&cfg).Elem().Type(),
827 | sliceIdx: -1,
828 | }
829 |
830 | f := newStructField(parent, 0, fig.tag)
831 | err := fig.processField(f)
832 | if err != nil {
833 | t.Fatalf("processField() returned unexpected error: %v", err)
834 | }
835 | if cfg.X != 10 {
836 | t.Errorf("cfg.X == %d, expected %d", cfg.X, 10)
837 | }
838 | })
839 |
840 | t.Run("field with required error", func(t *testing.T) {
841 | cfg := struct {
842 | X int `fig:"y" validate:"required"`
843 | }{}
844 | parent := &field{
845 | v: reflect.ValueOf(&cfg).Elem(),
846 | t: reflect.ValueOf(&cfg).Elem().Type(),
847 | sliceIdx: -1,
848 | }
849 |
850 | f := newStructField(parent, 0, fig.tag)
851 | err := fig.processField(f)
852 | if err == nil {
853 | t.Fatalf("processField() returned nil error")
854 | }
855 | })
856 |
857 | t.Run("field with default and required", func(t *testing.T) {
858 | cfg := struct {
859 | X int `fig:"y" default:"10" validate:"required"`
860 | }{}
861 | parent := &field{
862 | v: reflect.ValueOf(&cfg).Elem(),
863 | t: reflect.ValueOf(&cfg).Elem().Type(),
864 | sliceIdx: -1,
865 | }
866 |
867 | f := newStructField(parent, 0, fig.tag)
868 | err := fig.processField(f)
869 | if err == nil {
870 | t.Fatalf("processField() expected error")
871 | }
872 | })
873 |
874 | t.Run("field overwritten by env", func(t *testing.T) {
875 | fig := defaultFig()
876 | fig.tag = "fig"
877 | fig.useEnv = true
878 | fig.envPrefix = "fig"
879 |
880 | os.Clearenv()
881 | setenv(t, "FIG_X", "MEN")
882 |
883 | cfg := struct {
884 | X string `fig:"x"`
885 | }{}
886 | cfg.X = "BOYS"
887 | parent := &field{
888 | v: reflect.ValueOf(&cfg).Elem(),
889 | t: reflect.ValueOf(&cfg).Elem().Type(),
890 | sliceIdx: -1,
891 | }
892 |
893 | f := newStructField(parent, 0, fig.tag)
894 | err := fig.processField(f)
895 | if err != nil {
896 | t.Fatalf("processField() returned unexpected error: %v", err)
897 | }
898 | if cfg.X != "MEN" {
899 | t.Errorf("cfg.X == %s, expected %s", cfg.X, "MEN")
900 | }
901 | })
902 |
903 | t.Run("field with bad env", func(t *testing.T) {
904 | fig := defaultFig()
905 | fig.tag = "fig"
906 | fig.useEnv = true
907 | fig.envPrefix = "fig"
908 |
909 | os.Clearenv()
910 | setenv(t, "FIG_I", "FIFTY")
911 |
912 | cfg := struct {
913 | I int
914 | }{}
915 | parent := &field{
916 | v: reflect.ValueOf(&cfg).Elem(),
917 | t: reflect.ValueOf(&cfg).Elem().Type(),
918 | sliceIdx: -1,
919 | }
920 |
921 | f := newStructField(parent, 0, fig.tag)
922 | err := fig.processField(f)
923 | if err == nil {
924 | t.Fatalf("processField() returned nil error")
925 | }
926 | })
927 | }
928 |
929 | func Test_fig_setFromEnv(t *testing.T) {
930 | fig := defaultFig()
931 | fig.envPrefix = "fig"
932 |
933 | var s string
934 | fv := reflect.ValueOf(&s)
935 |
936 | os.Clearenv()
937 | err := fig.setFromEnv(fv, "config.string")
938 | if err != nil {
939 | t.Fatalf("setFromEnv() unexpected error: %v", err)
940 | }
941 | if s != "" {
942 | t.Fatalf("s modified to %s", s)
943 | }
944 |
945 | setenv(t, "FIG_CONFIG_STRING", "goroutine")
946 | err = fig.setFromEnv(fv, "config.string")
947 | if err != nil {
948 | t.Fatalf("setFromEnv() unexpected error: %v", err)
949 | }
950 | if s != "goroutine" {
951 | t.Fatalf("s == %s, expected %s", s, "goroutine")
952 | }
953 | }
954 |
955 | func Test_fig_formatEnvKey(t *testing.T) {
956 | fig := defaultFig()
957 |
958 | for _, tc := range []struct {
959 | key string
960 | prefix string
961 | want string
962 | }{
963 | {
964 | key: "port",
965 | want: "PORT",
966 | },
967 | {
968 | key: "server.host",
969 | prefix: "myapp",
970 | want: "MYAPP_SERVER_HOST",
971 | },
972 | {
973 | key: "loggers[0].log_level",
974 | want: "LOGGERS_0_LOG_LEVEL",
975 | },
976 | {
977 | key: "nested[1].slice[2].twice",
978 | want: "NESTED_1_SLICE_2_TWICE",
979 | },
980 | {
981 | key: "client.http.timeout",
982 | prefix: "auth_s",
983 | want: "AUTH_S_CLIENT_HTTP_TIMEOUT",
984 | },
985 | } {
986 | t.Run(fmt.Sprintf("%s/%s", tc.prefix, tc.key), func(t *testing.T) {
987 | fig.envPrefix = tc.prefix
988 | got := fig.formatEnvKey(tc.key)
989 | if got != tc.want {
990 | t.Errorf("formatEnvKey() == %s, expected %s", got, tc.want)
991 | }
992 | })
993 | }
994 | }
995 |
996 | func Test_fig_setDefaultValue(t *testing.T) {
997 | fig := defaultFig()
998 | var b bool
999 | fv := reflect.ValueOf(&b).Elem()
1000 |
1001 | err := fig.setDefaultValue(fv, "true")
1002 | if err == nil {
1003 | t.Fatalf("expected err")
1004 | }
1005 | }
1006 |
1007 | func Test_fig_setValue(t *testing.T) {
1008 | fig := defaultFig()
1009 |
1010 | t.Run("nil ptr", func(t *testing.T) {
1011 | var s *string
1012 | fv := reflect.ValueOf(&s)
1013 |
1014 | err := fig.setValue(fv, "bat")
1015 | if err != nil {
1016 | t.Fatalf("unexpected err: %v", err)
1017 | }
1018 |
1019 | if *s != "bat" {
1020 | t.Fatalf("want %s, got %s", "bat", *s)
1021 | }
1022 | })
1023 |
1024 | t.Run("slice", func(t *testing.T) {
1025 | var slice []int
1026 | fv := reflect.ValueOf(&slice).Elem()
1027 |
1028 | err := fig.setValue(fv, "5")
1029 | if err != nil {
1030 | t.Fatalf("unexpected err: %v", err)
1031 | }
1032 |
1033 | if !reflect.DeepEqual([]int{5}, slice) {
1034 | t.Fatalf("want %+v, got %+v", []int{5}, slice)
1035 | }
1036 | })
1037 |
1038 | t.Run("int", func(t *testing.T) {
1039 | var i int
1040 | fv := reflect.ValueOf(&i).Elem()
1041 |
1042 | err := fig.setValue(fv, "-8")
1043 | if err != nil {
1044 | t.Fatalf("unexpected err: %v", err)
1045 | }
1046 |
1047 | if i != -8 {
1048 | t.Fatalf("want %d, got %d", -8, i)
1049 | }
1050 | })
1051 |
1052 | t.Run("bool", func(t *testing.T) {
1053 | var b bool
1054 | fv := reflect.ValueOf(&b).Elem()
1055 |
1056 | err := fig.setValue(fv, "true")
1057 | if err != nil {
1058 | t.Fatalf("unexpected err: %v", err)
1059 | }
1060 |
1061 | if !b {
1062 | t.Fatalf("want true")
1063 | }
1064 | })
1065 |
1066 | t.Run("bad bool", func(t *testing.T) {
1067 | var b bool
1068 | fv := reflect.ValueOf(&b).Elem()
1069 |
1070 | err := fig.setValue(fv, "αλήθεια")
1071 | if err == nil {
1072 | t.Fatalf("returned nil err")
1073 | }
1074 | })
1075 |
1076 | t.Run("duration", func(t *testing.T) {
1077 | var d time.Duration
1078 | fv := reflect.ValueOf(&d).Elem()
1079 |
1080 | err := fig.setValue(fv, "5h")
1081 | if err != nil {
1082 | t.Fatalf("unexpected err: %v", err)
1083 | }
1084 |
1085 | if d.Hours() != 5 {
1086 | t.Fatalf("want %v, got %v", 5*time.Hour, d)
1087 | }
1088 | })
1089 |
1090 | t.Run("bad duration", func(t *testing.T) {
1091 | var d time.Duration
1092 | fv := reflect.ValueOf(&d).Elem()
1093 |
1094 | err := fig.setValue(fv, "5decades")
1095 | if err == nil {
1096 | t.Fatalf("expexted err")
1097 | }
1098 | })
1099 |
1100 | t.Run("uint", func(t *testing.T) {
1101 | var i uint
1102 | fv := reflect.ValueOf(&i).Elem()
1103 |
1104 | err := fig.setValue(fv, "42")
1105 | if err != nil {
1106 | t.Fatalf("unexpected err: %v", err)
1107 | }
1108 |
1109 | if i != 42 {
1110 | t.Fatalf("want %d, got %d", 42, i)
1111 | }
1112 | })
1113 |
1114 | t.Run("float", func(t *testing.T) {
1115 | var f float32
1116 | fv := reflect.ValueOf(&f).Elem()
1117 |
1118 | err := fig.setValue(fv, "0.015625")
1119 | if err != nil {
1120 | t.Fatalf("unexpected err: %v", err)
1121 | }
1122 |
1123 | if f != 0.015625 {
1124 | t.Fatalf("want %f, got %f", 0.015625, f)
1125 | }
1126 | })
1127 |
1128 | t.Run("bad float", func(t *testing.T) {
1129 | var f float32
1130 | fv := reflect.ValueOf(&f).Elem()
1131 |
1132 | err := fig.setValue(fv, "-i")
1133 | if err == nil {
1134 | t.Fatalf("expected err")
1135 | }
1136 | })
1137 |
1138 | t.Run("string", func(t *testing.T) {
1139 | var s string
1140 | fv := reflect.ValueOf(&s).Elem()
1141 |
1142 | err := fig.setValue(fv, "bat")
1143 | if err != nil {
1144 | t.Fatalf("unexpected err: %v", err)
1145 | }
1146 |
1147 | if s != "bat" {
1148 | t.Fatalf("want %s, got %s", "bat", s)
1149 | }
1150 | })
1151 |
1152 | t.Run("time", func(t *testing.T) {
1153 | var tme time.Time
1154 | fv := reflect.ValueOf(&tme).Elem()
1155 |
1156 | err := fig.setValue(fv, "2020-01-01T00:00:00Z")
1157 | if err != nil {
1158 | t.Fatalf("unexpected err: %v", err)
1159 | }
1160 |
1161 | want, err := time.Parse(fig.timeLayout, "2020-01-01T00:00:00Z")
1162 | if err != nil {
1163 | t.Fatalf("error parsing time: %v", err)
1164 | }
1165 |
1166 | if !tme.Equal(want) {
1167 | t.Fatalf("want %v, got %v", want, tme)
1168 | }
1169 | })
1170 |
1171 | t.Run("bad time", func(t *testing.T) {
1172 | var tme time.Time
1173 | fv := reflect.ValueOf(&tme).Elem()
1174 |
1175 | err := fig.setValue(fv, "2020-Feb-01T00:00:00Z")
1176 | if err == nil {
1177 | t.Fatalf("expected err")
1178 | }
1179 | })
1180 |
1181 | t.Run("regexp", func(t *testing.T) {
1182 | var re regexp.Regexp
1183 | fv := reflect.ValueOf(&re).Elem()
1184 |
1185 | err := fig.setValue(fv, "[a-z]+")
1186 | if err != nil {
1187 | t.Fatalf("unexpected err: %v", err)
1188 | }
1189 |
1190 | if want := regexp.MustCompile("[a-z]+"); re.String() != want.String() {
1191 | t.Fatalf("want %v, got %v", want, re)
1192 | }
1193 | })
1194 |
1195 | t.Run("bad regexp", func(t *testing.T) {
1196 | var re regexp.Regexp
1197 | fv := reflect.ValueOf(&re).Elem()
1198 |
1199 | err := fig.setValue(fv, "[a-")
1200 | if err == nil {
1201 | t.Fatalf("expected err")
1202 | }
1203 | })
1204 |
1205 | t.Run("interface returns error", func(t *testing.T) {
1206 | var i interface{}
1207 | fv := reflect.ValueOf(i)
1208 |
1209 | err := fig.setValue(fv, "empty")
1210 | if err == nil {
1211 | t.Fatalf("expected err")
1212 | }
1213 | })
1214 |
1215 | t.Run("struct returns error", func(t *testing.T) {
1216 | s := struct{ Name string }{}
1217 | fv := reflect.ValueOf(&s).Elem()
1218 |
1219 | err := fig.setValue(fv, "foo")
1220 | if err == nil {
1221 | t.Fatalf("expected err")
1222 | }
1223 | })
1224 | }
1225 |
1226 | func Test_fig_setSlice(t *testing.T) {
1227 | f := defaultFig()
1228 |
1229 | for _, tc := range []struct {
1230 | Name string
1231 | InSlice interface{}
1232 | WantSlice interface{}
1233 | Val string
1234 | }{
1235 | {
1236 | Name: "ints",
1237 | InSlice: &[]int{},
1238 | WantSlice: &[]int{5, 10, 15},
1239 | Val: "[5,10,15]",
1240 | },
1241 | {
1242 | Name: "ints-no-square-braces",
1243 | InSlice: &[]int{},
1244 | WantSlice: &[]int{5, 10, 15},
1245 | Val: "5,10,15",
1246 | },
1247 | {
1248 | Name: "uints",
1249 | InSlice: &[]uint{},
1250 | WantSlice: &[]uint{5, 10, 15, 20, 25},
1251 | Val: "[5,10,15,20,25]",
1252 | },
1253 | {
1254 | Name: "floats",
1255 | InSlice: &[]float32{},
1256 | WantSlice: &[]float32{1.5, 1.125, -0.25},
1257 | Val: "[1.5,1.125,-0.25]",
1258 | },
1259 | {
1260 | Name: "strings",
1261 | InSlice: &[]string{},
1262 | WantSlice: &[]string{"a", "b", "c", "d"},
1263 | Val: "[a,b,c,d]",
1264 | },
1265 | {
1266 | Name: "durations",
1267 | InSlice: &[]time.Duration{},
1268 | WantSlice: &[]time.Duration{30 * time.Minute, 2 * time.Hour},
1269 | Val: "[30m,2h]",
1270 | },
1271 | {
1272 | Name: "times",
1273 | InSlice: &[]time.Time{},
1274 | WantSlice: &[]time.Time{
1275 | time.Date(2019, 12, 25, 10, 30, 30, 0, time.UTC),
1276 | time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC),
1277 | },
1278 | Val: "[2019-12-25T10:30:30Z,2020-01-01T00:00:00Z]",
1279 | },
1280 | {
1281 | Name: "regexps",
1282 | InSlice: &[]*regexp.Regexp{},
1283 | WantSlice: &[]*regexp.Regexp{
1284 | regexp.MustCompile("[a-z]+"),
1285 | regexp.MustCompile(".*"),
1286 | },
1287 | Val: "[[a-z]+,.*]",
1288 | },
1289 | } {
1290 | t.Run(tc.Val, func(t *testing.T) {
1291 | in := reflect.ValueOf(tc.InSlice).Elem()
1292 |
1293 | err := f.setSlice(in, tc.Val)
1294 | if err != nil {
1295 | t.Fatalf("unexpected error: %v", err)
1296 | }
1297 |
1298 | want := reflect.ValueOf(tc.WantSlice).Elem()
1299 |
1300 | if !reflect.DeepEqual(want.Interface(), in.Interface()) {
1301 | t.Fatalf("want %+v, got %+v", want, in)
1302 | }
1303 | })
1304 | }
1305 |
1306 | t.Run("negative int into uint returns error", func(t *testing.T) {
1307 | in := &[]uint{}
1308 | val := "[-5]"
1309 |
1310 | err := f.setSlice(reflect.ValueOf(in).Elem(), val)
1311 | if err == nil {
1312 | t.Fatalf("expected err")
1313 | }
1314 | })
1315 | }
1316 |
1317 | func setenv(t *testing.T, key, value string) {
1318 | t.Helper()
1319 | t.Setenv(key, value)
1320 | }
1321 |
--------------------------------------------------------------------------------