| 1 |
// Copyright (c) 2018, Daniel Martà <[email protected]> |
| 2 |
// See LICENSE for licensing information |
| 3 |
|
| 4 |
package expand |
| 5 |
|
| 6 |
import ( |
| 7 |
"cmp" |
| 8 |
"runtime" |
| 9 |
"slices" |
| 10 |
"strconv" |
| 11 |
"strings" |
| 12 |
) |
| 13 |
|
| 14 |
// Environ is the base interface for a shell's environment, allowing it to fetch |
| 15 |
// variables by name and to iterate over all the currently set variables. |
| 16 |
type Environ interface { |
| 17 |
// Get retrieves a variable by its name. To check if the variable is |
| 18 |
// set, use Variable.IsSet. |
| 19 |
Get(name string) Variable |
| 20 |
|
| 21 |
// TODO(v4): make Each below a func that returns an iterator. |
| 22 |
|
| 23 |
// Each iterates over all the currently set variables, calling the |
| 24 |
// supplied function on each variable. Iteration is stopped if the |
| 25 |
// function returns false. |
| 26 |
// |
| 27 |
// The names used in the calls aren't required to be unique or sorted. |
| 28 |
// If a variable name appears twice, the latest occurrence takes |
| 29 |
// priority. |
| 30 |
// |
| 31 |
// Each is required to forward exported variables when executing |
| 32 |
// programs. |
| 33 |
Each(func(name string, vr Variable) bool) |
| 34 |
} |
| 35 |
|
| 36 |
// TODO(v4): [WriteEnviron.Set] below is overloaded to the point that correctly |
| 37 |
// implementing both sides of the interface is tricky. In particular, some operations |
| 38 |
// such as `export foo` or `readonly foo` alter the attributes but not the value, |
| 39 |
// and `foo=bar` or `foo=[3]=baz` alter the value but not the attributes. |
| 40 |
|
| 41 |
// WriteEnviron is an extension on Environ that supports modifying and deleting |
| 42 |
// variables. |
| 43 |
type WriteEnviron interface { |
| 44 |
Environ |
| 45 |
// Set sets a variable by name. If !vr.IsSet(), the variable is being |
| 46 |
// unset; otherwise, the variable is being replaced. |
| 47 |
// |
| 48 |
// The given variable can have the kind [KeepValue] to replace an existing |
| 49 |
// variable's attributes without changing its value at all. |
| 50 |
// This is helpful to implement `readonly foo=bar; export foo`, |
| 51 |
// as the second declaration needs to clearly signal that the value is not modified. |
| 52 |
// |
| 53 |
// An error may be returned if the operation is invalid, such as if the |
| 54 |
// name is empty or if we're trying to overwrite a read-only variable. |
| 55 |
Set(name string, vr Variable) error |
| 56 |
} |
| 57 |
|
| 58 |
//go:generate go tool stringer -type=ValueKind |
| 59 |
|
| 60 |
// ValueKind describes which kind of value the variable holds. |
| 61 |
// While most unset variables will have an [Unknown] kind, an unset variable may |
| 62 |
// have a kind associated too, such as via `declare -a foo` resulting in [Indexed]. |
| 63 |
type ValueKind uint8 |
| 64 |
|
| 65 |
const ( |
| 66 |
// Unknown is used for unset variables which do not have a kind yet. |
| 67 |
Unknown ValueKind = iota |
| 68 |
// String describes plain string variables, such as `foo=bar`. |
| 69 |
String |
| 70 |
// NameRef describes variables which reference another by name, such as `declare -n foo=foo2`. |
| 71 |
NameRef |
| 72 |
// Indexed describes indexed array variables, such as `foo=(bar baz)`. |
| 73 |
Indexed |
| 74 |
// Associative describes associative array variables, such as `foo=([bar]=x [baz]=y)`. |
| 75 |
Associative |
| 76 |
|
| 77 |
// KeepValue is used by [WriteEnviron.Set] to signal that we are changing attributes |
| 78 |
// about a variable, such as exporting it, without changing its value at all. |
| 79 |
KeepValue |
| 80 |
|
| 81 |
// Deprecated: use [Unknown], as tracking whether or not a variable is set |
| 82 |
// is now done via [Variable.Set]. |
| 83 |
// Otherwise it was impossible to describe an unset variable with a known kind |
| 84 |
// such as `declare -A foo`. |
| 85 |
Unset = Unknown |
| 86 |
) |
| 87 |
|
| 88 |
// Variable describes a shell variable, which can have a number of attributes |
| 89 |
// and a value. |
| 90 |
type Variable struct { |
| 91 |
// Set is true when the variable has been set to a value, |
| 92 |
// which may be empty. |
| 93 |
Set bool |
| 94 |
|
| 95 |
Local bool |
| 96 |
Exported bool |
| 97 |
ReadOnly bool |
| 98 |
|
| 99 |
// Kind defines which of the value fields below should be used. |
| 100 |
Kind ValueKind |
| 101 |
|
| 102 |
Str string // Used when Kind is String or NameRef. |
| 103 |
List []string // Used when Kind is Indexed. |
| 104 |
Map map[string]string // Used when Kind is Associative. |
| 105 |
|
| 106 |
// Indexes records the index of each [Variable.List] element when an |
| 107 |
// indexed array is sparse, such as `a=([2]=x [5]=y)`. The indices |
| 108 |
// must be unique, non-negative, sorted, and as many as the List |
| 109 |
// elements. Nil means the array is dense: element i has index i. |
| 110 |
Indexes []int |
| 111 |
} |
| 112 |
|
| 113 |
// IsSet reports whether the variable has been set to a value. |
| 114 |
// The zero value of a Variable is unset. |
| 115 |
func (v Variable) IsSet() bool { |
| 116 |
return v.Set |
| 117 |
} |
| 118 |
|
| 119 |
// Declared reports whether the variable has been declared. |
| 120 |
// Declared variables may not be set; `export foo` is exported but not set to a value, |
| 121 |
// and `declare -a foo` is an indexed array but not set to a value. |
| 122 |
func (v Variable) Declared() bool { |
| 123 |
return v.Set || v.Local || v.Exported || v.ReadOnly || v.Kind != Unknown |
| 124 |
} |
| 125 |
|
| 126 |
// Flags returns the variable's attribute flags in the order used by bash's |
| 127 |
// declare builtin and ${var@a}: type (a/A/n), readonly (r), exported (x). |
| 128 |
func (v Variable) Flags() string { |
| 129 |
var flags []byte |
| 130 |
switch v.Kind { |
| 131 |
case Indexed: |
| 132 |
flags = append(flags, 'a') |
| 133 |
case Associative: |
| 134 |
flags = append(flags, 'A') |
| 135 |
case NameRef: |
| 136 |
flags = append(flags, 'n') |
| 137 |
} |
| 138 |
if v.ReadOnly { |
| 139 |
flags = append(flags, 'r') |
| 140 |
} |
| 141 |
if v.Exported { |
| 142 |
flags = append(flags, 'x') |
| 143 |
} |
| 144 |
return string(flags) |
| 145 |
} |
| 146 |
|
| 147 |
// String returns the variable's value as a string. In general, this only makes |
| 148 |
// sense if the variable has a string value or no value at all. |
| 149 |
func (v Variable) String() string { |
| 150 |
switch v.Kind { |
| 151 |
case String: |
| 152 |
return v.Str |
| 153 |
case Indexed: |
| 154 |
if str, ok := v.indexedVal(0); ok { |
| 155 |
return str |
| 156 |
} |
| 157 |
case Associative: |
| 158 |
// nothing to do |
| 159 |
} |
| 160 |
return "" |
| 161 |
} |
| 162 |
|
| 163 |
// indexedVal returns the element of an indexed array at index i, |
| 164 |
// taking [Variable.Indexes] into account for sparse arrays. |
| 165 |
func (v Variable) indexedVal(i int) (string, bool) { |
| 166 |
if v.Indexes != nil { |
| 167 |
if pos, ok := slices.BinarySearch(v.Indexes, i); ok { |
| 168 |
return v.List[pos], true |
| 169 |
} |
| 170 |
return "", false |
| 171 |
} |
| 172 |
if i < len(v.List) { |
| 173 |
return v.List[i], true |
| 174 |
} |
| 175 |
return "", false |
| 176 |
} |
| 177 |
|
| 178 |
// indexedKeys returns the index of each element of an indexed array as a |
| 179 |
// string, for the sake of expansions like "${!a[@]}". |
| 180 |
func (v Variable) indexedKeys() []string { |
| 181 |
keys := make([]string, len(v.List)) |
| 182 |
for i := range v.List { |
| 183 |
if v.Indexes != nil { |
| 184 |
keys[i] = strconv.Itoa(v.Indexes[i]) |
| 185 |
} else { |
| 186 |
keys[i] = strconv.Itoa(i) |
| 187 |
} |
| 188 |
} |
| 189 |
return keys |
| 190 |
} |
| 191 |
|
| 192 |
// maxNameRefDepth defines the maximum number of times to follow references when |
| 193 |
// resolving a variable. Otherwise, simple name reference loops could crash a |
| 194 |
// program quite easily. |
| 195 |
const maxNameRefDepth = 100 |
| 196 |
|
| 197 |
// Resolve follows a number of nameref variables, returning the last reference |
| 198 |
// name that was followed and the variable that it points to. |
| 199 |
func (v Variable) Resolve(env Environ) (string, Variable) { |
| 200 |
name := "" |
| 201 |
for range maxNameRefDepth { |
| 202 |
if v.Kind != NameRef { |
| 203 |
return name, v |
| 204 |
} |
| 205 |
name = v.Str // keep name for the next iteration |
| 206 |
v = env.Get(name) |
| 207 |
} |
| 208 |
return name, Variable{} |
| 209 |
} |
| 210 |
|
| 211 |
// FuncEnviron wraps a function mapping variable names to their string values, |
| 212 |
// and implements [Environ]. Empty strings returned by the function will be |
| 213 |
// treated as unset variables. All variables will be exported. |
| 214 |
// |
| 215 |
// Note that the returned Environ's Each method will be a no-op. |
| 216 |
func FuncEnviron(fn func(string) string) Environ { |
| 217 |
return funcEnviron(fn) |
| 218 |
} |
| 219 |
|
| 220 |
type funcEnviron func(string) string |
| 221 |
|
| 222 |
func (f funcEnviron) Get(name string) Variable { |
| 223 |
value := f(name) |
| 224 |
if value == "" { |
| 225 |
return Variable{} |
| 226 |
} |
| 227 |
return Variable{Set: true, Exported: true, Kind: String, Str: value} |
| 228 |
} |
| 229 |
|
| 230 |
func (f funcEnviron) Each(func(name string, vr Variable) bool) {} |
| 231 |
|
| 232 |
// ListEnviron returns an [Environ] with the supplied variables, in the form |
| 233 |
// "key=value". All variables will be exported. The last value in pairs is used |
| 234 |
// if multiple values are present. |
| 235 |
// |
| 236 |
// On Windows, where environment variable names are case-insensitive, the |
| 237 |
// resulting variable names will all be uppercase. |
| 238 |
func ListEnviron(pairs ...string) Environ { |
| 239 |
return listEnviron_(runtime.GOOS == "windows", pairs...) |
| 240 |
} |
| 241 |
|
| 242 |
// listEnviron_ implements [ListEnviron], but letting the tests specify |
| 243 |
// whether to uppercase all names or not. |
| 244 |
func listEnviron_(caseInsensitive bool, pairs ...string) Environ { |
| 245 |
list := slices.Clone(pairs) |
| 246 |
env := listEnviron{caseInsensitive: caseInsensitive} |
| 247 |
slices.SortStableFunc(list, func(a, b string) int { |
| 248 |
isep := strings.IndexByte(a, '=') |
| 249 |
jsep := strings.IndexByte(b, '=') |
| 250 |
if isep < 0 { |
| 251 |
isep = 0 |
| 252 |
} else { |
| 253 |
isep += 1 |
| 254 |
} |
| 255 |
if jsep < 0 { |
| 256 |
jsep = 0 |
| 257 |
} else { |
| 258 |
jsep += 1 |
| 259 |
} |
| 260 |
return env.compare(a[:isep], b[:jsep]) |
| 261 |
}) |
| 262 |
|
| 263 |
last := "" |
| 264 |
for i := 0; i < len(list); { |
| 265 |
name, _, ok := strings.Cut(list[i], "=") |
| 266 |
if name == "" || !ok { |
| 267 |
// invalid element; remove it |
| 268 |
list = slices.Delete(list, i, i+1) |
| 269 |
continue |
| 270 |
} |
| 271 |
if env.compare(last, name) == 0 { |
| 272 |
// duplicate; the last one wins |
| 273 |
list = slices.Delete(list, i-1, i) |
| 274 |
continue |
| 275 |
} |
| 276 |
last = name |
| 277 |
i++ |
| 278 |
} |
| 279 |
env.pairs = list |
| 280 |
return env |
| 281 |
} |
| 282 |
|
| 283 |
// listEnviron is a sorted list of "name=value" strings. |
| 284 |
type listEnviron struct { |
| 285 |
caseInsensitive bool |
| 286 |
pairs []string |
| 287 |
} |
| 288 |
|
| 289 |
func (l listEnviron) compare(a, b string) int { |
| 290 |
if l.caseInsensitive { |
| 291 |
// This is not particularly efficient, but it does the job. |
| 292 |
// If we had a cmp-compatible version of [strings.EqualFold], we'd use it. |
| 293 |
a = strings.ToUpper(a) |
| 294 |
b = strings.ToUpper(b) |
| 295 |
} |
| 296 |
return strings.Compare(a, b) |
| 297 |
} |
| 298 |
|
| 299 |
func (l listEnviron) Get(name string) Variable { |
| 300 |
eqpos := len(name) |
| 301 |
endpos := len(name) + 1 |
| 302 |
i, ok := slices.BinarySearchFunc(l.pairs, name, func(pair, name string) int { |
| 303 |
if len(pair) < endpos { |
| 304 |
// Too short; see if we are before or after the name. |
| 305 |
return l.compare(pair, name) |
| 306 |
} |
| 307 |
// Compare the name prefix, then the equal character. |
| 308 |
c := l.compare(pair[:eqpos], name) |
| 309 |
eq := pair[eqpos] |
| 310 |
if c == 0 { |
| 311 |
return cmp.Compare(eq, '=') |
| 312 |
} |
| 313 |
return c |
| 314 |
}) |
| 315 |
if ok { |
| 316 |
return Variable{Set: true, Exported: true, Kind: String, Str: l.pairs[i][endpos:]} |
| 317 |
} |
| 318 |
return Variable{} |
| 319 |
} |
| 320 |
|
| 321 |
func (l listEnviron) Each(fn func(name string, vr Variable) bool) { |
| 322 |
for _, pair := range l.pairs { |
| 323 |
name, value, ok := strings.Cut(pair, "=") |
| 324 |
if !ok { |
| 325 |
// should never happen; see listEnvironWithUpper |
| 326 |
panic("expand.listEnviron: did not expect malformed name-value pair: " + pair) |
| 327 |
} |
| 328 |
if !fn(name, Variable{Set: true, Exported: true, Kind: String, Str: value}) { |
| 329 |
return |
| 330 |
} |
| 331 |
} |
| 332 |
} |