diff --git a/envutil/envutil.go b/envutil/envutil.go index fc1d07592..f9a312da2 100644 --- a/envutil/envutil.go +++ b/envutil/envutil.go @@ -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) + } +} diff --git a/envutil/get.go b/envutil/get.go index d5dd86ea3..8265579ab 100644 --- a/envutil/get.go +++ b/envutil/get.go @@ -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")) diff --git a/envutil/get_test.go b/envutil/get_test.go index 85e706f2a..e0fe9a397 100644 --- a/envutil/get_test.go +++ b/envutil/get_test.go @@ -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) }) } diff --git a/sysutil/sysenv.go b/sysutil/sysenv.go index 41586335b..2bd68bce4 100644 --- a/sysutil/sysenv.go +++ b/sysutil/sysenv.go @@ -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 + "*" @@ -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 + } } } diff --git a/sysutil/sysenv_test.go b/sysutil/sysenv_test.go index 55140be02..35c25beaf 100644 --- a/sysutil/sysenv_test.go +++ b/sysutil/sysenv_test.go @@ -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) }