-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathposix.go
81 lines (65 loc) · 1.82 KB
/
posix.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
79
80
81
package posix
import (
"os"
"syscall"
)
// Getter is the interface for mapping key to value lookups.
//
type Getter interface {
Get(key string) (value string, exists bool)
}
// Setter is the interface for mutable mappings to update a key.
type Setter interface {
Set(key string, value string) error
}
// Func implements the Getter interface for simple lookup functions.
type Func func(string) string
func (f Func) Get(s string) (string, bool) {
return f(s), true
}
// Map implements the Getter interface for map[string]string
type Map map[string]string
func (m Map) Get(k string) (string, bool) {
v, ok := m[k]
return v, ok
}
// RWMap implements the Getter and Setter interfaces for map[string]string.
type RWMap map[string]string
func (m RWMap) Get(k string) (string, bool) {
return Map(m).Get(k)
}
func (m RWMap) Set(k, v string) error {
m[k] = v
return nil
}
// Expand replaces ${var} or $var in the string based on the mapping.
// Supports most Posix shell exapansions:
//
// Default: ${param:-word} ${param-word}
//
// Assign default: ${param:=word} ${param=word}
//
// Error: ${param:?error} ${param?error}
//
// Alternative: ${param:+word} ${param+word}
//
// See: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
func Expand(s string, mapping Getter) (string, error) {
lexer := lex(s)
val, err := evalStream(mapping, lexer.stream)
lexer.Close()
return val, err
}
// ExpandEnv replaces ${var} or $var in the string according to the values of
// the current environment variables.
func ExpandEnv(s string) (string, error) {
return Expand(s, osEnviron)
}
type environGetSetter struct{}
func (e environGetSetter) Get(k string) (string, bool) {
return syscall.Getenv(k)
}
func (e environGetSetter) Set(k, v string) error {
return os.Setenv(k, v)
}
var osEnviron environGetSetter = environGetSetter{}