package deploy import ( "bytes" "context" "fmt" "os" "os/exec" "slices" "strings" "syscall" "time" ) const defaultGitTimeout = 10 * time.Minute func runGit(ctx context.Context, dir string, args ...string) (string, error) { cmd := exec.CommandContext(ctx, "git", append([]string{"-c", "http.lowSpeedLimit=1", "-c", "http.lowSpeedTime=60"}, args...)...) cmd.Dir = dir cmd.Env = append(os.Environ(), "GIT_TERMINAL_PROMPT=0") cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} cmd.Cancel = func() error { return syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL) } cmd.WaitDelay = 5 * time.Second var out, errb bytes.Buffer cmd.Stdout, cmd.Stderr = &out, &errb if err := cmd.Run(); err != nil { return "", fmt.Errorf("git %s: %w: %s", strings.Join(args, " "), err, strings.TrimSpace(errb.String())) } return strings.TrimSpace(out.String()), nil } // git holds a -j slot only for the subprocess itself, so callers never nest slots. func (d *Deployer) git(ctx context.Context, dir string, args ...string) (out string, err error) { err = d.limit(func() error { ctx, cancel := context.WithTimeout(ctx, d.gitTimeout) defer cancel() out, err = d.runGit(ctx, dir, args...) return err }) return out, err } func (d *Deployer) syncMirror(ctx context.Context, mirror, url string, opts, refspecs []string) error { if _, err := os.Stat(mirror); os.IsNotExist(err) { if _, err := d.git(ctx, "", "init", "-q", "--bare", "--", mirror); err != nil { return err } } args := slices.Concat(opts, []string{"fetch", "-q", "--prune", "--force", "--", url}, refspecs) _, err := d.git(ctx, mirror, args...) return err } func (d *Deployer) branches(ctx context.Context, mirror string) (map[string]string, error) { out, err := d.git(ctx, mirror, "for-each-ref", "--format=%(objectname) %(refname)", "refs/heads/") if err != nil { return nil, err } m := map[string]string{} for _, l := range strings.Split(out, "\n") { sha, ref, ok := strings.Cut(l, " ") if ok { m[strings.TrimPrefix(ref, "refs/heads/")] = sha } } return m, nil } func (d *Deployer) revParse(ctx context.Context, mirror string, candidates ...string) (string, error) { for _, c := range candidates { if sha, err := d.git(ctx, mirror, "rev-parse", "--verify", "--quiet", "--end-of-options", c+"^{commit}"); err == nil { return sha, nil } } return "", fmt.Errorf("cannot resolve %s", strings.Join(candidates, " or ")) } func (d *Deployer) removeWorktree(ctx context.Context, mirror, path string) error { _, _ = d.git(ctx, mirror, "worktree", "remove", "--force", "--", path) return os.RemoveAll(path) }