...
Source file
src/os/env.go
Documentation: os
1
2
3
4
5
6
7 package os
8
9 import (
10 "internal/testlog"
11 "syscall"
12 )
13
14
15
16 func Expand(s string, mapping func(string) string) string {
17 buf := make([]byte, 0, 2*len(s))
18
19 i := 0
20 for j := 0; j < len(s); j++ {
21 if s[j] == '$' && j+1 < len(s) {
22 buf = append(buf, s[i:j]...)
23 name, w := getShellName(s[j+1:])
24 buf = append(buf, mapping(name)...)
25 j += w
26 i = j + 1
27 }
28 }
29 return string(buf) + s[i:]
30 }
31
32
33
34
35 func ExpandEnv(s string) string {
36 return Expand(s, Getenv)
37 }
38
39
40
41 func isShellSpecialVar(c uint8) bool {
42 switch c {
43 case '*', '#', '$', '@', '!', '?', '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
44 return true
45 }
46 return false
47 }
48
49
50 func isAlphaNum(c uint8) bool {
51 return c == '_' || '0' <= c && c <= '9' || 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z'
52 }
53
54
55
56
57 func getShellName(s string) (string, int) {
58 switch {
59 case s[0] == '{':
60 if len(s) > 2 && isShellSpecialVar(s[1]) && s[2] == '}' {
61 return s[1:2], 3
62 }
63
64 for i := 1; i < len(s); i++ {
65 if s[i] == '}' {
66 return s[1:i], i + 1
67 }
68 }
69 return "", 1
70 case isShellSpecialVar(s[0]):
71 return s[0:1], 1
72 }
73
74 var i int
75 for i = 0; i < len(s) && isAlphaNum(s[i]); i++ {
76 }
77 return s[:i], i
78 }
79
80
81
82
83 func Getenv(key string) string {
84 testlog.Getenv(key)
85 v, _ := syscall.Getenv(key)
86 return v
87 }
88
89
90
91
92
93
94 func LookupEnv(key string) (string, bool) {
95 testlog.Getenv(key)
96 return syscall.Getenv(key)
97 }
98
99
100
101 func Setenv(key, value string) error {
102 err := syscall.Setenv(key, value)
103 if err != nil {
104 return NewSyscallError("setenv", err)
105 }
106 return nil
107 }
108
109
110 func Unsetenv(key string) error {
111 return syscall.Unsetenv(key)
112 }
113
114
115 func Clearenv() {
116 syscall.Clearenv()
117 }
118
119
120
121 func Environ() []string {
122 return syscall.Environ()
123 }
124
View as plain text