-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhypolashlckhelpers.go
78 lines (68 loc) · 1.72 KB
/
hypolashlckhelpers.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package hypolashlckhelpers
import (
"bytes"
"os"
"os/exec"
"strings"
"unicode"
)
func getEnv(enVar string, fallback string) string {
if value, ok := os.LookupEnv(enVar); ok {
if strings.Contains(value, "#CMDSTART#") {
return resolveCMD(os.ExpandEnv(value))
}
return os.ExpandEnv(value)
}
return os.ExpandEnv(fallback)
}
/*
* Run cmd embeded in environnement variable and run it
*/
func resolveCMD(cmdString string) string {
inputString := strings.TrimSpace(cmdString)
strCommand := getStringInBetween(inputString, "#CMDSTART#", "#CMDEND#")
stringToReplace := "#CMDSTART#" + strCommand + "#CMDEND#"
log.VarDebug(strCommand, "strCommand")
log.VarDebug(stringToReplace, "stringToReplace")
cmdArgs := strings.Split(strings.TrimSpace(strCommand), " ")
log.VarDebug(cmdArgs, "cmdArgs")
var cmd *exec.Cmd
if len(cmdArgs) == 1 {
cmd = exec.Command(cmdArgs[0])
} else {
cmd = exec.Command(cmdArgs[0], cmdArgs[1:]...)
}
var stdout bytes.Buffer
cmd.Stdout = &stdout
cmd.Env = os.Environ()
err := cmd.Run()
if err != nil {
log.Err.Fatalf("%s\n", err)
}
/*
* Remove all unwanted characters
*/
cmdResult := strings.TrimFunc(stdout.String(), func(r rune) bool {
return !unicode.IsGraphic(r)
})
log.VarDebug(cmdResult, "cmdResult")
detectedCMDValue := strings.Replace(inputString, stringToReplace, cmdResult, -1)
log.VarDebug(detectedCMDValue, "detectedCMDValue")
return detectedCMDValue
}
/*
* Extract command from environnement variables
*/
func getStringInBetween(str string, start string, end string) (result string) {
s := strings.Index(str, start)
if s == -1 {
return result
}
newS := str[s+len(start):]
e := strings.Index(newS, end)
if e == -1 {
return result
}
result = newS[:e]
return result
}