go_sysutils/internal/utils.go
2024-04-11 12:46:13 -04:00

102 lines
2.0 KiB
Go

package internal
import (
`runtime`
`strings`
)
// GetPathEnvName gets the OS-specific path environment variable name.
func GetPathEnvName() (envVarName string) {
var ok bool
if envVarName, ok = pathEnvVarName[runtime.GOOS]; !ok {
// *NIX/the default.
envVarName = "PATH"
}
return
}
/*
StringToMap takes string s, assumed to be in the form of
key=value[,key=value,key=value...]
and returns a map[string]string (map[key]value).
It is proccessed in order; later duplicate keys overwrite previous ones.
If s is an empty string or comprised only of whitespace, m will be nil.
If only a key is provided with no value, the value in the map will be an empty string.
(e.g. "foo,bar=baz" => map[string]string{"foo": "", "bar: "baz"}
Surrounding whitespace is trimmed.
*/
func StringToMap(s string) (m map[string]string) {
var kvSplit []string
var valSplit []string
var k string
var v string
if strings.TrimSpace(s) == "" {
return
}
kvSplit = strings.Split(s, ",")
if kvSplit == nil || len(kvSplit) == 0 {
return
}
for _, kv := range kvSplit {
valSplit = strings.SplitN(kv, "=", 2)
if valSplit == nil || len(valSplit) == 0 {
continue
}
k = valSplit[0]
switch len(valSplit) {
case 1:
v = ""
case 2:
v = valSplit[1]
// It's not possible to have more than 2.
}
if m == nil {
m = make(map[string]string)
}
k = strings.TrimSpace(k)
v = strings.TrimSpace(v)
m[k] = v
}
return
}
/*
StringToMapBool is like StringToMap but designed for a map of booleans.
It takes string s, assumed to be in the form of
option[,option,option...]
and returns a map[string]bool (map[option]true).
If s is an empty string or comprised only of whitespace, m will be nil.
Surrounding whitespace is trimmed.
*/
func StringToMapBool(s string) (m map[string]bool) {
var optSplit []string
if strings.TrimSpace(s) == "" {
return
}
optSplit = strings.Split(s, ",")
if optSplit == nil || len(optSplit) == 0 {
return
}
m = make(map[string]bool)
for _, o := range optSplit {
o = strings.TrimSpace(o)
m[o] = true
}
return
}