// Package git runs git commands in the current repository. package git import ( "bytes" "errors" "fmt" "net/url" "os" "os/exec" "strings" ) // Run runs git with args, connected to the terminal. func Run(args ...string) error { cmd := exec.Command("git", args...) cmd.Stdin = os.Stdin cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr return cmd.Run() } // Output runs git with args and returns its trimmed stdout. func Output(args ...string) (string, error) { var stderr bytes.Buffer cmd := exec.Command("git", args...) cmd.Stderr = &stderr out, err := cmd.Output() if err != nil { msg := strings.TrimSpace(stderr.String()) if msg == "" { return "", fmt.Errorf("git %s: %w", strings.Join(args, " "), err) } return "", fmt.Errorf("git %s: %s", strings.Join(args, " "), msg) } return strings.TrimSpace(string(out)), nil } // Remote is a configured git remote. type Remote struct { Name string FetchURL string PushURL string } // Remotes returns the remotes of the current repository in the order they // are configured. func Remotes() ([]*Remote, error) { if _, err := Output("rev-parse", "--git-dir"); err != nil { return nil, err } // `git remote -v` decorates partial clones, so read the config instead out, _ := Output("config", "--get-regexp", `^remote\..*\.(url|pushurl)$`) var remotes []*Remote byName := map[string]*Remote{} for _, line := range strings.Split(out, "\n") { key, value, ok := strings.Cut(line, " ") if !ok { continue } key = strings.TrimPrefix(key, "remote.") dot := strings.LastIndexByte(key, '.') name, field := key[:dot], key[dot+1:] r, ok := byName[name] if !ok { r = &Remote{Name: name} byName[name] = r remotes = append(remotes, r) } switch field { case "url": r.FetchURL = value case "pushurl": r.PushURL = value } } return remotes, nil } // CurrentBranch returns the checked-out branch. func CurrentBranch() (string, error) { b, err := Output("symbolic-ref", "--quiet", "--short", "HEAD") if err != nil { return "", errors.New("not on any branch") } return b, nil } // Config returns a git config value, or "" if it isn't set. func Config(key string) string { v, _ := Output("config", "--get", key) return v } // PushRemote returns the remote a branch pushes to, following git's own // precedence, or "" when none is configured. func PushRemote(branch string) string { for _, key := range []string{"branch." + branch + ".pushRemote", "remote.pushDefault", "branch." + branch + ".remote"} { if v := Config(key); v != "" && v != "." { return v } } return "" } // RevParse resolves a revision to a commit ID. func RevParse(rev string) (string, error) { return Output("rev-parse", "--verify", "--quiet", rev+"^{commit}") } // HasCommit reports whether the object database contains commit. func HasCommit(commit string) bool { return exec.Command("git", "cat-file", "-e", commit+"^{commit}").Run() == nil } // RepoURL is a git remote URL split into host and path, such as // knot1.tangled.sh and alice.example.com/proj. type RepoURL struct { Host string Path string } // ParseURL understands https://, ssh://, and scp-like (user@host:path) git // URLs. func ParseURL(raw string) (*RepoURL, error) { if strings.Contains(raw, "://") { u, err := url.Parse(raw) if err != nil { return nil, err } return &RepoURL{Host: u.Hostname(), Path: strings.Trim(u.Path, "/")}, nil } // scp-like: [user@]host:path. A DID path contains colons, so split on the // first one after the host. at := strings.Index(raw, "@") rest := raw[at+1:] colon := strings.Index(rest, ":") if colon <= 0 { return nil, fmt.Errorf("unsupported git URL %q", raw) } return &RepoURL{Host: rest[:colon], Path: strings.Trim(rest[colon+1:], "/")}, nil }