You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

command.go 8.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. // Copyright 2015 The Gogs Authors. All rights reserved.
  2. // Copyright 2016 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package git
  6. import (
  7. "bytes"
  8. "context"
  9. "fmt"
  10. "io"
  11. "os"
  12. "os/exec"
  13. "strings"
  14. "time"
  15. "code.gitea.io/gitea/modules/process"
  16. )
  17. var (
  18. // GlobalCommandArgs global command args for external package setting
  19. GlobalCommandArgs []string
  20. // DefaultCommandExecutionTimeout default command execution timeout duration
  21. DefaultCommandExecutionTimeout = 360 * time.Second
  22. )
  23. // DefaultLocale is the default LC_ALL to run git commands in.
  24. const DefaultLocale = "C"
  25. // Command represents a command with its subcommands or arguments.
  26. type Command struct {
  27. name string
  28. args []string
  29. parentContext context.Context
  30. desc string
  31. }
  32. func (c *Command) String() string {
  33. if len(c.args) == 0 {
  34. return c.name
  35. }
  36. return fmt.Sprintf("%s %s", c.name, strings.Join(c.args, " "))
  37. }
  38. // NewCommand creates and returns a new Git Command based on given command and arguments.
  39. func NewCommand(args ...string) *Command {
  40. return NewCommandContext(DefaultContext, args...)
  41. }
  42. // NewCommandContext creates and returns a new Git Command based on given command and arguments.
  43. func NewCommandContext(ctx context.Context, args ...string) *Command {
  44. // Make an explicit copy of GlobalCommandArgs, otherwise append might overwrite it
  45. cargs := make([]string, len(GlobalCommandArgs))
  46. copy(cargs, GlobalCommandArgs)
  47. return &Command{
  48. name: GitExecutable,
  49. args: append(cargs, args...),
  50. parentContext: ctx,
  51. }
  52. }
  53. // NewCommandNoGlobals creates and returns a new Git Command based on given command and arguments only with the specify args and don't care global command args
  54. func NewCommandNoGlobals(args ...string) *Command {
  55. return NewCommandContextNoGlobals(DefaultContext, args...)
  56. }
  57. // NewCommandContextNoGlobals creates and returns a new Git Command based on given command and arguments only with the specify args and don't care global command args
  58. func NewCommandContextNoGlobals(ctx context.Context, args ...string) *Command {
  59. return &Command{
  60. name: GitExecutable,
  61. args: args,
  62. parentContext: ctx,
  63. }
  64. }
  65. // SetParentContext sets the parent context for this command
  66. func (c *Command) SetParentContext(ctx context.Context) *Command {
  67. c.parentContext = ctx
  68. return c
  69. }
  70. // SetDescription sets the description for this command which be returned on
  71. // c.String()
  72. func (c *Command) SetDescription(desc string) *Command {
  73. c.desc = desc
  74. return c
  75. }
  76. // AddArguments adds new argument(s) to the command.
  77. func (c *Command) AddArguments(args ...string) *Command {
  78. c.args = append(c.args, args...)
  79. return c
  80. }
  81. // RunInDirTimeoutEnvPipeline executes the command in given directory with given timeout,
  82. // it pipes stdout and stderr to given io.Writer.
  83. func (c *Command) RunInDirTimeoutEnvPipeline(env []string, timeout time.Duration, dir string, stdout, stderr io.Writer) error {
  84. return c.RunInDirTimeoutEnvFullPipeline(env, timeout, dir, stdout, stderr, nil)
  85. }
  86. // RunInDirTimeoutEnvFullPipeline executes the command in given directory with given timeout,
  87. // it pipes stdout and stderr to given io.Writer and passes in an io.Reader as stdin.
  88. func (c *Command) RunInDirTimeoutEnvFullPipeline(env []string, timeout time.Duration, dir string, stdout, stderr io.Writer, stdin io.Reader) error {
  89. return c.RunInDirTimeoutEnvFullPipelineFunc(env, timeout, dir, stdout, stderr, stdin, nil)
  90. }
  91. // RunInDirTimeoutEnvFullPipelineFunc executes the command in given directory with given timeout,
  92. // it pipes stdout and stderr to given io.Writer and passes in an io.Reader as stdin. Between cmd.Start and cmd.Wait the passed in function is run.
  93. func (c *Command) RunInDirTimeoutEnvFullPipelineFunc(env []string, timeout time.Duration, dir string, stdout, stderr io.Writer, stdin io.Reader, fn func(context.Context, context.CancelFunc) error) error {
  94. if timeout == -1 {
  95. timeout = DefaultCommandExecutionTimeout
  96. }
  97. if len(dir) == 0 {
  98. log(c.String())
  99. } else {
  100. log("%s: %v", dir, c)
  101. }
  102. ctx, cancel := context.WithTimeout(c.parentContext, timeout)
  103. defer cancel()
  104. cmd := exec.CommandContext(ctx, c.name, c.args...)
  105. if env == nil {
  106. cmd.Env = append(os.Environ(), fmt.Sprintf("LC_ALL=%s", DefaultLocale))
  107. } else {
  108. cmd.Env = env
  109. cmd.Env = append(cmd.Env, fmt.Sprintf("LC_ALL=%s", DefaultLocale))
  110. }
  111. // TODO: verify if this is still needed in golang 1.15
  112. if goVersionLessThan115 {
  113. cmd.Env = append(cmd.Env, "GODEBUG=asyncpreemptoff=1")
  114. }
  115. cmd.Dir = dir
  116. cmd.Stdout = stdout
  117. cmd.Stderr = stderr
  118. cmd.Stdin = stdin
  119. if err := cmd.Start(); err != nil {
  120. return err
  121. }
  122. desc := c.desc
  123. if desc == "" {
  124. desc = fmt.Sprintf("%s %s %s [repo_path: %s]", GitExecutable, c.name, strings.Join(c.args, " "), dir)
  125. }
  126. pid := process.GetManager().Add(desc, cancel)
  127. defer process.GetManager().Remove(pid)
  128. if fn != nil {
  129. err := fn(ctx, cancel)
  130. if err != nil {
  131. cancel()
  132. _ = cmd.Wait()
  133. return err
  134. }
  135. }
  136. if err := cmd.Wait(); err != nil && ctx.Err() != context.DeadlineExceeded {
  137. return err
  138. }
  139. return ctx.Err()
  140. }
  141. // RunInDirTimeoutPipeline executes the command in given directory with given timeout,
  142. // it pipes stdout and stderr to given io.Writer.
  143. func (c *Command) RunInDirTimeoutPipeline(timeout time.Duration, dir string, stdout, stderr io.Writer) error {
  144. return c.RunInDirTimeoutEnvPipeline(nil, timeout, dir, stdout, stderr)
  145. }
  146. // RunInDirTimeoutFullPipeline executes the command in given directory with given timeout,
  147. // it pipes stdout and stderr to given io.Writer, and stdin from the given io.Reader
  148. func (c *Command) RunInDirTimeoutFullPipeline(timeout time.Duration, dir string, stdout, stderr io.Writer, stdin io.Reader) error {
  149. return c.RunInDirTimeoutEnvFullPipeline(nil, timeout, dir, stdout, stderr, stdin)
  150. }
  151. // RunInDirTimeout executes the command in given directory with given timeout,
  152. // and returns stdout in []byte and error (combined with stderr).
  153. func (c *Command) RunInDirTimeout(timeout time.Duration, dir string) ([]byte, error) {
  154. return c.RunInDirTimeoutEnv(nil, timeout, dir)
  155. }
  156. // RunInDirTimeoutEnv executes the command in given directory with given timeout,
  157. // and returns stdout in []byte and error (combined with stderr).
  158. func (c *Command) RunInDirTimeoutEnv(env []string, timeout time.Duration, dir string) ([]byte, error) {
  159. stdout := new(bytes.Buffer)
  160. stderr := new(bytes.Buffer)
  161. if err := c.RunInDirTimeoutEnvPipeline(env, timeout, dir, stdout, stderr); err != nil {
  162. return nil, ConcatenateError(err, stderr.String())
  163. }
  164. if stdout.Len() > 0 {
  165. log("stdout:\n%s", stdout.Bytes()[:1024])
  166. }
  167. return stdout.Bytes(), nil
  168. }
  169. // RunInDirPipeline executes the command in given directory,
  170. // it pipes stdout and stderr to given io.Writer.
  171. func (c *Command) RunInDirPipeline(dir string, stdout, stderr io.Writer) error {
  172. return c.RunInDirFullPipeline(dir, stdout, stderr, nil)
  173. }
  174. // RunInDirFullPipeline executes the command in given directory,
  175. // it pipes stdout and stderr to given io.Writer.
  176. func (c *Command) RunInDirFullPipeline(dir string, stdout, stderr io.Writer, stdin io.Reader) error {
  177. return c.RunInDirTimeoutFullPipeline(-1, dir, stdout, stderr, stdin)
  178. }
  179. // RunInDirBytes executes the command in given directory
  180. // and returns stdout in []byte and error (combined with stderr).
  181. func (c *Command) RunInDirBytes(dir string) ([]byte, error) {
  182. return c.RunInDirTimeout(-1, dir)
  183. }
  184. // RunInDir executes the command in given directory
  185. // and returns stdout in string and error (combined with stderr).
  186. func (c *Command) RunInDir(dir string) (string, error) {
  187. return c.RunInDirWithEnv(dir, nil)
  188. }
  189. // RunInDirWithEnv executes the command in given directory
  190. // and returns stdout in string and error (combined with stderr).
  191. func (c *Command) RunInDirWithEnv(dir string, env []string) (string, error) {
  192. stdout, err := c.RunInDirTimeoutEnv(env, -1, dir)
  193. if err != nil {
  194. return "", err
  195. }
  196. return string(stdout), nil
  197. }
  198. // RunTimeout executes the command in default working directory with given timeout,
  199. // and returns stdout in string and error (combined with stderr).
  200. func (c *Command) RunTimeout(timeout time.Duration) (string, error) {
  201. stdout, err := c.RunInDirTimeout(timeout, "")
  202. if err != nil {
  203. return "", err
  204. }
  205. return string(stdout), nil
  206. }
  207. // Run executes the command in default working directory
  208. // and returns stdout in string and error (combined with stderr).
  209. func (c *Command) Run() (string, error) {
  210. return c.RunTimeout(-1)
  211. }