Debian Codegraph @

expand/expand.go

raw
1 // Copyright (c) 2017, Daniel Martí <[email protected]>
2 // See LICENSE for licensing information
3
4 package expand
5
6 import (
7 "cmp"
8 "errors"
9 "fmt"
10 "io"
11 "io/fs"
12 "iter"
13 "maps"
14 "os"
15 "os/user"
16 "path/filepath"
17 "regexp"
18 "runtime"
19 "slices"
20 "strconv"
21 "strings"
22 "syscall"
23 "unicode/utf8"
24
25 "mvdan.cc/sh/v3/internal"
26 "mvdan.cc/sh/v3/pattern"
27 "mvdan.cc/sh/v3/syntax"
28 )
29
30 // A Config specifies details about how shell expansion should be performed. The
31 // zero value is a valid configuration.
32 type Config struct {
33 // Env is used to get and set environment variables when performing
34 // shell expansions. Some special parameters are also expanded via this
35 // interface, such as:
36 //
37 // * "#", "@", "*", "0"-"9" for the shell's parameters
38 // * "?", "$", "PPID" for the shell's status and process
39 // * "HOME foo" to retrieve user foo's home directory (if unset,
40 // os/user.Lookup will be used)
41 //
42 // If nil, there are no environment variables set. Use
43 // ListEnviron(os.Environ()...) to use the system's environment
44 // variables.
45 Env Environ
46
47 // CmdSubst expands a command substitution node, writing its standard
48 // output to the provided [io.Writer].
49 //
50 // If nil, encountering a command substitution will result in an
51 // UnexpectedCommandError.
52 CmdSubst func(io.Writer, *syntax.CmdSubst) error
53
54 // ProcSubst expands a process substitution node.
55 ProcSubst func(*syntax.ProcSubst) (string, error)
56
57 // TODO(v4): replace ReadDir with ReadDir2.
58
59 // ReadDir is the older form of [ReadDir2], before io/fs.
60 //
61 // Deprecated: use ReadDir2 instead.
62 ReadDir func(string) ([]fs.FileInfo, error)
63
64 // ReadDir2 is used for file path globbing.
65 // If nil, and [ReadDir] is nil as well, globbing is disabled.
66 // Use [os.ReadDir] to use the filesystem directly.
67 ReadDir2 func(string) ([]fs.DirEntry, error)
68
69 // GlobStar corresponds to the shell option which allows globbing with "**".
70 GlobStar bool
71
72 // DotGlob corresponds to the shell option which allows filenames beginning
73 // with a dot to be matched by a pattern which does not begin with a dot.
74 DotGlob bool
75
76 // NoCaseGlob corresponds to the shell option which causes case-insensitive
77 // pattern matching in pathname expansion.
78 NoCaseGlob bool
79
80 // NullGlob corresponds to the shell option which allows globbing
81 // patterns which match nothing to result in zero fields.
82 NullGlob bool
83
84 // NoUnset corresponds to the shell option which treats unset variables
85 // as errors.
86 NoUnset bool
87
88 // ExtGlob corresponds to the shell option which allows using extended
89 // pattern matching features when performing pathname expansion (globbing).
90 ExtGlob bool
91
92 bufferAlloc strings.Builder
93 fieldAlloc [4]fieldPart
94 fieldsAlloc [4][]fieldPart
95
96 ifs string
97 // A pointer to a parameter expansion node, if we're inside one.
98 // Necessary for ${LINENO}.
99 curParam *syntax.ParamExp
100 }
101
102 // UnexpectedCommandError is returned if a command substitution is encountered
103 // when [Config.CmdSubst] is nil.
104 type UnexpectedCommandError struct {
105 Node *syntax.CmdSubst
106 }
107
108 func (u UnexpectedCommandError) Error() string {
109 return fmt.Sprintf("unexpected command substitution at %s", u.Node.Pos())
110 }
111
112 var zeroConfig = &Config{}
113
114 // TODO: note that prepareConfig is modifying the user's config in place,
115 // which doesn't feel right - we should make a copy.
116
117 func prepareConfig(cfg *Config) *Config {
118 cfg = cmp.Or(cfg, zeroConfig)
119 cfg.Env = cmp.Or(cfg.Env, FuncEnviron(func(string) string { return "" }))
120
121 cfg.ifs = " \t\n"
122 if vr := cfg.Env.Get("IFS"); vr.IsSet() {
123 cfg.ifs = vr.String()
124 }
125
126 if cfg.ReadDir != nil && cfg.ReadDir2 == nil {
127 cfg.ReadDir2 = func(path string) ([]fs.DirEntry, error) {
128 infos, err := cfg.ReadDir(path)
129 if err != nil {
130 return nil, err
131 }
132 entries := make([]fs.DirEntry, len(infos))
133 for i, info := range infos {
134 entries[i] = fs.FileInfoToDirEntry(info)
135 }
136 return entries, nil
137 }
138 }
139 return cfg
140 }
141
142 func (cfg *Config) ifsRune(r rune) bool {
143 return strings.ContainsRune(cfg.ifs, r)
144 }
145
146 // ifsWhitespace reports whether r is a space, tab, or newline present in IFS.
147 func (cfg *Config) ifsWhitespace(r rune) bool {
148 return (r == ' ' || r == '\t' || r == '\n') && cfg.ifsRune(r)
149 }
150
151 func (cfg *Config) ifsJoin(strs []string) string {
152 sep := ""
153 if cfg.ifs != "" {
154 // The separator is the first character of IFS, not the first byte.
155 _, size := utf8.DecodeRuneInString(cfg.ifs)
156 sep = cfg.ifs[:size]
157 }
158 return strings.Join(strs, sep)
159 }
160
161 func (cfg *Config) strBuilder() *strings.Builder {
162 b := &cfg.bufferAlloc
163 b.Reset()
164 return b
165 }
166
167 func (cfg *Config) envGet(name string) string {
168 return cfg.Env.Get(name).String()
169 }
170
171 func (cfg *Config) envSet(name, value string) error {
172 wenv, ok := cfg.Env.(WriteEnviron)
173 if !ok {
174 return fmt.Errorf("environment is read-only")
175 }
176 return wenv.Set(name, Variable{Set: true, Kind: String, Str: value})
177 }
178
179 // Literal expands a single shell word. It is similar to [Fields], but the result
180 // is a single string. This is the behavior when a word is used as the value in
181 // a shell variable assignment, for example.
182 //
183 // The config specifies shell expansion options; nil behaves the same as an
184 // empty config.
185 func Literal(cfg *Config, word *syntax.Word) (string, error) {
186 if word == nil {
187 return "", nil
188 }
189 cfg = prepareConfig(cfg)
190 field, err := cfg.wordField(word.Parts, quoteNone)
191 if err != nil {
192 return "", err
193 }
194 return cfg.fieldJoin(field), nil
195 }
196
197 // Document expands a single shell word as if it were a here-document body.
198 // It is similar to [Literal], but without brace expansion, tilde expansion, and
199 // globbing.
200 //
201 // The config specifies shell expansion options; nil behaves the same as an
202 // empty config.
203 func Document(cfg *Config, word *syntax.Word) (string, error) {
204 if word == nil {
205 return "", nil
206 }
207 cfg = prepareConfig(cfg)
208 field, err := cfg.wordField(word.Parts, quoteHeredoc)
209 if err != nil {
210 return "", err
211 }
212 return cfg.fieldJoin(field), nil
213 }
214
215 // Pattern expands a single shell word as a pattern, using [pattern.QuoteMeta]
216 // on any non-quoted parts of the input word. The result can be used on
217 // [pattern.Regexp] directly.
218 //
219 // The config specifies shell expansion options; nil behaves the same as an
220 // empty config.
221 func Pattern(cfg *Config, word *syntax.Word) (string, error) {
222 if word == nil {
223 return "", nil
224 }
225 cfg = prepareConfig(cfg)
226 field, err := cfg.wordField(word.Parts, quoteNone)
227 if err != nil {
228 return "", err
229 }
230 sb := cfg.strBuilder()
231 for _, part := range field {
232 if part.quote > quoteNone {
233 sb.WriteString(pattern.QuoteMeta(part.val, 0))
234 } else {
235 sb.WriteString(part.val)
236 }
237 }
238 return sb.String(), nil
239 }
240
241 // Format expands a format string with a number of arguments, following the
242 // shell's format specifications. These include printf(1), among others.
243 //
244 // The resulting string is returned, along with the number of arguments used.
245 // Note that the resulting string may contain null bytes, for example
246 // if the format string used `\x00`. The caller should terminate the string
247 // at the first null byte if needed, such as when expanding for `$'foo\x00bar'`.
248 //
249 // The config specifies shell expansion options; nil behaves the same as an
250 // empty config.
251 func Format(cfg *Config, format string, args []string) (string, int, error) {
252 cfg = prepareConfig(cfg)
253 sb := cfg.strBuilder()
254
255 consumed, err := formatInto(sb, format, args)
256 if err != nil {
257 return "", 0, err
258 }
259
260 return sb.String(), consumed, err
261 }
262
263 func formatInto(sb *strings.Builder, format string, args []string) (int, error) {
264 var fmts []byte
265 initialArgs := len(args)
266
267 for i := 0; i < len(format); i++ {
268 // readDigits reads from 0 to max digits, either octal or
269 // hexadecimal.
270 readDigits := func(max int, hex bool) string {
271 j := 0
272 for ; j < max && i+j < len(format); j++ {
273 c := format[i+j]
274 if (c >= '0' && c <= '9') ||
275 (hex && c >= 'a' && c <= 'f') ||
276 (hex && c >= 'A' && c <= 'F') {
277 // valid octal or hex char
278 } else {
279 break
280 }
281 }
282 digits := format[i : i+j]
283 i += j - 1 // -1 since the outer loop does i++
284 return digits
285 }
286 c := format[i]
287 switch {
288 case c == '\\': // escaped
289 i++
290 if i >= len(format) {
291 sb.WriteByte('\\')
292 break
293 }
294 switch c = format[i]; c {
295 case 'a': // bell
296 sb.WriteByte('\a')
297 case 'b': // backspace
298 sb.WriteByte('\b')
299 case 'e', 'E': // escape
300 sb.WriteByte('\x1b')
301 case 'f': // form feed
302 sb.WriteByte('\f')
303 case 'n': // new line
304 sb.WriteByte('\n')
305 case 'r': // carriage return
306 sb.WriteByte('\r')
307 case 't': // horizontal tab
308 sb.WriteByte('\t')
309 case 'v': // vertical tab
310 sb.WriteByte('\v')
311 case '\\', '\'', '"', '?': // just the character
312 sb.WriteByte(c)
313 case '0', '1', '2', '3', '4', '5', '6', '7':
314 digits := readDigits(3, false)
315 // if digits don't fit in 8 bits, 0xff via strconv
316 n, _ := strconv.ParseUint(digits, 8, 8)
317 sb.WriteByte(byte(n))
318 case 'x', 'u', 'U':
319 i++
320 max := 2
321 switch c {
322 case 'u':
323 max = 4
324 case 'U':
325 max = 8
326 }
327 digits := readDigits(max, true)
328 if len(digits) > 0 {
329 // can't error
330 n, _ := strconv.ParseUint(digits, 16, 32)
331 if c == 'x' {
332 // always as a single byte
333 sb.WriteByte(byte(n))
334 } else {
335 sb.WriteRune(rune(n))
336 }
337 break
338 }
339 fallthrough
340 default: // no escape sequence
341 sb.WriteByte('\\')
342 sb.WriteByte(c)
343 }
344 case len(fmts) > 0:
345 switch c {
346 case '%':
347 sb.WriteByte('%')
348 fmts = nil
349 case 'c':
350 var b byte
351 if len(args) > 0 {
352 arg := ""
353 arg, args = args[0], args[1:]
354 if len(arg) > 0 {
355 b = arg[0]
356 }
357 }
358 sb.WriteByte(b)
359 fmts = nil
360 case '+', '-', ' ':
361 if len(fmts) > 1 {
362 return 0, fmt.Errorf("invalid format char: %c", c)
363 }
364 fmts = append(fmts, c)
365 case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
366 fmts = append(fmts, c)
367 case 's', 'b', 'd', 'i', 'u', 'o', 'x':
368 arg := ""
369 if len(args) > 0 {
370 arg, args = args[0], args[1:]
371 }
372 var farg any
373 if c == 'b' {
374 // Passing in nil for args ensures that % format
375 // strings aren't processed; only escape sequences
376 // will be handled.
377 _, err := formatInto(sb, arg, nil)
378 if err != nil {
379 return 0, err
380 }
381 } else if c != 's' {
382 n, _ := strconv.ParseInt(arg, 0, 0)
383 if c == 'i' || c == 'd' {
384 farg = int(n)
385 } else {
386 farg = uint(n)
387 }
388 if c == 'i' || c == 'u' {
389 c = 'd'
390 }
391 } else {
392 farg = arg
393 }
394 if farg != nil {
395 fmts = append(fmts, c)
396 fmt.Fprintf(sb, string(fmts), farg)
397 }
398 fmts = nil
399 default:
400 return 0, fmt.Errorf("invalid format char: %c", c)
401 }
402 case args != nil && c == '%':
403 // if args == nil, we are not doing format
404 // arguments
405 fmts = []byte{c}
406 default:
407 sb.WriteByte(c)
408 }
409 }
410 if len(fmts) > 0 {
411 return 0, fmt.Errorf("missing format char")
412 }
413 return initialArgs - len(args), nil
414 }
415
416 func (cfg *Config) fieldJoin(parts []fieldPart) string {
417 switch len(parts) {
418 case 0:
419 return ""
420 case 1: // short-cut without a string copy
421 return parts[0].val
422 }
423 sb := cfg.strBuilder()
424 for _, part := range parts {
425 sb.WriteString(part.val)
426 }
427 return sb.String()
428 }
429
430 func (cfg *Config) escapedGlobField(parts []fieldPart) (escaped string, glob bool) {
431 candidate := false
432 for _, part := range parts {
433 if part.quote == quoteNone && strings.ContainsAny(part.val, "*?[") {
434 candidate = true
435 break
436 }
437 }
438 if !candidate {
439 return "", false
440 }
441 sb := cfg.strBuilder()
442 for _, part := range parts {
443 if part.quote > quoteNone {
444 sb.WriteString(pattern.QuoteMeta(part.val, 0))
445 } else {
446 sb.WriteString(part.val)
447 }
448 }
449 // Check the entire escaped word, as a bracket expression could span
450 // multiple unquoted parts, such as `[a$x` where x holds "]".
451 escaped = sb.String()
452 if pattern.HasMeta(escaped, 0) {
453 return escaped, true
454 }
455 return "", false
456 }
457
458 // Fields is a pre-iterators API which now wraps [FieldsSeq].
459 func Fields(cfg *Config, words ...*syntax.Word) ([]string, error) {
460 var fields []string
461 for s, err := range FieldsSeq(cfg, words...) {
462 if err != nil {
463 return nil, err
464 }
465 fields = append(fields, s)
466 }
467 return fields, nil
468 }
469
470 // FieldsSeq expands a number of words as if they were arguments in a shell
471 // command. This includes brace expansion, tilde expansion, parameter expansion,
472 // command substitution, arithmetic expansion, quote removal, and globbing.
473 func FieldsSeq(cfg *Config, words ...*syntax.Word) iter.Seq2[string, error] {
474 cfg = prepareConfig(cfg)
475 dir := cfg.envGet("PWD")
476 return func(yield func(string, error) bool) {
477 expandWord := func(w *syntax.Word) (stop bool) {
478 wfields, err := cfg.wordFields(w.Parts)
479 if err != nil {
480 yield("", err)
481 return true
482 }
483 for _, field := range wfields {
484 path, doGlob := cfg.escapedGlobField(field)
485 if doGlob && cfg.ReadDir2 != nil {
486 // Note that globbing requires keeping a slice state, so it doesn't
487 // really benefit from using an iterator.
488 matches, err := cfg.glob(dir, path)
489 if err != nil {
490 // We avoid [errors.As] as it allocates,
491 // and we know that [Config.glob] returns [pattern.Regexp] errors without wrapping.
492 if _, ok := err.(*pattern.SyntaxError); !ok {
493 yield("", err)
494 return true
495 }
496 } else if len(matches) > 0 || cfg.NullGlob {
497 for _, m := range matches {
498 if !yield(m, nil) {
499 return true
500 }
501 }
502 continue
503 }
504 }
505 if !yield(cfg.fieldJoin(field), nil) {
506 return true
507 }
508 }
509 return false
510 }
511 for _, word := range words {
512 word := *word // make a copy, since SplitBraces replaces the Parts slice
513 if !syntax.SplitBraces(&word) {
514 if expandWord(&word) {
515 return
516 }
517 continue
518 }
519 for w, err := range BracesSeq(cfg, &word) {
520 if err != nil {
521 yield("", err)
522 return
523 }
524 if expandWord(w) {
525 return
526 }
527 }
528 }
529 }
530 }
531
532 type fieldPart struct {
533 val string
534 quote quoteLevel
535 }
536
537 type quoteLevel uint
538
539 const (
540 quoteNone quoteLevel = iota
541 quoteDouble
542 quoteHeredoc
543 quoteSingle
544 )
545
546 func (cfg *Config) wordField(wps []syntax.WordPart, ql quoteLevel) ([]fieldPart, error) {
547 var field []fieldPart
548 for i, wp := range wps {
549 switch wp := wp.(type) {
550 case *syntax.Lit:
551 s := wp.Value
552 if i == 0 && ql == quoteNone {
553 if prefix, rest := cfg.expandUser(s, len(wps) > 1); prefix != "" {
554 // TODO: return two separate fieldParts,
555 // like in wordFields?
556 s = prefix + rest
557 }
558 }
559 if (ql == quoteDouble || ql == quoteHeredoc) && strings.Contains(s, "\\") {
560 sb := cfg.strBuilder()
561 for i := 0; i < len(s); i++ {
562 b := s[i]
563 if b == '\\' && i+1 < len(s) {
564 switch s[i+1] {
565 case '"':
566 if ql != quoteDouble {
567 break
568 }
569 fallthrough
570 case '\\', '$', '`': // special chars
571 i++
572 b = s[i] // write the special char, skipping the backslash
573 }
574 }
575 sb.WriteByte(b)
576 }
577 s = sb.String()
578 }
579 s, _, _ = strings.Cut(s, "\x00") // TODO: why is this needed?
580 field = append(field, fieldPart{val: s})
581 case *syntax.SglQuoted:
582 fp := fieldPart{quote: quoteSingle, val: wp.Value}
583 if wp.Dollar {
584 fp.val, _, _ = Format(cfg, fp.val, nil)
585 fp.val, _, _ = strings.Cut(fp.val, "\x00") // cut the string if format included \x00
586 }
587 field = append(field, fp)
588 case *syntax.DblQuoted:
589 wfield, err := cfg.wordField(wp.Parts, quoteDouble)
590 if err != nil {
591 return nil, err
592 }
593 for _, part := range wfield {
594 part.quote = quoteDouble
595 field = append(field, part)
596 }
597 case *syntax.ParamExp:
598 val, err := cfg.paramExp(wp)
599 if err != nil {
600 return nil, err
601 }
602 field = append(field, fieldPart{val: val})
603 case *syntax.CmdSubst:
604 val, err := cfg.cmdSubst(wp)
605 if err != nil {
606 return nil, err
607 }
608 field = append(field, fieldPart{val: val})
609 case *syntax.ArithmExp:
610 n, err := Arithm(cfg, wp.X)
611 if err != nil {
612 return nil, err
613 }
614 field = append(field, fieldPart{val: strconv.Itoa(n)})
615 case *syntax.ProcSubst:
616 path, err := cfg.ProcSubst(wp)
617 if err != nil {
618 return nil, err
619 }
620 field = append(field, fieldPart{val: path})
621 case *syntax.ExtGlob:
622 // Like how [Config.wordFields] deals with [syntax.ExtGlob],
623 // except that we allow these through even when [Config.ExtGlob]
624 // is false, as it only applies to pathname expansion.
625 field = append(field, fieldPart{val: wp.Op.String() + wp.Pattern.Value + ")"})
626 default:
627 panic(fmt.Sprintf("unhandled word part: %T", wp))
628 }
629 }
630 return field, nil
631 }
632
633 func (cfg *Config) cmdSubst(cs *syntax.CmdSubst) (string, error) {
634 if cfg.CmdSubst == nil {
635 return "", UnexpectedCommandError{Node: cs}
636 }
637 sb := cfg.strBuilder()
638 if err := cfg.CmdSubst(sb, cs); err != nil {
639 return "", err
640 }
641 out := sb.String()
642 out = strings.ReplaceAll(out, "\x00", "")
643 return strings.TrimRight(out, "\n"), nil
644 }
645
646 func (cfg *Config) wordFields(wps []syntax.WordPart) ([][]fieldPart, error) {
647 fields := cfg.fieldsAlloc[:0]
648 curField := cfg.fieldAlloc[:0]
649 allowEmpty := false
650 flush := func() {
651 if len(curField) == 0 {
652 return
653 }
654 fields = append(fields, curField)
655 curField = nil
656 }
657 splitAdd := func(val string) {
658 fieldStart := -1
659 for i, r := range val {
660 if cfg.ifsRune(r) {
661 if fieldStart >= 0 { // ending a field
662 curField = append(curField, fieldPart{val: val[fieldStart:i]})
663 fieldStart = -1
664 }
665 flush()
666 } else {
667 if fieldStart < 0 { // starting a new field
668 fieldStart = i
669 }
670 }
671 }
672 if fieldStart >= 0 { // ending a field without IFS
673 curField = append(curField, fieldPart{val: val[fieldStart:]})
674 }
675 }
676 for i, wp := range wps {
677 switch wp := wp.(type) {
678 case *syntax.Lit:
679 s := wp.Value
680 if i == 0 {
681 prefix, rest := cfg.expandUser(s, len(wps) > 1)
682 curField = append(curField, fieldPart{
683 quote: quoteSingle,
684 val: prefix,
685 })
686 s = rest
687 }
688 // Escaped characters are quoted, so that they aren't
689 // treated as metacharacters when globbing.
690 for {
691 i := strings.IndexByte(s, '\\')
692 if i < 0 || i == len(s)-1 {
693 break // a trailing backslash is kept as-is
694 }
695 _, size := utf8.DecodeRuneInString(s[i+1:])
696 curField = append(curField,
697 fieldPart{val: s[:i]},
698 fieldPart{quote: quoteSingle, val: s[i+1 : i+1+size]},
699 )
700 s = s[i+1+size:]
701 }
702 curField = append(curField, fieldPart{val: s})
703 case *syntax.SglQuoted:
704 allowEmpty = true
705 fp := fieldPart{quote: quoteSingle, val: wp.Value}
706 if wp.Dollar {
707 fp.val, _, _ = Format(cfg, fp.val, nil)
708 fp.val, _, _ = strings.Cut(fp.val, "\x00") // cut the string if format included \x00
709 }
710 curField = append(curField, fp)
711 case *syntax.DblQuoted:
712 if len(wp.Parts) == 1 {
713 pe, _ := wp.Parts[0].(*syntax.ParamExp)
714 elems, err := cfg.quotedElemFields(pe)
715 if err != nil {
716 return nil, err
717 }
718 if elems != nil {
719 for i, elem := range elems {
720 if i > 0 {
721 flush()
722 }
723 curField = append(curField, fieldPart{
724 quote: quoteDouble,
725 val: elem,
726 })
727 }
728 continue
729 }
730 }
731 allowEmpty = true
732 wfield, err := cfg.wordField(wp.Parts, quoteDouble)
733 if err != nil {
734 return nil, err
735 }
736 for _, part := range wfield {
737 part.quote = quoteDouble
738 curField = append(curField, part)
739 }
740 case *syntax.ParamExp:
741 if elems, ok := cfg.unquotedElemFields(wp); ok {
742 // Unquoted "*" or "@" expansions produce one field per
743 // element; joining and re-splitting them would lose
744 // fields when IFS is empty.
745 for j, elem := range elems {
746 if j > 0 {
747 flush()
748 }
749 splitAdd(elem)
750 }
751 continue
752 }
753 val, err := cfg.paramExp(wp)
754 if err != nil {
755 return nil, err
756 }
757 splitAdd(val)
758 case *syntax.CmdSubst:
759 val, err := cfg.cmdSubst(wp)
760 if err != nil {
761 return nil, err
762 }
763 splitAdd(val)
764 case *syntax.ArithmExp:
765 n, err := Arithm(cfg, wp.X)
766 if err != nil {
767 return nil, err
768 }
769 curField = append(curField, fieldPart{val: strconv.Itoa(n)})
770 case *syntax.ProcSubst:
771 path, err := cfg.ProcSubst(wp)
772 if err != nil {
773 return nil, err
774 }
775 splitAdd(path)
776 case *syntax.ExtGlob:
777 if !cfg.ExtGlob {
778 return nil, fmt.Errorf("extended globbing operator used without the \"extglob\" option set")
779 }
780 // We don't translate or interpret the pattern here in any way;
781 // that's done later when globbing takes place via [pattern.Regexp].
782 // Here, all we do is keep the extended globbing expression in string form.
783 //
784 // TODO(v4): perhaps the syntax parser should keep extended globbing expressions
785 // as plain literal strings, because a custom node is not particularly helpful.
786 // It's not like other globbing operators like `*` or `**` get their own nodes.
787 curField = append(curField, fieldPart{val: wp.Op.String() + wp.Pattern.Value + ")"})
788 default:
789 panic(fmt.Sprintf("unhandled word part: %T", wp))
790 }
791 }
792 flush()
793 if allowEmpty && len(fields) == 0 {
794 fields = append(fields, curField)
795 }
796 return fields, nil
797 }
798
799 // listElems returns the elements of a "*" or "@" expansion of a list, like
800 // $@ or ${arr[*]}, with star set for the "*" forms which join into a single
801 // field when quoted. ok is false for any other parameter expansion.
802 func (cfg *Config) listElems(pe *syntax.ParamExp) (elems []string, star, ok bool) {
803 if pe.Param == nil { // e.g. zsh's ${}; paramExp rejects it
804 return nil, false, false
805 }
806 switch name := pe.Param.Value; name {
807 case "*", "@":
808 return cfg.sliceElems(pe, cfg.Env.Get(name).List, nil, true), name == "*", true
809 }
810 switch lit := nodeLit(pe.Index); lit {
811 case "@", "*":
812 switch vr := cfg.Env.Get(pe.Param.Value); vr.Kind {
813 case Indexed:
814 return cfg.sliceElems(pe, vr.List, vr.Indexes, false), lit == "*", true
815 case Associative:
816 return slices.Sorted(maps.Values(vr.Map)), lit == "*", true
817 }
818 }
819 return nil, false, false
820 }
821
822 // unquotedElemFields returns the elements of an unquoted "*" or "@" list
823 // expansion like $* or ${foo[@]}; ok is false for any other expansion.
824 func (cfg *Config) unquotedElemFields(pe *syntax.ParamExp) ([]string, bool) {
825 if pe.Excl || pe.Length || pe.Width || pe.IsSet || pe.Repl != nil || pe.Exp != nil {
826 return nil, false
827 }
828 elems, _, ok := cfg.listElems(pe)
829 return elems, ok
830 }
831
832 // quotedElemFields returns the list of elements resulting from a quoted
833 // parameter expansion that should be treated especially, like "${foo[@]}".
834 // The result is nil for any other parameter expansion.
835 func (cfg *Config) quotedElemFields(pe *syntax.ParamExp) ([]string, error) {
836 if pe == nil || pe.Param == nil || pe.Length || pe.Width || pe.IsSet {
837 return nil, nil
838 }
839 name := pe.Param.Value
840 if pe.Excl {
841 switch pe.Names {
842 case syntax.NamesPrefixWords: // "${!prefix@}"
843 return cfg.namesByPrefix(pe.Param.Value), nil
844 case syntax.NamesPrefix: // "${!prefix*}"
845 return nil, nil
846 }
847 switch nodeLit(pe.Index) {
848 case "@": // "${!name[@]}"
849 switch vr := cfg.Env.Get(name); vr.Kind {
850 case Indexed:
851 return vr.indexedKeys(), nil
852 case Associative:
853 return slices.Collect(maps.Keys(vr.Map)), nil
854 }
855 }
856 return nil, nil
857 }
858 if elems, star, ok := cfg.listElems(pe); ok {
859 // Operators like "${foo[@]#prefix}" apply to each element.
860 elems, err := cfg.perElemOps(pe, elems)
861 if err != nil {
862 return nil, err
863 }
864 if star {
865 return []string{cfg.ifsJoin(elems)}, nil
866 }
867 return elems, nil
868 }
869 if nodeLit(pe.Index) == "@" && !cfg.Env.Get(name).IsSet() {
870 // An unset "${name[@]}" produces zero fields, like an empty array.
871 return []string{}, nil
872 }
873 return nil, nil
874 }
875
876 // sliceElems applies ${var:offset:length} slicing to a list of elements.
877 // When positional is true, $0 is prepended to the list before slicing.
878 // In bash, positional parameter offsets ($@ and $*) are 1-based and
879 // offset 0 includes $0 (the shell or script name). Negative offsets
880 // count from $# + 1, so $0 is reachable via large enough negative values.
881 // A non-nil indexes records the index of each element in a sparse array;
882 // see [Variable.Indexes].
883 func (cfg *Config) sliceElems(pe *syntax.ParamExp, elems []string, indexes []int, positional bool) []string {
884 if pe.Slice == nil {
885 return elems
886 }
887 if positional {
888 elems = append([]string{cfg.Env.Get("0").Str}, elems...)
889 }
890 slicePos := func(n int) int {
891 if n < 0 {
892 n = len(elems) + n
893 if n < 0 {
894 n = len(elems)
895 }
896 } else if n > len(elems) {
897 n = len(elems)
898 }
899 return n
900 }
901 if pe.Slice.Offset != nil {
902 offset, err := Arithm(cfg, pe.Slice.Offset)
903 if err != nil {
904 return elems
905 }
906 if len(indexes) > 0 {
907 // Sparse arrays slice by index: a negative offset counts
908 // from one past the maximum index, and the result begins
909 // with the first element whose index is at least the offset.
910 if offset < 0 {
911 offset += indexes[len(indexes)-1] + 1
912 if offset < 0 {
913 offset = indexes[len(indexes)-1] + 1
914 }
915 }
916 pos, _ := slices.BinarySearch(indexes, offset)
917 elems = elems[pos:]
918 } else {
919 elems = elems[slicePos(offset):]
920 }
921 }
922 if pe.Slice.Length != nil {
923 length, err := Arithm(cfg, pe.Slice.Length)
924 if err != nil {
925 return elems
926 }
927 elems = elems[:slicePos(length)]
928 }
929 return elems
930 }
931
932 func (cfg *Config) expandUser(field string, moreFields bool) (prefix, rest string) {
933 name, ok := strings.CutPrefix(field, "~")
934 if !ok {
935 // No tilde prefix to expand, e.g. "foo".
936 return "", field
937 }
938 i := strings.IndexByte(name, '/')
939 if i < 0 && moreFields {
940 // There is a tilde prefix, but followed by more fields, e.g. "~'foo'".
941 // We only proceed if an unquoted slash was found in this field, e.g. "~/'foo'".
942 return "", field
943 }
944 if i >= 0 {
945 rest = name[i:]
946 name = name[:i]
947 }
948 if name == "" {
949 // Current user; try via "HOME", otherwise fall back to the
950 // system's appropriate home dir env var. Don't use os/user, as
951 // that's overkill. We can't use [os.UserHomeDir], because we want
952 // to use cfg.Env, and we always want to check "HOME" first.
953
954 if vr := cfg.Env.Get("HOME"); vr.IsSet() {
955 return vr.String(), rest
956 }
957
958 if runtime.GOOS == "windows" {
959 if vr := cfg.Env.Get("USERPROFILE"); vr.IsSet() {
960 return vr.String(), rest
961 }
962 }
963 return "", field
964 }
965
966 // Not the current user; try via "HOME <name>", otherwise fall back to
967 // os/user. There isn't a way to lookup user home dirs without cgo.
968
969 if vr := cfg.Env.Get("HOME " + name); vr.IsSet() {
970 return vr.String(), rest
971 }
972
973 u, err := user.Lookup(name)
974 if err != nil {
975 return "", field
976 }
977 return u.HomeDir, rest
978 }
979
980 func findAllIndex(pat, name string, n int) [][]int {
981 expr, err := pattern.Regexp(pat, 0)
982 if err != nil {
983 return nil
984 }
985 rx := regexp.MustCompile(expr)
986 return rx.FindAllStringIndex(name, n)
987 }
988
989 var (
990 rxGlobStar = regexp.MustCompile(`^[^/.][^/]*$`)
991 rxGlobStarDotGlob = regexp.MustCompile(`^[^/]*$`)
992 )
993
994 // pathJoin2 is a simpler version of [filepath.Join] without cleaning the result,
995 // since that's needed for globbing.
996 func pathJoin2(elem1, elem2 string) string {
997 if elem1 == "" {
998 return elem2
999 }
1000 if strings.HasSuffix(elem1, string(filepath.Separator)) {
1001 return elem1 + elem2
1002 }
1003 return elem1 + string(filepath.Separator) + elem2
1004 }
1005
1006 // pathSplit splits a file path into its elements, retaining empty ones. Before
1007 // splitting, slashes are replaced with [filepath.Separator], so that splitting
1008 // Unix paths on Windows works as well.
1009 func pathSplit(path string) []string {
1010 path = filepath.FromSlash(path)
1011 return strings.Split(path, string(filepath.Separator))
1012 }
1013
1014 func (cfg *Config) glob(base, pat string) ([]string, error) {
1015 parts := pathSplit(pat)
1016 matches := []string{""}
1017 if filepath.IsAbs(pat) {
1018 if parts[0] == "" {
1019 // unix-like
1020 matches[0] = string(filepath.Separator)
1021 } else {
1022 // windows (for some reason it won't work without the
1023 // trailing separator)
1024 matches[0] = parts[0] + string(filepath.Separator)
1025 }
1026 parts = parts[1:]
1027 }
1028 // TODO: as an optimization, we could do chunks of the path all at once,
1029 // like doing a single stat for "/foo/bar" in "/foo/bar/*".
1030
1031 // TODO: Another optimization would be to reduce the number of ReadDir2 calls.
1032 // For example, /foo/* can end up doing one duplicate call:
1033 //
1034 // ReadDir2("/foo") to ensure that "/foo/" exists and only matches a directory
1035 // ReadDir2("/foo") glob "*"
1036
1037 for i, part := range parts {
1038 // Keep around for debugging.
1039 // log.Printf("matches %q part %d %q", matches, i, part)
1040
1041 wantDir := i < len(parts)-1
1042 switch {
1043 case part == "", part == ".", part == "..":
1044 for i, dir := range matches {
1045 matches[i] = pathJoin2(dir, part)
1046 }
1047 continue
1048 case !pattern.HasMeta(part, 0):
1049 var newMatches []string
1050 for _, dir := range matches {
1051 match := dir
1052 if !filepath.IsAbs(match) {
1053 match = filepath.Join(base, match)
1054 }
1055 match = pathJoin2(match, part)
1056 // We can't use [Config.ReadDir2] on the parent and match the directory
1057 // entry by name, because short paths on Windows break that.
1058 // Our only option is to [Config.ReadDir2] on the directory entry itself,
1059 // which can be wasteful if we only want to see if it exists,
1060 // but at least it's correct in all scenarios.
1061 if _, err := cfg.ReadDir2(match); err != nil {
1062 if errors.Is(err, syscall.ENOTDIR) {
1063 // Reading a regular file as a directory.
1064 // Note that on Windows this error also satisfies
1065 // [fs.ErrNotExist], so it must be checked first;
1066 // see https://github.com/golang/go/issues/46734.
1067 } else if errors.Is(err, fs.ErrNotExist) {
1068 continue // simply doesn't exist
1069 }
1070 if wantDir {
1071 continue // exists but not a directory
1072 }
1073 }
1074 newMatches = append(newMatches, pathJoin2(dir, part))
1075 }
1076 matches = newMatches
1077 continue
1078 case part == "**" && cfg.GlobStar:
1079 // Find all recursive matches for "**".
1080 // Note that we need the results to be in depth-first order,
1081 // and to avoid recursion, we use a slice as a stack.
1082 // Since we pop from the back, we populate the stack backwards.
1083 stack := make([]string, 0, len(matches))
1084 for _, match := range slices.Backward(matches) {
1085 // "a/**" should match "a/ a/b a/b/cfg ...";
1086 // note how the zero-match case there has a trailing separator.
1087 stack = append(stack, pathJoin2(match, ""))
1088 }
1089 matches = matches[:0]
1090 var newMatches []string // to reuse its capacity
1091 for len(stack) > 0 {
1092 dir := stack[len(stack)-1]
1093 stack = stack[:len(stack)-1]
1094 matches = append(matches, dir)
1095
1096 // If dir is not a directory, we keep the stack as-is and continue.
1097 newMatches = newMatches[:0]
1098 rx := rxGlobStar.MatchString
1099 if cfg.DotGlob {
1100 rx = rxGlobStarDotGlob.MatchString
1101 }
1102 newMatches, _ = cfg.globDir(base, dir, rx, wantDir, newMatches)
1103 for _, match := range slices.Backward(newMatches) {
1104 stack = append(stack, match)
1105 }
1106 }
1107 continue
1108 }
1109 mode := pattern.Filenames | pattern.EntireString | pattern.NoGlobStar
1110 if cfg.NoCaseGlob {
1111 mode |= pattern.NoGlobCase
1112 }
1113 if cfg.DotGlob {
1114 mode |= pattern.GlobLeadingDot
1115 }
1116 if cfg.ExtGlob {
1117 mode |= pattern.ExtendedOperators
1118 }
1119 matcher, err := internal.ExtendedPatternMatcher(part, mode)
1120 if err != nil {
1121 return nil, err
1122 }
1123 var newMatches []string
1124 for _, dir := range matches {
1125 newMatches, err = cfg.globDir(base, dir, matcher, wantDir, newMatches)
1126 if err != nil {
1127 return nil, err
1128 }
1129 }
1130 matches = newMatches
1131 }
1132 // Note that the results need to be sorted.
1133 // TODO: above we do a BFS; if we did a DFS, the matches would already be sorted.
1134 slices.Sort(matches)
1135 // Remove any empty matches left behind from "**".
1136 if len(matches) > 0 && matches[0] == "" {
1137 matches = matches[1:]
1138 }
1139 return matches, nil
1140 }
1141
1142 func (cfg *Config) globDir(base, dir string, matcher func(string) bool, wantDir bool, matches []string) ([]string, error) {
1143 fullDir := dir
1144 if !filepath.IsAbs(dir) {
1145 fullDir = filepath.Join(base, dir)
1146 }
1147 infos, err := cfg.ReadDir2(fullDir)
1148 if err != nil {
1149 // We still want to return matches, for the sake of reusing slices.
1150 return matches, err
1151 }
1152 for _, info := range infos {
1153 name := info.Name()
1154 if !wantDir {
1155 // No filtering.
1156 } else if mode := info.Type(); mode&os.ModeSymlink != 0 {
1157 // We need to know if the symlink points to a directory.
1158 // This requires an extra syscall, as [Config.ReadDir] on the parent directory
1159 // does not follow symlinks for each of the directory entries.
1160 // ReadDir is somewhat wasteful here, as we only want its error result,
1161 // but we could try to reuse its result as per the TODO in [Config.glob].
1162 if _, err := cfg.ReadDir2(filepath.Join(fullDir, info.Name())); err != nil {
1163 continue
1164 }
1165 } else if !mode.IsDir() {
1166 // Not a symlink nor a directory.
1167 continue
1168 }
1169 if matcher(name) {
1170 matches = append(matches, pathJoin2(dir, name))
1171 }
1172 }
1173 return matches, nil
1174 }
1175
1176 // ReadFields splits and returns n fields from s, like the "read" shell builtin.
1177 // If raw is set, backslash escape sequences are not interpreted.
1178 //
1179 // The config specifies shell expansion options; nil behaves the same as an
1180 // empty config.
1181 func ReadFields(cfg *Config, s string, n int, raw bool) []string {
1182 cfg = prepareConfig(cfg)
1183 type pos struct {
1184 start, end int
1185 }
1186 var fpos []pos
1187
1188 runes := make([]rune, 0, len(s))
1189 infield := false
1190 esc := false
1191 for _, r := range s {
1192 if infield {
1193 if cfg.ifsRune(r) && (raw || !esc) {
1194 fpos[len(fpos)-1].end = len(runes)
1195 infield = false
1196 }
1197 } else {
1198 if !cfg.ifsRune(r) && (raw || !esc) {
1199 fpos = append(fpos, pos{start: len(runes), end: -1})
1200 infield = true
1201 }
1202 }
1203 if r == '\\' {
1204 if raw || esc {
1205 runes = append(runes, r)
1206 }
1207 esc = !esc
1208 continue
1209 }
1210 runes = append(runes, r)
1211 esc = false
1212 }
1213 if len(fpos) == 0 {
1214 return nil
1215 }
1216 if infield {
1217 fpos[len(fpos)-1].end = len(runes)
1218 }
1219
1220 switch {
1221 case n == 1:
1222 // The single field spans the whole line minus leading and trailing
1223 // IFS whitespace; anything outside the fields is already IFS.
1224 lo, hi := 0, len(runes)
1225 for lo < fpos[0].start && cfg.ifsWhitespace(runes[lo]) {
1226 lo++
1227 }
1228 for hi > fpos[len(fpos)-1].end && cfg.ifsWhitespace(runes[hi-1]) {
1229 hi--
1230 }
1231 fpos[0].start, fpos[0].end = lo, hi
1232 fpos = fpos[:1]
1233 case n != -1 && n < len(fpos):
1234 // combine to max n fields
1235 fpos[n-1].end = fpos[len(fpos)-1].end
1236 fpos = fpos[:n]
1237 }
1238
1239 fields := make([]string, len(fpos))
1240 for i, p := range fpos {
1241 fields[i] = string(runes[p.start:p.end])
1242 }
1243 return fields
1244 }