feature: added process_environment.go
parent
a26b61975d
commit
194898b8a0
|
@ -0,0 +1,82 @@
|
|||
package process_environment
|
||||
|
||||
import (
|
||||
"log"
|
||||
"os"
|
||||
"os/exec"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"git.tswf.io/incredible-go/incredible-go-core/pkg/collections/array_list"
|
||||
)
|
||||
|
||||
var PathEnvironmentVariableName = "PATH"
|
||||
|
||||
func AppendPath(cmd *exec.Cmd, newElements ...string) {
|
||||
pathEntries := GetPath(cmd)
|
||||
for _, newPathEntry := range newElements {
|
||||
if !pathEntries.Contains(newPathEntry) {
|
||||
pathEntries.Add(newPathEntry)
|
||||
}
|
||||
}
|
||||
|
||||
SetPath(cmd, pathEntries.ToSliceUnsafe()...)
|
||||
}
|
||||
|
||||
func SetPath(cmd *exec.Cmd, entries ...string) {
|
||||
pathEntries := GetPath(cmd)
|
||||
for _, entry := range entries {
|
||||
if !pathEntries.Contains(entry) {
|
||||
pathEntries.Add(entry)
|
||||
}
|
||||
}
|
||||
|
||||
newPathEnvValue := strings.Join(pathEntries.ToSliceUnsafe(), string(os.PathListSeparator))
|
||||
SetEnvironmentVariable(cmd, PathEnvironmentVariableName, newPathEnvValue)
|
||||
}
|
||||
|
||||
func GetPath(cmd *exec.Cmd) *array_list.ArrayList[string] {
|
||||
oldPathEnvValue := GetEnvironmentVariable(cmd, PathEnvironmentVariableName)
|
||||
pathListSeparatorString := string(os.PathListSeparator)
|
||||
|
||||
oldPathEnvEntries := array_list.NewArrayListWithContent(strings.Split(oldPathEnvValue, pathListSeparatorString)...)
|
||||
|
||||
oldPathEnvEntries.RemoveIf(func(s string) bool {
|
||||
return s == ""
|
||||
})
|
||||
|
||||
return oldPathEnvEntries
|
||||
}
|
||||
|
||||
func SetEnvironmentVariable(cmd *exec.Cmd, envName string, envValue string) *exec.Cmd {
|
||||
envPrefix := getEnvironmentVariablePrefix(envName)
|
||||
cmd.Env = slices.DeleteFunc(cmd.Env, func(s string) bool {
|
||||
return strings.HasPrefix(strings.ToLower(s), envPrefix)
|
||||
})
|
||||
|
||||
cmd.Env = append(cmd.Env, envPrefix+envValue)
|
||||
|
||||
return cmd
|
||||
}
|
||||
|
||||
func GetEnvironmentVariable(cmd *exec.Cmd, envName string) string {
|
||||
envPrefix := getEnvironmentVariablePrefix(envName)
|
||||
for _, env := range cmd.Env {
|
||||
if strings.HasPrefix(strings.ToLower(env), envPrefix) {
|
||||
split := strings.SplitN(env, "=", 2)
|
||||
if len(split) < 2 {
|
||||
log.Printf("%v is not valid split for env '%s'", cmd.Env, env)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
func IsEnvironmentVariablePresent(cmd *exec.Cmd, envName string) bool {
|
||||
return GetEnvironmentVariable(cmd, envName) != ""
|
||||
}
|
||||
|
||||
func getEnvironmentVariablePrefix(envName string) string {
|
||||
return strings.ToLower(envName + "=")
|
||||
}
|
Loading…
Reference in New Issue