github.com/gitbundle/modules@v0.0.0-20231025071548-85b91c5c3b01/git/command.go (about)

     1  // Copyright 2023 The GitBundle Inc. All rights reserved.
     2  // Copyright 2017 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  
     6  // Copyright 2015 The Gogs Authors. All rights reserved.
     7  // Copyright 2016 The GitBundle Authors. All rights reserved.
     8  // Use of this source code is governed by a MIT-style
     9  // license that can be found in the LICENSE file.
    10  
    11  package git
    12  
    13  import (
    14  	"bytes"
    15  	"context"
    16  	"errors"
    17  	"fmt"
    18  	"io"
    19  	"os"
    20  	"os/exec"
    21  	"strings"
    22  	"time"
    23  	"unsafe"
    24  
    25  	"github.com/gitbundle/modules/process"
    26  	"github.com/gitbundle/modules/util"
    27  )
    28  
    29  var (
    30  	// globalCommandArgs global command args for external package setting
    31  	globalCommandArgs []string
    32  
    33  	// defaultCommandExecutionTimeout default command execution timeout duration
    34  	defaultCommandExecutionTimeout = 360 * time.Second
    35  )
    36  
    37  // DefaultLocale is the default LC_ALL to run git commands in.
    38  const DefaultLocale = "C"
    39  
    40  // Command represents a command with its subcommands or arguments.
    41  type Command struct {
    42  	name             string
    43  	args             []string
    44  	parentContext    context.Context
    45  	desc             string
    46  	globalArgsLength int
    47  }
    48  
    49  func (c *Command) String() string {
    50  	if len(c.args) == 0 {
    51  		return c.name
    52  	}
    53  	return fmt.Sprintf("%s %s", c.name, strings.Join(c.args, " "))
    54  }
    55  
    56  // NewCommand creates and returns a new Git Command based on given command and arguments.
    57  func NewCommand(ctx context.Context, args ...string) *Command {
    58  	// Make an explicit copy of globalCommandArgs, otherwise append might overwrite it
    59  	cargs := make([]string, len(globalCommandArgs))
    60  	copy(cargs, globalCommandArgs)
    61  	return &Command{
    62  		name:             GitExecutable,
    63  		args:             append(cargs, args...),
    64  		parentContext:    ctx,
    65  		globalArgsLength: len(globalCommandArgs),
    66  	}
    67  }
    68  
    69  // 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
    70  func NewCommandNoGlobals(args ...string) *Command {
    71  	return NewCommandContextNoGlobals(DefaultContext, args...)
    72  }
    73  
    74  // 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
    75  func NewCommandContextNoGlobals(ctx context.Context, args ...string) *Command {
    76  	return &Command{
    77  		name:          GitExecutable,
    78  		args:          args,
    79  		parentContext: ctx,
    80  	}
    81  }
    82  
    83  // SetParentContext sets the parent context for this command
    84  func (c *Command) SetParentContext(ctx context.Context) *Command {
    85  	c.parentContext = ctx
    86  	return c
    87  }
    88  
    89  // SetDescription sets the description for this command which be returned on
    90  // c.String()
    91  func (c *Command) SetDescription(desc string) *Command {
    92  	c.desc = desc
    93  	return c
    94  }
    95  
    96  // AddArguments adds new argument(s) to the command.
    97  func (c *Command) AddArguments(args ...string) *Command {
    98  	c.args = append(c.args, args...)
    99  	return c
   100  }
   101  
   102  // RunOpts represents parameters to run the command. If UseContextTimeout is specified, then Timeout is ignored.
   103  type RunOpts struct {
   104  	Env               []string
   105  	Timeout           time.Duration
   106  	UseContextTimeout bool
   107  	Dir               string
   108  	Stdout, Stderr    io.Writer
   109  	Stdin             io.Reader
   110  	PipelineFunc      func(context.Context, context.CancelFunc) error
   111  }
   112  
   113  func commonBaseEnvs() []string {
   114  	// at the moment, do not set "GIT_CONFIG_NOSYSTEM", users may have put some configs like "receive.certNonceSeed" in it
   115  	envs := []string{
   116  		"HOME=" + HomeDir(),        // make GitBundle use internal git config only, to prevent conflicts with user's git config
   117  		"GIT_NO_REPLACE_OBJECTS=1", // ignore replace references (https://git-scm.com/docs/git-replace)
   118  	}
   119  
   120  	// some environment variables should be passed to git command
   121  	passThroughEnvKeys := []string{
   122  		"GNUPGHOME", // git may call gnupg to do commit signing
   123  	}
   124  	for _, key := range passThroughEnvKeys {
   125  		if val, ok := os.LookupEnv(key); ok {
   126  			envs = append(envs, key+"="+val)
   127  		}
   128  	}
   129  	return envs
   130  }
   131  
   132  // CommonGitCmdEnvs returns the common environment variables for a "git" command.
   133  func CommonGitCmdEnvs() []string {
   134  	return append(commonBaseEnvs(), []string{
   135  		"LC_ALL=" + DefaultLocale,
   136  		"GIT_TERMINAL_PROMPT=0", // avoid prompting for credentials interactively, supported since git v2.3
   137  	}...)
   138  }
   139  
   140  // CommonCmdServEnvs is like CommonGitCmdEnvs but it only returns minimal required environment variables for the "gitbundle serv" command
   141  func CommonCmdServEnvs() []string {
   142  	return commonBaseEnvs()
   143  }
   144  
   145  // Run runs the command with the RunOpts
   146  func (c *Command) Run(opts *RunOpts) error {
   147  	if opts == nil {
   148  		opts = &RunOpts{}
   149  	}
   150  	if opts.Timeout <= 0 {
   151  		opts.Timeout = defaultCommandExecutionTimeout
   152  	}
   153  
   154  	// NOTE: remove trace log
   155  	// if log.IsTrace() {
   156  	// 	if len(opts.Dir) == 0 {
   157  	// 		log.Trace("%s", c)
   158  	// 	} else {
   159  	// 		log.Trace("%s: %v", opts.Dir, c)
   160  	// 	}
   161  	// }
   162  
   163  	desc := c.desc
   164  	if desc == "" {
   165  		args := c.args[c.globalArgsLength:]
   166  		var argSensitiveURLIndexes []int
   167  		for i, arg := range c.args {
   168  			if strings.Contains(arg, "://") && strings.Contains(arg, "@") {
   169  				argSensitiveURLIndexes = append(argSensitiveURLIndexes, i)
   170  			}
   171  		}
   172  		if len(argSensitiveURLIndexes) > 0 {
   173  			args = make([]string, len(c.args))
   174  			copy(args, c.args)
   175  			for _, urlArgIndex := range argSensitiveURLIndexes {
   176  				args[urlArgIndex] = util.SanitizeCredentialURLs(args[urlArgIndex])
   177  			}
   178  		}
   179  		desc = fmt.Sprintf("%s %s [repo_path: %s]", c.name, strings.Join(args, " "), opts.Dir)
   180  	}
   181  
   182  	var ctx context.Context
   183  	var cancel context.CancelFunc
   184  	var finished context.CancelFunc
   185  
   186  	if opts.UseContextTimeout {
   187  		ctx, cancel, finished = process.GetManager().AddContext(c.parentContext, desc)
   188  	} else {
   189  		ctx, cancel, finished = process.GetManager().AddContextTimeout(c.parentContext, opts.Timeout, desc)
   190  	}
   191  	defer finished()
   192  
   193  	cmd := exec.CommandContext(ctx, c.name, c.args...)
   194  	if opts.Env == nil {
   195  		cmd.Env = os.Environ()
   196  	} else {
   197  		cmd.Env = opts.Env
   198  	}
   199  
   200  	process.SetSysProcAttribute(cmd)
   201  	cmd.Env = append(cmd.Env, CommonGitCmdEnvs()...)
   202  	cmd.Dir = opts.Dir
   203  	cmd.Stdout = opts.Stdout
   204  	cmd.Stderr = opts.Stderr
   205  	cmd.Stdin = opts.Stdin
   206  	if err := cmd.Start(); err != nil {
   207  		return err
   208  	}
   209  
   210  	if opts.PipelineFunc != nil {
   211  		err := opts.PipelineFunc(ctx, cancel)
   212  		if err != nil {
   213  			cancel()
   214  			_ = cmd.Wait()
   215  			return err
   216  		}
   217  	}
   218  
   219  	if err := cmd.Wait(); err != nil && ctx.Err() != context.DeadlineExceeded {
   220  		return err
   221  	}
   222  
   223  	return ctx.Err()
   224  }
   225  
   226  type RunStdError interface {
   227  	error
   228  	Unwrap() error
   229  	Stderr() string
   230  	IsExitCode(code int) bool
   231  }
   232  
   233  type runStdError struct {
   234  	err    error
   235  	stderr string
   236  	errMsg string
   237  }
   238  
   239  func (r *runStdError) Error() string {
   240  	// the stderr must be in the returned error text, some code only checks `strings.Contains(err.Error(), "git error")`
   241  	if r.errMsg == "" {
   242  		r.errMsg = ConcatenateError(r.err, r.stderr).Error()
   243  	}
   244  	return r.errMsg
   245  }
   246  
   247  func (r *runStdError) Unwrap() error {
   248  	return r.err
   249  }
   250  
   251  func (r *runStdError) Stderr() string {
   252  	return r.stderr
   253  }
   254  
   255  func (r *runStdError) IsExitCode(code int) bool {
   256  	var exitError *exec.ExitError
   257  	if errors.As(r.err, &exitError) {
   258  		return exitError.ExitCode() == code
   259  	}
   260  	return false
   261  }
   262  
   263  func bytesToString(b []byte) string {
   264  	return *(*string)(unsafe.Pointer(&b)) // that's what Golang's strings.Builder.String() does (go/src/strings/builder.go)
   265  }
   266  
   267  // RunStdString runs the command with options and returns stdout/stderr as string. and store stderr to returned error (err combined with stderr).
   268  func (c *Command) RunStdString(opts *RunOpts) (stdout, stderr string, runErr RunStdError) {
   269  	stdoutBytes, stderrBytes, err := c.RunStdBytes(opts)
   270  	stdout = bytesToString(stdoutBytes)
   271  	stderr = bytesToString(stderrBytes)
   272  	if err != nil {
   273  		return stdout, stderr, &runStdError{err: err, stderr: stderr}
   274  	}
   275  	// even if there is no err, there could still be some stderr output, so we just return stdout/stderr as they are
   276  	return stdout, stderr, nil
   277  }
   278  
   279  // RunStdBytes runs the command with options and returns stdout/stderr as bytes. and store stderr to returned error (err combined with stderr).
   280  func (c *Command) RunStdBytes(opts *RunOpts) (stdout, stderr []byte, runErr RunStdError) {
   281  	if opts == nil {
   282  		opts = &RunOpts{}
   283  	}
   284  	if opts.Stdout != nil || opts.Stderr != nil {
   285  		// we must panic here, otherwise there would be bugs if developers set Stdin/Stderr by mistake, and it would be very difficult to debug
   286  		panic("stdout and stderr field must be nil when using RunStdBytes")
   287  	}
   288  	stdoutBuf := &bytes.Buffer{}
   289  	stderrBuf := &bytes.Buffer{}
   290  	opts.Stdout = stdoutBuf
   291  	opts.Stderr = stderrBuf
   292  	err := c.Run(opts)
   293  	stderr = stderrBuf.Bytes()
   294  	if err != nil {
   295  		return nil, stderr, &runStdError{err: err, stderr: bytesToString(stderr)}
   296  	}
   297  	// even if there is no err, there could still be some stderr output
   298  	return stdoutBuf.Bytes(), stderr, nil
   299  }
   300  
   301  // AllowLFSFiltersArgs return globalCommandArgs with lfs filter, it should only be used for tests
   302  func AllowLFSFiltersArgs() []string {
   303  	// Now here we should explicitly allow lfs filters to run
   304  	filteredLFSGlobalArgs := make([]string, len(globalCommandArgs))
   305  	j := 0
   306  	for _, arg := range globalCommandArgs {
   307  		if strings.Contains(arg, "lfs") {
   308  			j--
   309  		} else {
   310  			filteredLFSGlobalArgs[j] = arg
   311  			j++
   312  		}
   313  	}
   314  	return filteredLFSGlobalArgs[:j]
   315  }