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.5KB

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