1
2
3
4
5
6
7 package os
8
9 func setenv_c(k, v string)
10
11
12
13 func Expand(s string, mapping func(string) string) string {
14 buf := make([]byte, 0, 2*len(s))
15
16 i := 0
17 for j := 0; j < len(s); j++ {
18 if s[j] == '$' && j+1 < len(s) {
19 buf = append(buf, []byte(s[i:j])...)
20 name, w := getShellName(s[j+1:])
21 buf = append(buf, []byte(mapping(name))...)
22 j += w
23 i = j + 1
24 }
25 }
26 return string(buf) + s[i:]
27 }
28
29
30
31
32 func ShellExpand(s string) string {
33 return Expand(s, Getenv)
34 }
35
36
37
38 func isShellSpecialVar(c uint8) bool {
39 switch c {
40 case '*', '#', '$', '@', '!', '?', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
41 return true
42 }
43 return false
44 }
45
46
47 func isAlphaNum(c uint8) bool {
48 return c == '_' || '0' <= c && c <= '9' || 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z'
49 }
50
51
52
53
54 func getShellName(s string) (string, int) {
55 switch {
56 case s[0] == '{':
57 if len(s) > 2 && isShellSpecialVar(s[1]) && s[2] == '}' {
58 return s[1:2], 3
59 }
60
61 for i := 1; i < len(s); i++ {
62 if s[i] == '}' {
63 return s[1:i], i + 1
64 }
65 }
66 return "", 1
67 case isShellSpecialVar(s[0]):
68 return s[0:1], 1
69 }
70
71 var i int
72 for i = 0; i < len(s) && isAlphaNum(s[i]); i++ {
73 }
74 return s[:i], i
75 }