├── .gitignore ├── tests └── assets │ ├── sample.env │ ├── sample.json │ ├── sample.yaml │ └── sample.toml ├── Makefile ├── yaml.go ├── toml.go ├── go.mod ├── json.go ├── gophig.go ├── .github └── workflows │ └── ci.yml ├── README.md ├── CONTRIBUTING.md ├── LICENSE ├── marshal.go ├── gophig_test.go ├── config.go ├── go.sum ├── dotenv.go └── CODE_OF_CONDUCT.md /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | tests/tmp -------------------------------------------------------------------------------- /tests/assets/sample.env: -------------------------------------------------------------------------------- 1 | NAME=jane 2 | SURNAME=doe 3 | AGE=20 4 | -------------------------------------------------------------------------------- /tests/assets/sample.json: -------------------------------------------------------------------------------- 1 | {"Name":"jane","Surname":"doe","Age":20} -------------------------------------------------------------------------------- /tests/assets/sample.yaml: -------------------------------------------------------------------------------- 1 | name: jane 2 | surname: doe 3 | age: 20 4 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: tests 2 | tests: 3 | go mod tidy 4 | go test ./... 5 | -------------------------------------------------------------------------------- /tests/assets/sample.toml: -------------------------------------------------------------------------------- 1 | Name = 'jane' 2 | Surname = 'doe' 3 | Age = 20 4 | -------------------------------------------------------------------------------- /yaml.go: -------------------------------------------------------------------------------- 1 | package gophig 2 | 3 | import ( 4 | "gopkg.in/yaml.v3" 5 | ) 6 | 7 | // YAMLMarshaler is a Marshaler that uses the go-yaml/yaml package. 8 | type YAMLMarshaler struct{} 9 | 10 | // Marshal ... 11 | func (YAMLMarshaler) Marshal(v interface{}) ([]byte, error) { 12 | return yaml.Marshal(v) 13 | } 14 | 15 | // Unmarshal ... 16 | func (YAMLMarshaler) Unmarshal(data []byte, v interface{}) error { 17 | return yaml.Unmarshal(data, v) 18 | } 19 | -------------------------------------------------------------------------------- /toml.go: -------------------------------------------------------------------------------- 1 | package gophig 2 | 3 | import ( 4 | "github.com/pelletier/go-toml/v2" 5 | ) 6 | 7 | // TOMLMarshaler is a Marshaler that uses the pelletier/go-toml package. 8 | type TOMLMarshaler struct{} 9 | 10 | // Marshal ... 11 | func (TOMLMarshaler) Marshal(v interface{}) ([]byte, error) { 12 | return toml.Marshal(v) 13 | } 14 | 15 | // Unmarshal ... 16 | func (TOMLMarshaler) Unmarshal(data []byte, v interface{}) error { 17 | return toml.Unmarshal(data, v) 18 | } 19 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/restartfu/gophig 2 | 3 | go 1.20 4 | 5 | require ( 6 | github.com/goccy/go-json v0.10.2 7 | github.com/joho/godotenv v1.5.1 8 | github.com/pelletier/go-toml/v2 v2.0.7 9 | github.com/stretchr/testify v1.9.0 10 | gopkg.in/yaml.v3 v3.0.1 11 | ) 12 | 13 | require ( 14 | github.com/davecgh/go-spew v1.1.1 // indirect 15 | github.com/pmezard/go-difflib v1.0.0 // indirect 16 | gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect 17 | ) 18 | -------------------------------------------------------------------------------- /json.go: -------------------------------------------------------------------------------- 1 | package gophig 2 | 3 | import "github.com/goccy/go-json" 4 | 5 | // JSONMarshaler is a Marshaler that uses the goccy/go-json package. 6 | type JSONMarshaler struct { 7 | Indent bool 8 | } 9 | 10 | // Marshal ... 11 | func (m JSONMarshaler) Marshal(v interface{}) ([]byte, error) { 12 | if m.Indent { 13 | return json.MarshalIndent(v, "", "\t") 14 | } 15 | return json.Marshal(v) 16 | } 17 | 18 | // Unmarshal ... 19 | func (JSONMarshaler) Unmarshal(data []byte, v interface{}) error { 20 | return json.Unmarshal(data, v) 21 | } 22 | -------------------------------------------------------------------------------- /gophig.go: -------------------------------------------------------------------------------- 1 | package gophig 2 | 3 | import ( 4 | "io/fs" 5 | ) 6 | 7 | // Gophig is a struct that contains the name, extension, and permission of a configuration file. 8 | type Gophig[T any] struct { 9 | ctx *RawContext 10 | 11 | name string 12 | marshaler Marshaler 13 | perm fs.FileMode 14 | } 15 | 16 | // NewGophig returns a new Gophig struct. 17 | func NewGophig[T any](name string, marshaler Marshaler, perm fs.FileMode) *Gophig[T] { 18 | g := &Gophig[T]{ 19 | name: name, 20 | marshaler: marshaler, 21 | perm: perm, 22 | 23 | ctx: newRawContext(name, marshaler, perm, nil), 24 | } 25 | return g 26 | } 27 | 28 | // SaveConf saves the given interface to the configuration file. 29 | func (g *Gophig[T]) SaveConf(v T) error { 30 | g.ctx.values["value"] = v 31 | return SaveConfContext(g.ctx) 32 | } 33 | 34 | // LoadConf loads the configuration file into the given interface. 35 | func (g *Gophig[T]) LoadConf() (T, error) { 36 | return LoadConfContext[T](g.ctx) 37 | } 38 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: Go CI 2 | 3 | on: 4 | push: 5 | branches: 6 | - "**" # runs on push to any branch 7 | pull_request: 8 | branches: 9 | - "**" # runs on all PRs 10 | 11 | jobs: 12 | test: 13 | name: Run Tests 14 | runs-on: ubuntu-latest 15 | 16 | strategy: 17 | matrix: 18 | go-version: [1.25] 19 | 20 | steps: 21 | - name: Checkout code 22 | uses: actions/checkout@v4 23 | 24 | - name: Set up Go 25 | uses: actions/setup-go@v4 26 | with: 27 | go-version: ${{ matrix.go-version }} 28 | 29 | - name: Cache Go modules 30 | uses: actions/cache@v3 31 | with: 32 | path: | 33 | ~/.cache/go-build 34 | ~/go/pkg/mod 35 | key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} 36 | restore-keys: | 37 | ${{ runner.os }}-go- 38 | 39 | - name: Install dependencies 40 | run: go mod download 41 | 42 | - name: Run tests 43 | run: go test ./... -v 44 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Gophig 2 | 3 | Gophig is a simple configuration manager for Go projects. It supports marshaling and unmarshaling config files (e.g., TOML) into typed Go structs. 4 | 5 | # Installation 6 | 7 | go get git.restartfu.com/restart/gophig 8 | 9 | # Usage 10 | 11 | Define your configuration struct: 12 | 13 | ```go 14 | type Foo struct { 15 | Foo string toml:"foo" 16 | Bar string toml:"bar" 17 | } 18 | ``` 19 | 20 | # Create a new *Gophig instance: 21 | ```go 22 | g := gophig.NewGophig[Foo]("./config.toml", gophig.TOMLMarshaler, os.ModePerm) 23 | ``` 24 | # Writing a Config 25 | ```go 26 | myFoo := Foo{Foo: "foo", Bar: "bar"} 27 | 28 | if err := g.WriteConf(myFoo); err != nil { 29 | log.Fatalln(err) 30 | } 31 | ``` 32 | 33 | This will generate a config.toml file with: 34 | ``` 35 | foo = "foo" 36 | bar = "bar" 37 | ``` 38 | # Reading a Config 39 | 40 | ```go 41 | myFoo, err := g.ReadConf() 42 | if err != nil { 43 | log.Fatalln(err) 44 | } 45 | 46 | log.Println(myFoo) 47 | ``` 48 | 49 | Output: 50 | 51 | ``` 52 | {Foo: "foo", Bar: "bar"} 53 | ``` 54 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to gophig 2 | 3 | 🎉 Thanks for taking the time to contribute! 🎉 4 | We welcome bug reports, feature requests, code improvements, documentation updates, and new ideas. 5 | 6 | --- 7 | 8 | ## How to Contribute 9 | 10 | 1. **Fork & Clone** 11 | ```bash 12 | git clone https://github.com/RestartFU/gophig.git 13 | cd gophig 14 | ``` 15 | 2. **Create a Branch** 16 | ```bash 17 | git checkout -b feature/my-change 18 | ``` 19 | 3. **Make Your Changes** 20 | - Write clear, concise code. 21 | - Run go fmt ./... before committing. 22 | - Add or update tests for new features or bug fixes. 23 | 4. **Run Tests** 24 | ```bash 25 | go test ./... 26 | ``` 27 | 5. **Commit & Push** 28 | ```bash 29 | git commit -m "feat: add YAML config example" 30 | git push origin feature/my-change 31 | ``` 32 | 6. **Open a Pull Request** 33 | - Open a PR against the master branch. 34 | - Describe what you changed and why. 35 | 36 | # Coding Guidelines 37 | - Follow Go best practices. 38 | - Keep functions small and focused. 39 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | This is free and unencumbered software released into the public domain. 2 | 3 | Anyone is free to copy, modify, publish, use, compile, sell, or 4 | distribute this software, either in source code form or as a compiled 5 | binary, for any purpose, commercial or non-commercial, and by any 6 | means. 7 | 8 | In jurisdictions that recognize copyright laws, the author or authors 9 | of this software dedicate any and all copyright interest in the 10 | software to the public domain. We make this dedication for the benefit 11 | of the public at large and to the detriment of our heirs and 12 | successors. We intend this dedication to be an overt act of 13 | relinquishment in perpetuity of all present and future rights to this 14 | software under copyright law. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 17 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 18 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 19 | IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR 20 | OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 21 | ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 22 | OTHER DEALINGS IN THE SOFTWARE. 23 | 24 | For more information, please refer to 25 | -------------------------------------------------------------------------------- /marshal.go: -------------------------------------------------------------------------------- 1 | package gophig 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "strings" 7 | ) 8 | 9 | // UnsupportedExtensionError is an error that is returned when a file extension is not supported. 10 | type UnsupportedExtensionError struct { 11 | extension string 12 | } 13 | 14 | // Error ... 15 | func (e UnsupportedExtensionError) Error() string { 16 | return fmt.Sprintf("error: gophig does not support the file extension '%s' at the moment", e.extension) 17 | } 18 | 19 | // IsUnsupportedExtensionErr returns true if the error is an UnsupportedExtensionError. 20 | func IsUnsupportedExtensionErr(err error) bool { 21 | var unsupportedExtensionError UnsupportedExtensionError 22 | ok := errors.As(err, &unsupportedExtensionError) 23 | return ok 24 | } 25 | 26 | // Marshaler is an interface that can marshal and unmarshal data. 27 | type Marshaler interface { 28 | Marshal(v any) ([]byte, error) 29 | Unmarshal(data []byte, v any) error 30 | } 31 | 32 | // MarshalerFromExtension is a Marshaler that uses a file extension to determine which Marshaler to use. 33 | func MarshalerFromExtension(ext string) (Marshaler, error) { 34 | ext = strings.ToLower(ext) 35 | switch ext { 36 | case "toml": 37 | return TOMLMarshaler{}, nil 38 | case "json": 39 | return JSONMarshaler{}, nil 40 | case "yaml": 41 | return YAMLMarshaler{}, nil 42 | case "env": 43 | return DotenvMarshaler{}, nil 44 | } 45 | return nil, UnsupportedExtensionError{ext} 46 | } 47 | -------------------------------------------------------------------------------- /gophig_test.go: -------------------------------------------------------------------------------- 1 | package gophig_test 2 | 3 | import ( 4 | "os" 5 | "testing" 6 | 7 | "github.com/restartfu/gophig" 8 | "github.com/stretchr/testify/require" 9 | ) 10 | 11 | type MockMarshaler struct{} 12 | 13 | func (m MockMarshaler) Marshal(any) ([]byte, error) { 14 | return []byte{}, nil 15 | } 16 | func (MockMarshaler) Unmarshal([]byte, any) error { 17 | return nil 18 | } 19 | 20 | func TestNewGophig(t *testing.T) { 21 | t.Run("gophig creation is successful", func(t *testing.T) { 22 | g := gophig.NewGophig[any]("", MockMarshaler{}, os.ModePerm) 23 | require.NotNil(t, g) 24 | }) 25 | } 26 | 27 | type Sample struct { 28 | Name string `json,toml,yaml:"name"` 29 | Surname string `json,toml,yaml:"surname"` 30 | Age int `json,toml,yaml:"age"` 31 | } 32 | 33 | func TestGophig_GetConf(t *testing.T) { 34 | for _, ext := range []string{ 35 | "json", 36 | "toml", 37 | "yaml", 38 | "env", 39 | } { 40 | t.Run("sample unmarshals successfully into "+ext+" sample struct", func(t *testing.T) { 41 | marshaler, err := gophig.MarshalerFromExtension(ext) 42 | require.NoError(t, err) 43 | 44 | g := gophig.NewGophig[Sample]("tests/assets/sample."+ext, marshaler, os.ModePerm) 45 | require.NotNil(t, g) 46 | 47 | sample, err := g.LoadConf() 48 | require.NoError(t, err) 49 | 50 | require.Equal(t, 51 | Sample{ 52 | Name: "jane", 53 | Surname: "doe", 54 | Age: 20, 55 | }, 56 | sample, 57 | ) 58 | }) 59 | } 60 | } 61 | 62 | func TestGophig_SetConf(t *testing.T) { 63 | for _, ext := range []string{ 64 | "json", 65 | "toml", 66 | "yaml", 67 | "env", 68 | } { 69 | t.Run("sample marshals successfully into "+ext+" sample data", func(t *testing.T) { 70 | marshaler, err := gophig.MarshalerFromExtension(ext) 71 | require.NoError(t, err) 72 | 73 | err = os.MkdirAll("tests/tmp", os.ModePerm) 74 | require.NoError(t, err) 75 | defer func() { 76 | require.NoError(t, os.RemoveAll("tests/tmp")) 77 | }() 78 | 79 | g := gophig.NewGophig[Sample]("tests/tmp/sample."+ext, marshaler, os.ModePerm) 80 | require.NotNil(t, g) 81 | 82 | sample := Sample{ 83 | Name: "jane", 84 | Surname: "doe", 85 | Age: 20, 86 | } 87 | 88 | err = g.SaveConf(sample) 89 | require.NoError(t, err) 90 | }) 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /config.go: -------------------------------------------------------------------------------- 1 | package gophig 2 | 3 | import ( 4 | "context" 5 | "errors" 6 | "fmt" 7 | "os" 8 | "strings" 9 | ) 10 | 11 | func SaveConf[T any](path string, marshaler Marshaler, v T) (T, error) { 12 | ctx := newRawContext(path, marshaler, os.ModePerm, v) 13 | return LoadConfContext[T](ctx) 14 | } 15 | 16 | func LoadConf[T any](path string, marshaler Marshaler) (T, error) { 17 | ctx := newRawContext(path, marshaler, os.ModePerm, nil) 18 | return LoadConfContext[T](ctx) 19 | } 20 | 21 | type RawContext struct { 22 | context.Context 23 | values map[any]any 24 | } 25 | 26 | func newRawContext(name string, marshaler Marshaler, perm os.FileMode, value any) *RawContext { 27 | return &RawContext{ 28 | Context: context.Background(), 29 | values: map[any]any{ 30 | "name": name, 31 | "marshaler": marshaler, 32 | "perm": perm, 33 | "value": value, 34 | }, 35 | } 36 | } 37 | 38 | func (c *RawContext) Value(key any) any { 39 | return c.values[key] 40 | } 41 | 42 | // LoadConfContext loads the configuration file into the given type. 43 | func LoadConfContext[T any](ctx context.Context) (T, error) { 44 | v := new(T) 45 | name, marshaler, err := extractContextValues(ctx) 46 | if err != nil { 47 | return *v, err 48 | } 49 | 50 | data, err := os.ReadFile(name) 51 | if err != nil { 52 | return *v, err 53 | } 54 | 55 | err = marshaler.Unmarshal(data, v) 56 | return *v, err 57 | } 58 | 59 | // SaveConfContext saves the given type to the configuration file. 60 | func SaveConfContext(ctx context.Context) error { 61 | name, marshaler, err := extractContextValues(ctx) 62 | if err != nil { 63 | return err 64 | } 65 | 66 | perm, ok := ctx.Value("perm").(os.FileMode) 67 | if !ok { 68 | return errors.New("perm not found in context") 69 | } 70 | 71 | v := ctx.Value("value") 72 | data, err := marshaler.Marshal(v) 73 | if err != nil { 74 | return err 75 | } 76 | 77 | return os.WriteFile(name, data, perm) 78 | } 79 | 80 | func extractContextValues(ctx context.Context) (string, Marshaler, error) { 81 | var missing []string 82 | name, ok := ctx.Value("name").(string) 83 | if !ok { 84 | missing = append(missing, "name") 85 | } 86 | 87 | marshaler, ok := ctx.Value("marshaler").(Marshaler) 88 | if !ok { 89 | missing = append(missing, "marshaler") 90 | } 91 | 92 | if len(missing) > 0 { 93 | return "", marshaler, fmt.Errorf("missing required values in context: %s", strings.Join(missing, ",")) 94 | } 95 | return name, marshaler, nil 96 | } 97 | -------------------------------------------------------------------------------- /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/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU= 5 | github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= 6 | github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0= 7 | github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= 8 | github.com/kr/pretty v0.2.1 h1:Fmg33tUaq4/8ym9TJN1x7sLJnHVwhP33CNkpYV/7rwI= 9 | github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= 10 | github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= 11 | github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= 12 | github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= 13 | github.com/pelletier/go-toml/v2 v2.0.7 h1:muncTPStnKRos5dpVKULv2FVd4bMOhNePj9CjgDb8Us= 14 | github.com/pelletier/go-toml/v2 v2.0.7/go.mod h1:eumQOmlWiOPt5WriQQqoM5y18pDHwha2N+QD+EUNTek= 15 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 16 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 17 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 18 | github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= 19 | github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= 20 | github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 21 | github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= 22 | github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= 23 | github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= 24 | github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= 25 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 26 | gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= 27 | gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= 28 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 29 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= 30 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 31 | -------------------------------------------------------------------------------- /dotenv.go: -------------------------------------------------------------------------------- 1 | package gophig 2 | 3 | import ( 4 | "fmt" 5 | "reflect" 6 | "strings" 7 | 8 | "github.com/joho/godotenv" 9 | ) 10 | 11 | type DotenvMarshaler struct{} 12 | 13 | func (DotenvMarshaler) Marshal(v any) ([]byte, error) { 14 | rv := reflect.ValueOf(v) 15 | if rv.Kind() == reflect.Pointer { 16 | rv = rv.Elem() 17 | } 18 | if !rv.IsValid() { 19 | return nil, fmt.Errorf("DotenvMarshaler: Marshal expects a valid value") 20 | } 21 | 22 | var sb strings.Builder 23 | 24 | switch rv.Kind() { 25 | case reflect.Map: 26 | m, ok := v.(map[string]string) 27 | if !ok { 28 | return nil, fmt.Errorf("DotenvMarshaler: Marshal expects map[string]string") 29 | } 30 | for key, val := range m { 31 | val = strings.ReplaceAll(val, "\n", `\n`) 32 | sb.WriteString(fmt.Sprintf("%s=%s\n", key, val)) 33 | } 34 | 35 | case reflect.Struct: 36 | rt := rv.Type() 37 | for i := 0; i < rt.NumField(); i++ { 38 | field := rt.Field(i) 39 | fv := rv.Field(i) 40 | if !fv.CanInterface() { 41 | continue 42 | } 43 | 44 | key := field.Tag.Get("env") 45 | if key == "" { 46 | continue // skip fields without env tag 47 | } 48 | 49 | val := fmt.Sprintf("%v", fv.Interface()) 50 | val = strings.ReplaceAll(val, "\n", `\n`) 51 | sb.WriteString(fmt.Sprintf("%s=%s\n", key, val)) 52 | } 53 | 54 | default: 55 | return nil, fmt.Errorf("DotenvMarshaler: unsupported type %s", rv.Kind()) 56 | } 57 | 58 | return []byte(sb.String()), nil 59 | } 60 | 61 | func (DotenvMarshaler) Unmarshal(data []byte, v any) error { 62 | envMap, err := godotenv.Unmarshal(string(data)) 63 | if err != nil { 64 | return fmt.Errorf("DotenvMarshaler: failed to unmarshal dotenv: %w", err) 65 | } 66 | 67 | rv := reflect.ValueOf(v) 68 | if rv.Kind() != reflect.Pointer || rv.IsNil() { 69 | return fmt.Errorf("DotenvMarshaler: Unmarshal expects a non-nil pointer") 70 | } 71 | 72 | rvElem := rv.Elem() 73 | 74 | switch rvElem.Kind() { 75 | case reflect.Map: 76 | if rvElem.Type().Key().Kind() != reflect.String || rvElem.Type().Elem().Kind() != reflect.String { 77 | return fmt.Errorf("DotenvMarshaler: only map[string]string supported") 78 | } 79 | rvElem.Set(reflect.ValueOf(envMap)) 80 | 81 | case reflect.Struct: 82 | for i := 0; i < rvElem.NumField(); i++ { 83 | field := rvElem.Type().Field(i) 84 | tag := field.Tag.Get("env") 85 | if tag == "" { 86 | tag = strings.ToUpper(field.Name) 87 | } 88 | if val, ok := envMap[tag]; ok { 89 | f := rvElem.Field(i) 90 | if f.CanSet() { 91 | switch f.Kind() { 92 | case reflect.String: 93 | f.SetString(val) 94 | case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: 95 | var intVal int64 96 | _, err := fmt.Sscan(val, &intVal) 97 | if err != nil { 98 | return fmt.Errorf("DotenvMarshaler: failed to parse int for field %s: %w", field.Name, err) 99 | } 100 | f.SetInt(intVal) 101 | case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: 102 | var uintVal uint64 103 | _, err := fmt.Sscan(val, &uintVal) 104 | if err != nil { 105 | return fmt.Errorf("DotenvMarshaler: failed to parse uint for field %s: %w", field.Name, err) 106 | } 107 | f.SetUint(uintVal) 108 | case reflect.Bool: 109 | var boolVal bool 110 | _, err := fmt.Sscan(val, &boolVal) 111 | if err != nil { 112 | return fmt.Errorf("DotenvMarshaler: failed to parse bool for field %s: %w", field.Name, err) 113 | } 114 | f.SetBool(boolVal) 115 | case reflect.Float32, reflect.Float64: 116 | var floatVal float64 117 | _, err := fmt.Sscan(val, &floatVal) 118 | if err != nil { 119 | return fmt.Errorf("DotenvMarshaler: failed to parse float for field %s: %w", field.Name, err) 120 | } 121 | f.SetFloat(floatVal) 122 | default: 123 | return fmt.Errorf("DotenvMarshaler: unsupported field type %s for field %s", f.Kind(), field.Name) 124 | } 125 | } 126 | } 127 | } 128 | 129 | default: 130 | return fmt.Errorf("DotenvMarshaler: unsupported type %s", rvElem.Kind()) 131 | } 132 | 133 | return nil 134 | } 135 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, caste, color, religion, or sexual identity and orientation. 6 | 7 | We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. 8 | 9 | ## Our Standards 10 | 11 | Examples of behavior that contributes to a positive environment for our community include: 12 | 13 | * Demonstrating empathy and kindness toward other people 14 | * Being respectful of differing opinions, viewpoints, and experiences 15 | * Giving and gracefully accepting constructive feedback 16 | * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience 17 | * Focusing on what is best not just for us as individuals, but for the overall community 18 | 19 | Examples of unacceptable behavior include: 20 | 21 | * The use of sexualized language or imagery, and sexual attention or advances of any kind 22 | * Trolling, insulting or derogatory comments, and personal or political attacks 23 | * Public or private harassment 24 | * Publishing others' private information, such as a physical or email address, without their explicit permission 25 | * Other conduct which could reasonably be considered inappropriate in a professional setting 26 | 27 | ## Enforcement Responsibilities 28 | 29 | Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. 30 | 31 | Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. 32 | 33 | ## Scope 34 | 35 | This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. 36 | 37 | ## Enforcement 38 | 39 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at complaints@restartfu.com. All complaints will be reviewed and investigated promptly and fairly. 40 | 41 | All community leaders are obligated to respect the privacy and security of the reporter of any incident. 42 | 43 | ## Enforcement Guidelines 44 | 45 | Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: 46 | 47 | ### 1. Correction 48 | 49 | **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. 50 | 51 | **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. 52 | 53 | ### 2. Warning 54 | 55 | **Community Impact**: A violation through a single incident or series of actions. 56 | 57 | **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. 58 | 59 | ### 3. Temporary Ban 60 | 61 | **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. 62 | 63 | **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. 64 | 65 | ### 4. Permanent Ban 66 | 67 | **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. 68 | 69 | **Consequence**: A permanent ban from any sort of public interaction within the community. 70 | 71 | ## Attribution 72 | 73 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.1, available at [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. 74 | 75 | Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder][Mozilla CoC]. 76 | 77 | For answers to common questions about this code of conduct, see the FAQ at [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at [https://www.contributor-covenant.org/translations][translations]. 78 | 79 | [homepage]: https://www.contributor-covenant.org 80 | [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html 81 | [Mozilla CoC]: https://github.com/mozilla/diversity 82 | [FAQ]: https://www.contributor-covenant.org/faq 83 | [translations]: https://www.contributor-covenant.org/translations 84 | --------------------------------------------------------------------------------