Skip to content

Commit

Permalink
✨ feat: env,sys - add new func for get all env info map
Browse files Browse the repository at this point in the history
  • Loading branch information
inhere committed Jan 28, 2023
1 parent c4447cb commit b3d7669
Show file tree
Hide file tree
Showing 5 changed files with 37 additions and 4 deletions.
26 changes: 26 additions & 0 deletions envutil/get.go
Expand Up @@ -2,6 +2,7 @@ package envutil

import (
"os"
"path/filepath"

"github.com/gookit/goutil/internal/comfunc"
"github.com/gookit/goutil/strutil"
Expand Down Expand Up @@ -40,7 +41,32 @@ func GetBool(name string, def ...bool) bool {
return false
}

// EnvPaths get and split $PATH to []string
func EnvPaths() []string {
return filepath.SplitList(os.Getenv("PATH"))
}

// Environ like os.Environ, but will returns key-value map[string]string data.
func Environ() map[string]string {
return comfunc.Environ()
}

// SearchEnvKeys values by given keywords
func SearchEnvKeys(keywords string) map[string]string {
return SearchEnv(keywords, false)
}

// SearchEnv values by given keywords
func SearchEnv(keywords string, matchValue bool) map[string]string {
founded := make(map[string]string)

for name, val := range comfunc.Environ() {
if strutil.IContains(name, keywords) {
founded[name] = val
} else if matchValue && strutil.IContains(val, keywords) {
founded[name] = val
}
}

return founded
}
2 changes: 2 additions & 0 deletions envutil/get_test.go
Expand Up @@ -42,6 +42,8 @@ func TestGetBool(t *testing.T) {
}

func TestEnviron(t *testing.T) {
assert.NotEmpty(t, EnvPaths())

testutil.MockOsEnv(map[string]string{
TestEnvName: TestEnvValue,
}, func() {
Expand Down
5 changes: 5 additions & 0 deletions sysutil/sysenv.go
Expand Up @@ -118,6 +118,11 @@ func HasExecutable(binName string) bool {
return err == nil
}

// Environ like os.Environ, but will returns key-value map[string]string data.
func Environ() map[string]string {
return comfunc.Environ()
}

// EnvPaths get and split $PATH to []string
func EnvPaths() []string {
return filepath.SplitList(os.Getenv("PATH"))
Expand Down
2 changes: 2 additions & 0 deletions sysutil/sysenv_test.go
Expand Up @@ -14,6 +14,8 @@ func TestSysenv_common(t *testing.T) {
ss := sysutil.EnvPaths()
assert.NotEmpty(t, ss)

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

ss = sysutil.SearchPath("go")
assert.NotEmpty(t, ss)
// dump.P(ss)
Expand Down
6 changes: 2 additions & 4 deletions sysutil/user.go
Expand Up @@ -46,11 +46,9 @@ var homeDir string

// UserHomeDir is alias of os.UserHomeDir, but ignore error
func UserHomeDir() string {
if homeDir != "" {
return homeDir
if homeDir == "" {
homeDir, _ = os.UserHomeDir()
}

homeDir, _ = os.UserHomeDir()
return homeDir
}

Expand Down

0 comments on commit b3d7669

Please sign in to comment.