63 lines
1.8 KiB
Go
63 lines
1.8 KiB
Go
package deploy
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"fmt"
|
|
"os"
|
|
"os/exec"
|
|
"strings"
|
|
)
|
|
|
|
func git(ctx context.Context, dir string, args ...string) (string, error) {
|
|
cmd := exec.CommandContext(ctx, "git", args...)
|
|
cmd.Dir = dir
|
|
cmd.Env = append(os.Environ(), "GIT_TERMINAL_PROMPT=0")
|
|
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
|
|
}
|
|
|
|
func syncMirror(ctx context.Context, mirror, url string, refspecs ...string) error {
|
|
if _, err := os.Stat(mirror); os.IsNotExist(err) {
|
|
if _, err := git(ctx, "", "init", "-q", "--bare", mirror); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
args := append([]string{"fetch", "-q", "--prune", "--force", url}, refspecs...)
|
|
_, err := git(ctx, mirror, args...)
|
|
return err
|
|
}
|
|
|
|
func branches(ctx context.Context, mirror string) (map[string]string, error) {
|
|
out, err := 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 revParse(ctx context.Context, mirror string, candidates ...string) (string, error) {
|
|
for _, c := range candidates {
|
|
if sha, err := git(ctx, mirror, "rev-parse", "--verify", "--quiet", c+"^{commit}"); err == nil {
|
|
return sha, nil
|
|
}
|
|
}
|
|
return "", fmt.Errorf("cannot resolve %s", strings.Join(candidates, " or "))
|
|
}
|
|
|
|
func removeWorktree(ctx context.Context, mirror, path string) error {
|
|
_, _ = git(ctx, mirror, "worktree", "remove", "--force", path)
|
|
return os.RemoveAll(path)
|
|
}
|