322 lines
7.2 KiB
Go
322 lines
7.2 KiB
Go
package git
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
"os/exec"
|
|
"path/filepath"
|
|
"strconv"
|
|
"strings"
|
|
)
|
|
|
|
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 {
|
|
_, err := run(repo, "worktree", "remove", "--force", path)
|
|
if err != nil {
|
|
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
|
|
}
|
|
|
|
return runEnv(repo, env, "commit-tree", lines[0], "-p", head, "-m", message)
|
|
}
|
|
|
|
const Remote = "origin"
|
|
|
|
var ErrRemoteMoved = errors.New("the remote's branch has moved")
|
|
|
|
func Push(repo, commit, branch string) error {
|
|
out, stderr, code, err := runCode(repo, nil, "push", "--porcelain", Remote, commit+":refs/heads/"+branch)
|
|
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 FetchFastForward(repo, branch string) error {
|
|
_, err := run(repo, "fetch", Remote, branch)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return FastForward(repo, Remote+"/"+branch)
|
|
}
|
|
|
|
func Head(dir string) (string, error) {
|
|
return run(dir, "rev-parse", "HEAD")
|
|
}
|
|
|
|
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
|
|
}
|
|
if status == "" {
|
|
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 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 runCode(dir string, env []string, args ...string) (string, string, int, error) {
|
|
cmd := exec.Command("git", args...)
|
|
cmd.Dir = dir
|
|
cmd.Env = append(os.Environ(), env...)
|
|
stderr := &strings.Builder{}
|
|
cmd.Stderr = stderr
|
|
out, err := cmd.Output()
|
|
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
|
|
}
|