| 1 | // Package subprocess provides helper functions for forking new processes |
| 2 | // NOTE: Subject to change, do not rely on this package from outside git-lfs source |
| 3 | package subprocess |
| 4 | |
| 5 | import ( |
| 6 | "bufio" |
| 7 | "errors" |
| 8 | "fmt" |
| 9 | "os" |
| 10 | "os/exec" |
| 11 | "regexp" |
| 12 | "strings" |
| 13 | "sync" |
| 14 | |
| 15 | "github.com/git-lfs/git-lfs/v3/tr" |
| 16 | "github.com/rubyist/tracerx" |
| 17 | ) |
| 18 | |
| 19 | // BufferedExec starts up a command and creates a stdin pipe and a buffered |
| 20 | // stdout & stderr pipes, wrapped in a BufferedCmd. The stdout buffer will be |
| 21 | // of stdoutBufSize bytes. |
| 22 | func BufferedExec(name string, args ...string) (*BufferedCmd, error) { |
| 23 | cmd, err := ExecCommand(name, args...) |
| 24 | if err != nil { |
| 25 | return nil, err |
| 26 | } |
| 27 | stdout, err := cmd.StdoutPipe() |
| 28 | if err != nil { |
| 29 | return nil, err |
| 30 | } |
| 31 | stderr, err := cmd.StderrPipe() |
| 32 | if err != nil { |
| 33 | return nil, err |
| 34 | } |
| 35 | |
| 36 | stdin, err := cmd.StdinPipe() |
| 37 | if err != nil { |
| 38 | return nil, err |
| 39 | } |
| 40 | |
| 41 | if err := cmd.Start(); err != nil { |
| 42 | return nil, err |
| 43 | } |
| 44 | |
| 45 | return &BufferedCmd{ |
| 46 | cmd, |
| 47 | stdin, |
| 48 | bufio.NewReaderSize(stdout, stdoutBufSize), |
| 49 | bufio.NewReaderSize(stderr, stdoutBufSize), |
| 50 | }, nil |
| 51 | } |
| 52 | |
| 53 | // StdoutBufferedExec starts up a command and creates a stdin pipe and a |
| 54 | // buffered stdout pipe, with stderr directed to /dev/null, wrapped in a |
| 55 | // BufferedCmd. The stdout buffer will be of stdoutBufSize bytes. |
| 56 | func StdoutBufferedExec(name string, args ...string) (*BufferedCmd, error) { |
| 57 | cmd, err := ExecCommand(name, args...) |
| 58 | if err != nil { |
| 59 | return nil, err |
| 60 | } |
| 61 | stdout, err := cmd.StdoutPipe() |
| 62 | if err != nil { |
| 63 | return nil, err |
| 64 | } |
| 65 | |
| 66 | stdin, err := cmd.StdinPipe() |
| 67 | if err != nil { |
| 68 | return nil, err |
| 69 | } |
| 70 | |
| 71 | if err := cmd.Start(); err != nil { |
| 72 | return nil, err |
| 73 | } |
| 74 | |
| 75 | return &BufferedCmd{ |
| 76 | cmd, |
| 77 | stdin, |
| 78 | bufio.NewReaderSize(stdout, stdoutBufSize), |
| 79 | nil, |
| 80 | }, nil |
| 81 | } |
| 82 | |
| 83 | // SimpleExec is a small wrapper around os/exec.Command. |
| 84 | func SimpleExec(name string, args ...string) (string, error) { |
| 85 | cmd, err := ExecCommand(name, args...) |
| 86 | if err != nil { |
| 87 | return "", err |
| 88 | } |
| 89 | return Output(cmd) |
| 90 | } |
| 91 | |
| 92 | func Output(cmd *Cmd) (string, error) { |
| 93 | out, err := cmd.Output() |
| 94 | |
| 95 | if exitError, ok := err.(*exec.ExitError); ok { |
| 96 | errorOutput := strings.TrimSpace(string(exitError.Stderr)) |
| 97 | if errorOutput == "" { |
| 98 | // some commands might write nothing to stderr but something to stdout in error-conditions, in which case, we'll use that |
| 99 | // in the error string |
| 100 | errorOutput = strings.TrimSpace(string(out)) |
| 101 | } |
| 102 | |
| 103 | ran := cmd.Path |
| 104 | if len(cmd.Args) > 1 { |
| 105 | ran = fmt.Sprintf("%s %s", cmd.Path, quotedArgs(cmd.Args[1:])) |
| 106 | } |
| 107 | formattedErr := errors.New(tr.Tr.Get("error running %s: '%s' '%s'", ran, errorOutput, strings.TrimSpace(exitError.Error()))) |
| 108 | |
| 109 | // return "" as output in error case, for callers that don't care about errors but rely on "" returned, in-case stdout != "" |
| 110 | return "", formattedErr |
| 111 | } |
| 112 | |
| 113 | return strings.Trim(string(out), " \n"), err |
| 114 | } |
| 115 | |
| 116 | var shellWordRe = regexp.MustCompile(`\A[A-Za-z0-9_@/.-]+\z`) |
| 117 | |
| 118 | // ShellQuoteSingle returns a string which is quoted suitably for sh. |
| 119 | func ShellQuoteSingle(str string) string { |
| 120 | // Quote anything that looks slightly complicated. |
| 121 | if shellWordRe.FindStringIndex(str) == nil { |
| 122 | return "'" + strings.Replace(str, "'", "'\\''", -1) + "'" |
| 123 | } |
| 124 | return str |
| 125 | } |
| 126 | |
| 127 | // ShellQuote returns a copied string slice where each element is quoted |
| 128 | // suitably for sh. |
| 129 | func ShellQuote(strs []string) []string { |
| 130 | dup := make([]string, 0, len(strs)) |
| 131 | |
| 132 | for _, str := range strs { |
| 133 | dup = append(dup, ShellQuoteSingle(str)) |
| 134 | } |
| 135 | return dup |
| 136 | } |
| 137 | |
| 138 | // FormatForShell takes a command name and an argument string and returns a |
| 139 | // command and arguments that pass this command to the shell. Note that neither |
| 140 | // the command nor the arguments are quoted. Consider FormatForShellQuoted |
| 141 | // instead. |
| 142 | func FormatForShell(name string, args string) (string, []string) { |
| 143 | return "sh", []string{"-c", name + " " + args} |
| 144 | } |
| 145 | |
| 146 | // FormatForShellQuotedArgs takes a command name and an argument string and |
| 147 | // returns a command and arguments that pass this command to the shell. The |
| 148 | // arguments are escaped, but the name of the command is not. |
| 149 | func FormatForShellQuotedArgs(name string, args []string) (string, []string) { |
| 150 | return FormatForShell(name, strings.Join(ShellQuote(args), " ")) |
| 151 | } |
| 152 | |
| 153 | func FormatPercentSequences(pattern string, replacements map[string]string) string { |
| 154 | s := new(strings.Builder) |
| 155 | state := 0 |
| 156 | for _, r := range pattern { |
| 157 | if state == 0 && r == '%' { |
| 158 | state = 1 |
| 159 | continue |
| 160 | } else if state == 1 { |
| 161 | state = 0 |
| 162 | if r == '%' { |
| 163 | s.WriteRune('%') |
| 164 | } else if val, ok := replacements[string([]rune{r})]; ok { |
| 165 | s.WriteString(ShellQuoteSingle(val)) |
| 166 | } |
| 167 | } else { |
| 168 | s.WriteRune(r) |
| 169 | } |
| 170 | } |
| 171 | return s.String() |
| 172 | } |
| 173 | |
| 174 | func Trace(name string, args ...string) { |
| 175 | tracerx.Printf("exec: %s %s", name, quotedArgs(args)) |
| 176 | } |
| 177 | |
| 178 | func quotedArgs(args []string) string { |
| 179 | if len(args) == 0 { |
| 180 | return "" |
| 181 | } |
| 182 | |
| 183 | quoted := make([]string, len(args)) |
| 184 | for i, arg := range args { |
| 185 | quoted[i] = fmt.Sprintf("'%s'", arg) |
| 186 | } |
| 187 | return strings.Join(quoted, " ") |
| 188 | } |
| 189 | |
| 190 | // An env for an exec.Command without GIT_TRACE and GIT_INTERNAL_SUPER_PREFIX |
| 191 | var env []string |
| 192 | var envMu sync.Mutex |
| 193 | var traceEnv = "GIT_TRACE=" |
| 194 | |
| 195 | // Don't pass GIT_INTERNAL_SUPER_PREFIX back to Git. Git passes this environment |
| 196 | // variable to child processes when submodule.recurse is set to true. However, |
| 197 | // passing that environment variable back to Git will cause it to append the |
| 198 | // --super-prefix command-line option to every Git call. This is problematic |
| 199 | // because many Git commands (including git config and git rev-parse) don't |
| 200 | // support --super-prefix and would immediately exit with an error as a result. |
| 201 | var superPrefixEnv = "GIT_INTERNAL_SUPER_PREFIX=" |
| 202 | |
| 203 | func fetchEnvironment() []string { |
| 204 | envMu.Lock() |
| 205 | defer envMu.Unlock() |
| 206 | |
| 207 | return fetchEnvironmentInternal() |
| 208 | } |
| 209 | |
| 210 | // fetchEnvironmentInternal should only be called from fetchEnvironment or |
| 211 | // ResetEnvironment, who will hold the required lock. |
| 212 | func fetchEnvironmentInternal() []string { |
| 213 | if env != nil { |
| 214 | return env |
| 215 | } |
| 216 | |
| 217 | realEnv := os.Environ() |
| 218 | env = make([]string, 0, len(realEnv)) |
| 219 | |
| 220 | for _, kv := range realEnv { |
| 221 | if strings.HasPrefix(kv, traceEnv) || strings.HasPrefix(kv, superPrefixEnv) { |
| 222 | continue |
| 223 | } |
| 224 | env = append(env, kv) |
| 225 | } |
| 226 | return env |
| 227 | } |
| 228 | |
| 229 | // ResetEnvironment resets the cached environment that's used in subprocess |
| 230 | // calls. |
| 231 | func ResetEnvironment() { |
| 232 | envMu.Lock() |
| 233 | defer envMu.Unlock() |
| 234 | |
| 235 | env = nil |
| 236 | // Reinitialize the environment settings. |
| 237 | fetchEnvironmentInternal() |
| 238 | } |