From e855d33ab0954dce3944bc22b8a858bf02542285 Mon Sep 17 00:00:00 2001 From: Alfarih Faza Date: Mon, 27 Dec 2021 13:40:44 +0700 Subject: [PATCH] build(chore): Initial commit --- .editorconfig | 12 ++++ .gitattributes | 1 + .gitignore | 42 +++++++++++++ LICENSE.md | 21 +++++++ README.md | 44 ++++++++++++++ env.go | 159 +++++++++++++++++++++++++++++++++++++++++++++++++ env_test.go | 22 +++++++ go.mod | 15 +++++ go.sum | 15 +++++ 9 files changed, 331 insertions(+) create mode 100644 .editorconfig create mode 100644 .gitattributes create mode 100644 .gitignore create mode 100644 LICENSE.md create mode 100644 README.md create mode 100644 env.go create mode 100644 env_test.go create mode 100644 go.mod create mode 100644 go.sum diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..c1322dc --- /dev/null +++ b/.editorconfig @@ -0,0 +1,12 @@ +# EditorConfig is awesome: https://EditorConfig.org + +# top-most EditorConfig file +root = true + +[*] +indent_style = space +indent_size = 4 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = false +insert_final_newline = false \ No newline at end of file diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..94f480d --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +* text=auto eol=lf \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..93bbcc8 --- /dev/null +++ b/.gitignore @@ -0,0 +1,42 @@ +.idea +.vscode + +# Build +build +dist + +.DS_Store +*.[56789ao] +*.a[56789o] +*.so +*.pyc +._* +.nfs.* +[56789a].out +*~ +*.orig +*.rej +*.exe +.*.swp +core +*.cgo*.go +*.cgo*.c +_cgo_* +_obj +_test +_testmain.go + +*.exe~ +*.dll +*.dylib + +# Test binary, built with `go test -c` +*.test + +# Output of the go coverage tool, specifically when used with LiteIDE +*.out + +# Dependency directories (remove the comment below to include it) +# vendor/ +.env +config.json \ No newline at end of file diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..0aeae76 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2013-present Pagar.me Pagamentos S/A + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..b010431 --- /dev/null +++ b/README.md @@ -0,0 +1,44 @@ +# Noob-Env + +[![Go Reference](https://pkg.go.dev/badge/github.com/alfarih31/nb-go-env.svg)](https://pkg.go.dev/github.com/alfarih31/nb-go-env) +![GitHub go.mod Go version (subdirectory of monorepo)](https://img.shields.io/github/go-mod/go-version/alfarih31/nb-go-env?style=flat-square) +![GitHub release (latest by date)](https://img.shields.io/github/v/release/alfarih31/nb-go-env?style=flat-square) + +Noob Env is a tools for working with `.env`, such as: +- Load Env +- Get Env + +## Contents + +- [Noob-Env](#Noob-Env) + - [Installation](#Installation) + - [Quick Start & Usage](#Quick) + +## Installation + +To install this package, you need to install Go (**version 1.17+ is required**) & initiate your Go workspace first. + +1. After you initiate your workspace then you can install this package with below command. + +```shell +go get -u github.com/alfarih31/nb-go-env +``` + +2. Import it in your code + +```go +import "github.com/alfarih31/nb-go-env" +``` + +## Quick Start & Usage + +See the test: +- [env_test.go](env_test.go) + +## Contributors ## + +- Alfarih Faza + +## License + +This project is licensed under the - see the [LICENSE.md](LICENSE.md) file for details \ No newline at end of file diff --git a/env.go b/env.go new file mode 100644 index 0000000..8e9a227 --- /dev/null +++ b/env.go @@ -0,0 +1,159 @@ +package env + +import ( + "encoding/json" + "errors" + "github.com/alfarih31/nb-go-parser" + "github.com/joho/godotenv" + "os" +) + +var ErrorVarNotExist = errors.New("variable not exist") + +type env struct { + envs map[string]string + useDotEnv bool +} + +type Env interface { + GetInt(k string, def ...int) (int, error) + GetString(k string, def ...string) (string, error) + GetBool(k string, def ...bool) (bool, error) + GetStringArr(k string, def ...[]string) ([]string, error) + GetIntArr(k string, def ...[]int) ([]int, error) + Dump() (string, error) +} + +func (c env) GetInt(k string, def ...int) (int, error) { + cfg, exist := c.get(k) + + if !exist { + if len(def) == 0 { + return 0, ErrorVarNotExist + } + return def[0], nil + } + + i, e := parser.String(cfg).ToInt() + + if e != nil { + if len(def) == 0 { + return 0, e + } + + return def[0], nil + } + + return i, e +} + +func (c env) GetString(k string, def ...string) (string, error) { + cfg, exist := c.get(k) + if !exist { + if len(def) == 0 { + return "", ErrorVarNotExist + } + return def[0], nil + } + + return cfg, nil +} + +func (c env) GetBool(k string, def ...bool) (bool, error) { + cfg, exist := c.get(k) + if !exist { + if len(def) == 0 { + return false, ErrorVarNotExist + } + return def[0], nil + } + + b, e := parser.String(cfg).ToBool() + if e != nil { + if len(def) == 0 { + return false, e + } + + return def[0], nil + } + + return b, e +} + +func (c env) get(k string) (string, bool) { + if c.useDotEnv { + cfg, exist := c.envs[k] + return cfg, exist + } + + cfg := os.Getenv(k) + return cfg, cfg != "" +} + +func (c env) GetStringArr(k string, def ...[]string) ([]string, error) { + cfg, exist := c.get(k) + if !exist { + if len(def) == 0 { + return nil, ErrorVarNotExist + } + + return def[0], nil + } + + return parser.String(cfg).ToStringArr() +} + +func (c env) GetIntArr(k string, def ...[]int) ([]int, error) { + cfg, exist := c.get(k) + if !exist { + if len(def) == 0 { + return nil, ErrorVarNotExist + } + return def[0], nil + } + + is, e := parser.String(cfg).ToIntArr() + + if e != nil { + if len(def) == 0 { + return nil, e + } + + return def[0], nil + } + + return is, e +} + +func (c env) Dump() (string, error) { + if !c.useDotEnv { + return "", errors.New("cannot dump env, you are using system-wide env") + } + + j, e := json.Marshal(c.envs) + + return string(j), e +} + +func LoadEnv(envPath string, fallbackToWide ...bool) (Env, error) { + fBackToWide := false + if len(fallbackToWide) > 0 { + fBackToWide = fallbackToWide[0] + } + + envs, err := godotenv.Read(envPath) + if err != nil && !fBackToWide { + return nil, err + } + + if err == nil { + for key, val := range envs { + err = os.Setenv(key, val) + } + } + + return env{ + envs: envs, + useDotEnv: err == nil, + }, nil +} diff --git a/env_test.go b/env_test.go new file mode 100644 index 0000000..7165925 --- /dev/null +++ b/env_test.go @@ -0,0 +1,22 @@ +package env + +import ( + "github.com/stretchr/testify/assert" + "testing" +) + +func TestLoadEnv(t *testing.T) { + nv, err := LoadEnv(".env.test") + assert.Equal(t, err, nil, "Error must be nil") + + _, ok := nv.(Env) + assert.Equal(t, ok, true, "nv must be instance of Env") +} + +func TestLoadEnvFallbackToWide(t *testing.T) { + nv, err := LoadEnv("", true) + assert.Equal(t, err, nil, "Error must be nil") + + _, ok := nv.(Env) + assert.Equal(t, ok, true, "nv must be instance of Env") +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..58be91b --- /dev/null +++ b/go.mod @@ -0,0 +1,15 @@ +module github.com/alfarih31/nb-go-env + +go 1.17 + +require ( + github.com/alfarih31/nb-go-parser v1.0.3 + github.com/joho/godotenv v1.4.0 + github.com/stretchr/testify v1.7.0 +) + +require ( + github.com/davecgh/go-spew v1.1.0 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..bc73ae8 --- /dev/null +++ b/go.sum @@ -0,0 +1,15 @@ +github.com/alfarih31/nb-go-parser v1.0.3 h1:UeNLCb6aKnnbjwzZd6zhSrCit1lhBkBjRhCetekpPas= +github.com/alfarih31/nb-go-parser v1.0.3/go.mod h1:0+2qf5oT5sEy4qyNxY/ewsREpHtUYfis3/bERolDFGI= +github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/joho/godotenv v1.4.0 h1:3l4+N6zfMWnkbPEXKng2o2/MR5mSwTrBih4ZEkkz1lg= +github.com/joho/godotenv v1.4.0/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=