440 lines
11 KiB
Go
440 lines
11 KiB
Go
package git
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
"os/exec"
|
|
"path/filepath"
|
|
"slices"
|
|
"strconv"
|
|
"strings"
|
|
"syscall"
|
|
"time"
|
|
)
|
|
|
|
type RepoInfo struct {
|
|
Root string
|
|
DefaultBranch string
|
|
Remote string
|
|
}
|
|
|
|
func Inspect(path string) (RepoInfo, error) {
|
|
abs, err := filepath.Abs(path)
|
|
if err != nil {
|
|
return RepoInfo{}, err
|
|
}
|
|
|
|
root, err := run(abs, "rev-parse", "--show-toplevel")
|
|
if err != nil {
|
|
return RepoInfo{}, err
|
|
}
|
|
|
|
root, err = filepath.EvalSymlinks(root)
|
|
if err != nil {
|
|
return RepoInfo{}, err
|
|
}
|
|
|
|
abs, err = filepath.EvalSymlinks(abs)
|
|
if err != nil {
|
|
return RepoInfo{}, err
|
|
}
|
|
|
|
if root != abs {
|
|
return RepoInfo{}, fmt.Errorf("%s is inside the repo at %s; register the repo root", abs, root)
|
|
}
|
|
|
|
branch, err := run(root, "symbolic-ref", "--short", "HEAD")
|
|
if err != nil {
|
|
return RepoInfo{}, err
|
|
}
|
|
|
|
remote, err := run(root, "remote", "get-url", "origin")
|
|
if err != nil {
|
|
return RepoInfo{}, err
|
|
}
|
|
|
|
return RepoInfo{Root: root, DefaultBranch: branch, Remote: remote}, nil
|
|
}
|
|
|
|
func AddWorktree(repo, path, branch, base string) (string, error) {
|
|
sha, err := run(repo, "rev-parse", "--verify", base+"^{commit}")
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
_, err = run(repo, "worktree", "add", "-b", branch, path, sha)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
return sha, nil
|
|
}
|
|
|
|
func AddDetachedWorktree(repo, path, commit string) error {
|
|
_, err := run(repo, "worktree", "add", "--detach", path, commit)
|
|
return err
|
|
}
|
|
|
|
func RemoveDetachedWorktree(repo, path string) error {
|
|
_, err := os.Stat(path)
|
|
if errors.Is(err, os.ErrNotExist) {
|
|
return nil
|
|
}
|
|
_, err = run(repo, "worktree", "remove", "--force", path)
|
|
return err
|
|
}
|
|
|
|
func RemoveWorktree(repo, path, branch string) error {
|
|
list, err := run(repo, "worktree", "list", "--porcelain")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
_, statErr := os.Stat(path)
|
|
if statErr == nil || slices.Contains(strings.Split(list, "\n"), "worktree "+path) {
|
|
_, err = run(repo, "worktree", "remove", "--force", path)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
}
|
|
|
|
_, _, code, err := runCode(repo, nil, "rev-parse", "--verify", "--quiet", "refs/heads/"+branch)
|
|
if err != nil || code != 0 {
|
|
return err
|
|
}
|
|
_, err = run(repo, "branch", "-D", branch)
|
|
return err
|
|
}
|
|
|
|
type Unmerged struct {
|
|
Commits int
|
|
Files int
|
|
Insertions int
|
|
Deletions int
|
|
Uncommitted int
|
|
}
|
|
|
|
type ConflictError struct {
|
|
Files []string
|
|
}
|
|
|
|
func (e *ConflictError) Error() string {
|
|
return "merge conflicts in " + strings.Join(e.Files, ", ")
|
|
}
|
|
|
|
func UnmergedChanges(worktree, target string) (Unmerged, error) {
|
|
u := Unmerged{}
|
|
|
|
count, err := run(worktree, "rev-list", "--count", target+"..HEAD")
|
|
if err != nil {
|
|
return u, err
|
|
}
|
|
u.Commits, err = strconv.Atoi(count)
|
|
if err != nil {
|
|
return u, err
|
|
}
|
|
|
|
status, err := run(worktree, "status", "--porcelain", "--untracked-files=all")
|
|
if err != nil {
|
|
return u, err
|
|
}
|
|
if status != "" {
|
|
u.Uncommitted = len(strings.Split(status, "\n"))
|
|
}
|
|
|
|
tree, err := Snapshot(worktree)
|
|
if err != nil {
|
|
return u, err
|
|
}
|
|
base, err := run(worktree, "merge-base", target, "HEAD")
|
|
if err != nil {
|
|
return u, err
|
|
}
|
|
numstat, err := run(worktree, "diff", "--numstat", base, tree)
|
|
if err != nil {
|
|
return u, err
|
|
}
|
|
for _, line := range strings.Split(numstat, "\n") {
|
|
if line == "" {
|
|
continue
|
|
}
|
|
fields := strings.SplitN(line, "\t", 3)
|
|
u.Files++
|
|
adds, err := strconv.Atoi(fields[0])
|
|
if err != nil {
|
|
continue
|
|
}
|
|
dels, err := strconv.Atoi(fields[1])
|
|
if err != nil {
|
|
continue
|
|
}
|
|
u.Insertions += adds
|
|
u.Deletions += dels
|
|
}
|
|
|
|
return u, nil
|
|
}
|
|
|
|
func SquashCommit(repo, worktree, target, message string, env []string) (string, error) {
|
|
checkedOut, err := run(repo, "symbolic-ref", "--short", "HEAD")
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if checkedOut != target {
|
|
return "", fmt.Errorf("%s has %s checked out, not %s", repo, checkedOut, target)
|
|
}
|
|
|
|
tree, err := Snapshot(worktree)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
base, err := run(worktree, "merge-base", target, "HEAD")
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
head, err := run(repo, "rev-parse", target)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
out, stderr, code, err := runCode(repo, nil, "merge-tree", "--write-tree", "--name-only", "--merge-base="+base, head, tree)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
lines := strings.Split(out, "\n")
|
|
if code == 1 {
|
|
conflict := &ConflictError{}
|
|
for _, l := range lines[1:] {
|
|
if l == "" {
|
|
break
|
|
}
|
|
conflict.Files = append(conflict.Files, l)
|
|
}
|
|
return "", conflict
|
|
}
|
|
if code != 0 {
|
|
return "", fmt.Errorf("git merge-tree exited %d: %s", code, stderr)
|
|
}
|
|
|
|
headTree, err := run(repo, "rev-parse", head+"^{tree}")
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if lines[0] == headTree {
|
|
return "", nil
|
|
}
|
|
|
|
args := []string{"commit-tree", lines[0], "-p", head, "-m", message}
|
|
sign, stderr, code, err := runCode(repo, nil, "config", "--type=bool", "--get", "commit.gpgsign")
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if code != 0 && code != 1 {
|
|
return "", fmt.Errorf("git config --get commit.gpgsign: exit status %d: %s", code, stderr)
|
|
}
|
|
if sign == "true" {
|
|
args = append(args, "-S")
|
|
}
|
|
return runEnv(repo, env, args...)
|
|
}
|
|
|
|
const Remote = "origin"
|
|
|
|
const networkTimeout = 2 * time.Minute
|
|
|
|
var networkEnv = []string{
|
|
"GIT_TERMINAL_PROMPT=0",
|
|
"GIT_SSH_COMMAND=ssh -o BatchMode=yes -o ConnectTimeout=30",
|
|
}
|
|
|
|
var ErrRemoteMoved = errors.New("the remote's branch has moved")
|
|
|
|
func Push(ctx context.Context, repo, commit, branch, notes string) error {
|
|
out, stderr, code, err := runNetwork(ctx, repo, "push", "--atomic", "--porcelain", Remote, commit+":refs/heads/"+branch, notes+":"+NotesRef)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if code == 0 {
|
|
return nil
|
|
}
|
|
for _, line := range strings.Split(out, "\n") {
|
|
if strings.HasPrefix(line, "!") && strings.Contains(line, "[rejected]") && (strings.Contains(line, "(fetch first)") || strings.Contains(line, "(non-fast-forward)")) {
|
|
return fmt.Errorf("pushing %s to %s: %w", branch, Remote, ErrRemoteMoved)
|
|
}
|
|
}
|
|
return fmt.Errorf("pushing %s to %s: exit status %d: %s", branch, Remote, code, strings.TrimSpace(out+"\n"+stderr))
|
|
}
|
|
|
|
func FastForward(repo, rev string) error {
|
|
_, err := run(repo, "merge", "--ff-only", rev)
|
|
return err
|
|
}
|
|
|
|
func Fetch(ctx context.Context, repo string) error {
|
|
_, stderr, code, err := runNetwork(ctx, repo, "fetch", Remote)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if code != 0 {
|
|
return fmt.Errorf("git fetch %s: exit status %d: %s", Remote, code, stderr)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func FetchFastForward(ctx context.Context, repo, branch string) error {
|
|
err := Fetch(ctx, repo)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return FastForward(repo, Remote+"/"+branch)
|
|
}
|
|
|
|
func Head(dir string) (string, error) {
|
|
return run(dir, "rev-parse", "HEAD")
|
|
}
|
|
|
|
func IsAncestor(dir, ancestor, descendant string) (bool, error) {
|
|
_, stderr, code, err := runCode(dir, nil, "merge-base", "--is-ancestor", ancestor, descendant)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
switch code {
|
|
case 0:
|
|
return true, nil
|
|
case 1:
|
|
return false, nil
|
|
}
|
|
return false, fmt.Errorf("git merge-base --is-ancestor %s %s: exit status %d: %s", ancestor, descendant, code, stderr)
|
|
}
|
|
|
|
func MergeInProgress(dir string) (bool, error) {
|
|
_, _, code, err := runCode(dir, nil, "rev-parse", "--quiet", "--verify", "MERGE_HEAD")
|
|
return err == nil && code == 0, err
|
|
}
|
|
|
|
func AbortMerge(dir string) error {
|
|
merging, err := MergeInProgress(dir)
|
|
if err != nil || !merging {
|
|
return err
|
|
}
|
|
_, err = run(dir, "merge", "--abort")
|
|
return err
|
|
}
|
|
|
|
func ReadFile(repo, rev, path string) (string, bool, error) {
|
|
_, _, code, err := runCode(repo, nil, "cat-file", "-e", rev+":"+path)
|
|
if err != nil {
|
|
return "", false, err
|
|
}
|
|
if code != 0 {
|
|
return "", false, nil
|
|
}
|
|
out, err := run(repo, "cat-file", "blob", rev+":"+path)
|
|
return out, true, err
|
|
}
|
|
|
|
func CommitAll(dir, message, name, email string) (string, error) {
|
|
status, err := run(dir, "status", "--porcelain", "--untracked-files=all")
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
merging, err := MergeInProgress(dir)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if status == "" && !merging {
|
|
return "", nil
|
|
}
|
|
|
|
env := []string{
|
|
"GIT_AUTHOR_NAME=" + name,
|
|
"GIT_AUTHOR_EMAIL=" + email,
|
|
"GIT_COMMITTER_NAME=" + name,
|
|
"GIT_COMMITTER_EMAIL=" + email,
|
|
}
|
|
_, err = runEnv(dir, env, "add", "--all")
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
_, err = runEnv(dir, env, "commit", "--quiet", "--message", message)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return Head(dir)
|
|
}
|
|
|
|
func Merge(dir, rev, message, name, email string) error {
|
|
env := []string{
|
|
"GIT_AUTHOR_NAME=" + name,
|
|
"GIT_AUTHOR_EMAIL=" + email,
|
|
"GIT_COMMITTER_NAME=" + name,
|
|
"GIT_COMMITTER_EMAIL=" + email,
|
|
}
|
|
_, err := runEnv(dir, env, "merge", "--no-ff", "--quiet", "--message", message, rev)
|
|
return err
|
|
}
|
|
|
|
func run(dir string, args ...string) (string, error) {
|
|
return runEnv(dir, nil, args...)
|
|
}
|
|
|
|
func runEnv(dir string, env []string, args ...string) (string, error) {
|
|
out, stderr, code, err := runCode(dir, env, args...)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if code != 0 {
|
|
return "", fmt.Errorf("git %s: exit status %d: %s", strings.Join(args, " "), code, stderr)
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
func runInput(dir string, env []string, input string, args ...string) (string, error) {
|
|
out, stderr, code, err := runCodeInput(context.Background(), dir, env, strings.NewReader(input), args...)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if code != 0 {
|
|
return "", fmt.Errorf("git %s: exit status %d: %s", strings.Join(args, " "), code, stderr)
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
func runCode(dir string, env []string, args ...string) (string, string, int, error) {
|
|
return runCodeInput(context.Background(), dir, env, nil, args...)
|
|
}
|
|
|
|
func runNetwork(ctx context.Context, dir string, args ...string) (string, string, int, error) {
|
|
ctx, cancel := context.WithTimeout(ctx, networkTimeout)
|
|
defer cancel()
|
|
return runCodeInput(ctx, dir, networkEnv, nil, args...)
|
|
}
|
|
|
|
func runCodeInput(ctx context.Context, dir string, env []string, stdin io.Reader, args ...string) (string, string, int, error) {
|
|
cmd := exec.CommandContext(ctx, "git", args...)
|
|
cmd.Dir = dir
|
|
cmd.Env = append(os.Environ(), env...)
|
|
cmd.Stdin = stdin
|
|
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
|
|
cmd.Cancel = func() error {
|
|
return syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
|
|
}
|
|
cmd.WaitDelay = 5 * time.Second
|
|
stderr := &strings.Builder{}
|
|
cmd.Stderr = stderr
|
|
out, err := cmd.Output()
|
|
if ctx.Err() != nil {
|
|
return "", "", 0, fmt.Errorf("git %s: %w: %s", strings.Join(args, " "), context.Cause(ctx), strings.TrimSpace(stderr.String()))
|
|
}
|
|
exit := &exec.ExitError{}
|
|
if errors.As(err, &exit) {
|
|
return strings.TrimSpace(string(out)), strings.TrimSpace(stderr.String()), exit.ExitCode(), nil
|
|
}
|
|
if err != nil {
|
|
return "", "", 0, fmt.Errorf("git %s: %w", strings.Join(args, " "), err)
|
|
}
|
|
return strings.TrimSpace(string(out)), strings.TrimSpace(stderr.String()), 0, nil
|
|
}
|