Run executes a git command with the specified arguments in the given path and returns its output or an error. If path is empty, the command runs without -C (use for commands like `clone` that take an explicit destination). Use it to run one-off git commands that don't fit into the other helper funct
(ctx context.Context, path string, args ...string)
| 214 | // If path is empty, the command runs without -C (use for commands like `clone` that take an explicit destination). |
| 215 | // Use it to run one-off git commands that don't fit into the other helper functions in this package. |
| 216 | func Run(ctx context.Context, path string, args ...string) (string, error) { |
| 217 | fullArgs := args |
| 218 | if path != "" { |
| 219 | fullArgs = append([]string{"-C", path}, args...) |
| 220 | } |
| 221 | var stdout, stderr bytes.Buffer |
| 222 | cmd := exec.CommandContext(ctx, "git", fullArgs...) |
| 223 | // Force English error messages so stderr substring checks are stable, and disable interactive credential prompts. |
| 224 | cmd.Env = append(os.Environ(), "LC_ALL=C", "GIT_TERMINAL_PROMPT=0") |
| 225 | cmd.Stdout = &stdout |
| 226 | cmd.Stderr = &stderr |
| 227 | if err := cmd.Run(); err != nil { |
| 228 | // Redact credentials: args and git's stderr may contain credential-embedded remote URLs. |
| 229 | msg := fmt.Sprintf("git %s: %s", strings.Join(args, " "), strings.TrimSpace(stderr.String())) |
| 230 | return "", fmt.Errorf("%s(%w)", redactURLCredentials(msg), err) |
| 231 | } |
| 232 | return strings.TrimSpace(stdout.String()), nil |
| 233 | } |
| 234 | |
| 235 | // urlCredentialsRegexp matches the userinfo component of a URL (e.g. "https://user:token@host"). |
| 236 | var urlCredentialsRegexp = regexp.MustCompile(`([a-zA-Z][a-zA-Z0-9+.-]*://)[^@/\s]+@`) |