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. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package git
  5. import (
  6. "bytes"
  7. "context"
  8. "fmt"
  9. "io"
  10. "os"
  11. "os/exec"
  12. "runtime"
  13. "strings"
  14. "time"
  15. "code.gitea.io/gitea/modules/process"
  16. "github.com/mcuadros/go-version"
  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(c.String())
  100. } else {
  101. log("%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 = append(os.Environ(), fmt.Sprintf("LC_ALL=%s", DefaultLocale))
  108. } else {
  109. cmd.Env = env
  110. cmd.Env = append(cmd.Env, fmt.Sprintf("LC_ALL=%s", DefaultLocale))
  111. }
  112. // TODO: verify if this is still needed in golang 1.15
  113. if version.Compare(runtime.Version(), "go1.15", "<") {
  114. cmd.Env = append(cmd.Env, "GODEBUG=asyncpreemptoff=1")
  115. }
  116. cmd.Dir = dir
  117. cmd.Stdout = stdout
  118. cmd.Stderr = stderr
  119. cmd.Stdin = stdin
  120. if err := cmd.Start(); err != nil {
  121. return err
  122. }
  123. desc := c.desc
  124. if desc == "" {
  125. desc = fmt.Sprintf("%s %s %s [repo_path: %s]", GitExecutable, c.name, strings.Join(c.args, " "), dir)
  126. }
  127. pid := process.GetManager().Add(desc, cancel)
  128. defer process.GetManager().Remove(pid)
  129. if fn != nil {
  130. err := fn(ctx, cancel)
  131. if err != nil {
  132. cancel()
  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. }