1
0
mirror of https://github.com/shirou/gopsutil.git synced 2025-04-24 13:48:56 +08:00

change to use a typed map per code review

This commit is contained in:
Antoine Toulme 2023-05-26 15:53:58 -07:00
parent 5b9212e240
commit 0cbdf257ab
3 changed files with 18 additions and 8 deletions

View File

@ -1,11 +1,19 @@
package common
type envKey string
type EnvKeyType string
// Env is a context key that can be used to set programmatically the environment
// EnvKey is a context key that can be used to set programmatically the environment
// gopsutil relies on to perform calls against the OS.
// Example of use:
//
// ctx := context.WithValue(context.Background(), Env, map[string]string{"HOST_PROC": "/myproc"})
// ctx := context.WithValue(context.Background(), common.EnvKey, EnvMap{"HOST_PROC": "/myproc"})
// avg, err := load.AvgWithContext(ctx)
var Env = envKey("env")
var EnvKey = EnvKeyType("env")
const (
HostProcEnvKey EnvKeyType = "HOST_PROC"
HostSysEnvKey EnvKeyType = "HOST_SYS"
HostEtcEnvKey EnvKeyType = "HOST_ETC"
)
type EnvMap map[EnvKeyType]string

View File

@ -324,11 +324,11 @@ func PathExistsWithContents(filename string) bool {
}
// GetEnvWithContext retrieves the environment variable key. If it does not exist it returns the default.
// The context may optionally contain a map superseding os.Env.
// The context may optionally contain a map superseding os.EnvKey.
func GetEnvWithContext(ctx context.Context, key string, dfault string, combineWith ...string) string {
var value string
if env, ok := ctx.Value(common.Env).(map[string]string); ok {
value = env[key]
if env, ok := ctx.Value(common.EnvKey).(common.EnvMap); ok {
value = env[common.EnvKeyType(key)]
}
if value == "" {
value = os.Getenv(key)

View File

@ -8,6 +8,8 @@ import (
"runtime"
"strings"
"testing"
"github.com/shirou/gopsutil/v3/common"
)
func TestReadlines(t *testing.T) {
@ -196,7 +198,7 @@ func TestGetEnvWithContextOverride(t *testing.T) {
defer func() {
os.Setenv("HOST_ETC", old)
}()
ctx := context.WithValue(context.Background(), Env, map[string]string{"HOST_ETC": "/foo"})
ctx := context.WithValue(context.Background(), common.EnvKey, common.EnvMap{common.HostEtcEnvKey: "/foo"})
p := HostEtcWithContext(ctx, "mtab")
if p != "/foo/mtab" {
t.Errorf("invalid HostEtc, %s", p)