-
Notifications
You must be signed in to change notification settings - Fork 165
/
when.go
48 lines (44 loc) · 829 Bytes
/
when.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
package cmdutil
import (
"fmt"
"os"
"strings"
"github.com/antonmedv/expr"
)
func IsAllowedToExecute(when string) (bool, error) {
if when == "" {
return true, nil
}
ropts := []string{}
em := envMap()
for k := range em {
ropts = append(ropts, fmt.Sprintf("$%s", k), fmt.Sprintf("Env.%s", k))
}
r := strings.NewReplacer(ropts...)
when = r.Replace(when)
got, err := expr.Eval(fmt.Sprintf("(%s) == true", when), struct {
Env map[string]string
}{
Env: em,
})
if err != nil {
return false, err
}
return got.(bool), nil
}
func envMap() map[string]string {
m := map[string]string{}
for _, kv := range os.Environ() {
if !strings.Contains(kv, "=") {
continue
}
parts := strings.SplitN(kv, "=", 2)
k := parts[0]
if len(parts) < 2 {
m[k] = ""
continue
}
m[k] = parts[1]
}
return m
}