expand.go 591 B

1234567891011121314151617181920212223242526272829
  1. package fsext
  2. import (
  3. "os"
  4. "strings"
  5. "mvdan.cc/sh/v3/expand"
  6. "mvdan.cc/sh/v3/syntax"
  7. )
  8. // Expand is a wrapper around [expand.Literal]. It will escape the input
  9. // string, expand any shell symbols (such as '~') and resolve any environment
  10. // variables.
  11. func Expand(s string) (string, error) {
  12. if s == "" {
  13. return "", nil
  14. }
  15. p := syntax.NewParser()
  16. word, err := p.Document(strings.NewReader(s))
  17. if err != nil {
  18. return "", err
  19. }
  20. cfg := &expand.Config{
  21. Env: expand.FuncEnviron(os.Getenv),
  22. ReadDir2: os.ReadDir,
  23. GlobStar: true,
  24. }
  25. return expand.Literal(cfg, word)
  26. }