exec.go 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  1. package execext
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "os"
  8. "path/filepath"
  9. "strings"
  10. "time"
  11. "mvdan.cc/sh/v3/expand"
  12. "mvdan.cc/sh/v3/interp"
  13. "mvdan.cc/sh/v3/shell"
  14. "mvdan.cc/sh/v3/syntax"
  15. )
  16. // RunCommandOptions is the options for the RunCommand func
  17. type RunCommandOptions struct {
  18. Command string
  19. Dir string
  20. Env []string
  21. PosixOpts []string
  22. BashOpts []string
  23. Stdin io.Reader
  24. Stdout io.Writer
  25. Stderr io.Writer
  26. }
  27. // ErrNilOptions is returned when a nil options is given
  28. var ErrNilOptions = errors.New("execext: nil options given")
  29. // RunCommand runs a shell command
  30. func RunCommand(ctx context.Context, opts *RunCommandOptions) error {
  31. if opts == nil {
  32. return ErrNilOptions
  33. }
  34. // Set "-e" or "errexit" by default
  35. opts.PosixOpts = append(opts.PosixOpts, "e")
  36. // Format POSIX options into a slice that mvdan/sh understands
  37. var params []string
  38. for _, opt := range opts.PosixOpts {
  39. if len(opt) == 1 {
  40. params = append(params, fmt.Sprintf("-%s", opt))
  41. } else {
  42. params = append(params, "-o")
  43. params = append(params, opt)
  44. }
  45. }
  46. environ := opts.Env
  47. if len(environ) == 0 {
  48. environ = os.Environ()
  49. }
  50. r, err := interp.New(
  51. interp.Params(params...),
  52. interp.Env(expand.ListEnviron(environ...)),
  53. interp.ExecHandlers(execHandler),
  54. interp.OpenHandler(openHandler),
  55. interp.StdIO(opts.Stdin, opts.Stdout, opts.Stderr),
  56. dirOption(opts.Dir),
  57. )
  58. if err != nil {
  59. return err
  60. }
  61. parser := syntax.NewParser()
  62. // Run any shopt commands
  63. if len(opts.BashOpts) > 0 {
  64. shoptCmdStr := fmt.Sprintf("shopt -s %s", strings.Join(opts.BashOpts, " "))
  65. shoptCmd, err := parser.Parse(strings.NewReader(shoptCmdStr), "")
  66. if err != nil {
  67. return err
  68. }
  69. if err := r.Run(ctx, shoptCmd); err != nil {
  70. return err
  71. }
  72. }
  73. // Run the user-defined command
  74. p, err := parser.Parse(strings.NewReader(opts.Command), "")
  75. if err != nil {
  76. return err
  77. }
  78. return r.Run(ctx, p)
  79. }
  80. // Expand is a helper to mvdan.cc/shell.Fields that returns the first field
  81. // if available.
  82. func Expand(s string) (string, error) {
  83. s = filepath.ToSlash(s)
  84. s = strings.ReplaceAll(s, " ", `\ `)
  85. s = strings.ReplaceAll(s, "&", `\&`)
  86. s = strings.ReplaceAll(s, "(", `\(`)
  87. s = strings.ReplaceAll(s, ")", `\)`)
  88. fields, err := shell.Fields(s, nil)
  89. if err != nil {
  90. return "", err
  91. }
  92. if len(fields) > 0 {
  93. return fields[0], nil
  94. }
  95. return "", nil
  96. }
  97. func execHandler(next interp.ExecHandlerFunc) interp.ExecHandlerFunc {
  98. return interp.DefaultExecHandler(15 * time.Second)
  99. }
  100. func openHandler(ctx context.Context, path string, flag int, perm os.FileMode) (io.ReadWriteCloser, error) {
  101. if path == "/dev/null" {
  102. return devNull{}, nil
  103. }
  104. return interp.DefaultOpenHandler()(ctx, path, flag, perm)
  105. }
  106. func dirOption(path string) interp.RunnerOption {
  107. return func(r *interp.Runner) error {
  108. err := interp.Dir(path)(r)
  109. if err == nil {
  110. return nil
  111. }
  112. // If the specified directory doesn't exist, it will be created later.
  113. // Therefore, even if `interp.Dir` method returns an error, the
  114. // directory path should be set only when the directory cannot be found.
  115. if absPath, _ := filepath.Abs(path); absPath != "" {
  116. if _, err := os.Stat(absPath); os.IsNotExist(err) {
  117. r.Dir = absPath
  118. return nil
  119. }
  120. }
  121. return err
  122. }
  123. }