Skip to content

Commit

Permalink
✨ up(env,sys): update some func and add new util func
Browse files Browse the repository at this point in the history
  • Loading branch information
inhere committed Feb 5, 2023
1 parent 676fe4e commit 9eaddb5
Show file tree
Hide file tree
Showing 5 changed files with 41 additions and 4 deletions.
22 changes: 20 additions & 2 deletions envutil/envutil.go
Expand Up @@ -42,9 +42,27 @@ func ParseValue(val string) (newVal string) {
return comfunc.ParseEnvVar(val, ValueGetter)
}

// SetEnvs to os
func SetEnvs(mp map[string]string) {
// SetEnvMap set multi ENV(string-map) to os
func SetEnvMap(mp map[string]string) {
for key, value := range mp {
_ = os.Setenv(key, value)
}
}

// SetEnvs set multi k-v ENV pairs to os
func SetEnvs(kvPairs ...string) {
if len(kvPairs)%2 == 1 {
panic("envutil.SetEnvs: odd argument count")
}

for i := 0; i < len(kvPairs); i += 2 {
_ = os.Setenv(kvPairs[i], kvPairs[i+1])
}
}

// UnsetEnvs from os
func UnsetEnvs(keys ...string) {
for _, key := range keys {
_ = os.Unsetenv(key)
}
}
12 changes: 12 additions & 0 deletions envutil/get.go
Expand Up @@ -41,6 +41,18 @@ func GetBool(name string, def ...bool) bool {
return false
}

// GetMulti ENV values by input names.
func GetMulti(names ...string) map[string]string {
valMap := make(map[string]string, len(names))

for _, name := range names {
if val := os.Getenv(name); val != "" {
valMap[name] = val
}
}
return valMap
}

// EnvPaths get and split $PATH to []string
func EnvPaths() []string {
return filepath.SplitList(os.Getenv("PATH"))
Expand Down
2 changes: 2 additions & 0 deletions envutil/get_test.go
Expand Up @@ -28,6 +28,8 @@ func TestGetenv(t *testing.T) {
assert.Eq(t, 1, GetInt(TestEnvName), "int env value not equals")
assert.Eq(t, 0, GetInt(TestNoEnvName))
assert.Eq(t, 2, GetInt(TestNoEnvName, 2))

assert.Len(t, GetMulti(TestEnvName, TestNoEnvName), 1)
})
}

Expand Down
7 changes: 6 additions & 1 deletion sysutil/sysenv.go
Expand Up @@ -133,7 +133,7 @@ func EnvPaths() []string {
// Usage:
//
// sysutil.SearchPath("go")
func SearchPath(keywords string) []string {
func SearchPath(keywords string, limit int) []string {
path := os.Getenv("PATH")
ptn := "*" + keywords + "*"

Expand All @@ -147,6 +147,11 @@ func SearchPath(keywords string) []string {
matches, err := filepath.Glob(filepath.Join(dir, ptn))
if err == nil && len(matches) > 0 {
list = append(list, matches...)

// limit result
if limit > 0 && len(list) > limit {
break
}
}
}

Expand Down
2 changes: 1 addition & 1 deletion sysutil/sysenv_test.go
Expand Up @@ -16,7 +16,7 @@ func TestSysenv_common(t *testing.T) {

assert.NotEmpty(t, sysutil.Environ())

ss = sysutil.SearchPath("go")
ss = sysutil.SearchPath("go", 3)
assert.NotEmpty(t, ss)
// dump.P(ss)
}
Expand Down

0 comments on commit 9eaddb5

Please sign in to comment.