showcase
- v0.2.4
- 37 commits
- 1 branch
- 6 tags
- updated
- CI 2/2
gitx.go
7.8 KB · 246 lines
1// Package gitx wraps the git CLI for reading bare mirrors.2package gitx34import (5 "bytes"6 "context"7 "fmt"8 "os"9 "os/exec"10 "path"11 "regexp"12 "strconv"13 "strings"14 "time"15)1617// env keeps git from prompting for credentials, reading user config or18// using anything but HTTP(S). A private repo just fails.19var env = append(os.Environ(),20 "GIT_TERMINAL_PROMPT=0",21 "GIT_CONFIG_NOSYSTEM=1",22 "GIT_CONFIG_GLOBAL=/dev/null",23 "GIT_ALLOW_PROTOCOL=http:https",24 "GIT_ASKPASS=/bin/false",25)2627type Repo struct{ Dir string }2829func git(ctx context.Context, dir string, args ...string) ([]byte, error) {30 args = append([]string{"-c", "credential.helper=", "-c", "core.quotePath=false"}, args...)31 cmd := exec.CommandContext(ctx, "git", args...)32 cmd.Dir, cmd.Env = dir, env33 var stderr bytes.Buffer34 cmd.Stderr = &stderr35 out, err := cmd.Output()36 if err != nil {37 return nil, fmt.Errorf("git %s: %w: %s", args[4], err, strings.TrimSpace(stderr.String()))38 }39 return out, nil40}4142// Mirror clones url into dir as a bare mirror, or fetches if it exists. The43// remote is reset to url first, so changing gitea_url (say, to a tailnet44// address) moves existing mirrors along instead of fetching the old host.45func Mirror(ctx context.Context, url, dir string) (Repo, error) {46 if _, err := os.Stat(dir); err == nil {47 if _, err := git(ctx, dir, "remote", "set-url", "origin", url); err != nil {48 return Repo{dir}, err49 }50 _, err := git(ctx, dir, "fetch", "--prune", "--quiet", "origin")51 return Repo{dir}, err52 }53 tmp := dir + ".tmp"54 os.RemoveAll(tmp)55 if _, err := git(ctx, "", "clone", "--mirror", "--quiet", url, tmp); err != nil {56 os.RemoveAll(tmp)57 return Repo{}, err58 }59 return Repo{dir}, os.Rename(tmp, dir)60}6162func (r Repo) run(ctx context.Context, args ...string) ([]byte, error) {63 return git(ctx, r.Dir, args...)64}6566// Head returns the commit hash of branch.67func (r Repo) Head(ctx context.Context, branch string) (string, error) {68 out, err := r.run(ctx, "rev-parse", "--verify", "--end-of-options", "refs/heads/"+branch+"^{commit}")69 return strings.TrimSpace(string(out)), err70}7172type Entry struct {73 Mode, Type, Hash, Name string74 Size int64 // -1 for trees and submodules75}7677// Tree lists every entry at rev, recursively, with full paths as names.78func (r Repo) Tree(ctx context.Context, rev string) ([]Entry, error) {79 out, err := r.run(ctx, "ls-tree", "-r", "-t", "-z", "-l", "--end-of-options", rev+"^{tree}")80 if err != nil {81 return nil, err82 }83 var es []Entry84 for _, rec := range strings.Split(strings.TrimSuffix(string(out), "\x00"), "\x00") {85 meta, name, ok := strings.Cut(rec, "\t")86 f := strings.Fields(meta)87 if !ok || len(f) != 4 {88 continue89 }90 size, err := strconv.ParseInt(f[3], 10, 64)91 if err != nil {92 size = -193 }94 es = append(es, Entry{Mode: f[0], Type: f[1], Hash: f[2], Name: name, Size: size})95 }96 return es, nil97}9899// Blob returns the contents of the blob at hash.100func (r Repo) Blob(ctx context.Context, hash string) ([]byte, error) {101 return r.run(ctx, "cat-file", "blob", hash)102}103104type Commit struct {105 Hash, Author, Subject, Body string106 When time.Time107 Parents []string108}109110func (c Commit) Short() string { return c.Hash[:min(len(c.Hash), 10)] }111112// Log returns up to n commits reachable from rev, optionally touching path.113func (r Repo) Log(ctx context.Context, rev string, n int, path string) ([]Commit, error) {114 args := []string{"log", "-n", strconv.Itoa(n), "--format=%H%x1f%an%x1f%at%x1f%s%x1f%b%x1f%P%x1e", "--end-of-options", rev}115 if path != "" {116 args = append(args, "--", ":(literal)"+path)117 }118 out, err := r.run(ctx, args...)119 if err != nil {120 return nil, err121 }122 var cs []Commit123 for _, rec := range strings.Split(string(out), "\x1e") {124 f := strings.Split(strings.TrimLeft(rec, "\n"), "\x1f")125 if len(f) != 6 {126 continue127 }128 at, _ := strconv.ParseInt(f[2], 10, 64)129 cs = append(cs, Commit{Hash: f[0], Author: f[1], When: time.Unix(at, 0).UTC(), Subject: f[3],130 Body: strings.TrimSpace(f[4]), Parents: strings.Fields(f[5])})131 }132 return cs, nil133}134135// CommitCount is the number of commits reachable from rev.136func (r Repo) CommitCount(ctx context.Context, rev string) (int, error) {137 out, err := r.run(ctx, "rev-list", "--count", "--end-of-options", rev)138 if err != nil {139 return 0, err140 }141 return strconv.Atoi(strings.TrimSpace(string(out)))142}143144// Ref is a branch or tag and the commit it points at.145type Ref struct {146 Name, Hash, Subject string147 When time.Time148}149150// Refs lists "heads" or "tags", newest first. Annotated tags resolve to151// their commit.152func (r Repo) Refs(ctx context.Context, kind string) ([]Ref, error) {153 out, err := r.run(ctx, "for-each-ref", "--sort=-creatordate",154 "--format=%(refname:lstrip=2)%1f%(if)%(*objectname)%(then)%(*objectname)%(else)%(objectname)%(end)%1f%(creatordate:unix)%1f%(contents:subject)%1e",155 "refs/"+kind)156 if err != nil {157 return nil, err158 }159 var refs []Ref160 for _, rec := range strings.Split(string(out), "\x1e") {161 f := strings.Split(strings.TrimSpace(rec), "\x1f")162 if len(f) != 4 {163 continue164 }165 at, _ := strconv.ParseInt(f[2], 10, 64)166 refs = append(refs, Ref{Name: f[0], Hash: f[1], When: time.Unix(at, 0).UTC(), Subject: f[3]})167 }168 return refs, nil169}170171// LastChanges maps every path (files and directories) to the newest commit172// reachable from rev that touched it, in one pass over history.173func (r Repo) LastChanges(ctx context.Context, rev string) (map[string]Commit, error) {174 out, err := r.run(ctx, "log", "-z", "--name-only", "--format=%x1e%H%x1f%an%x1f%at%x1f%s", "--end-of-options", rev)175 if err != nil {176 return nil, err177 }178 last := map[string]Commit{}179 for _, rec := range strings.Split(string(out), "\x1e")[1:] {180 head, files, _ := strings.Cut(rec, "\x00")181 f := strings.Split(head, "\x1f")182 if len(f) != 4 {183 continue184 }185 at, _ := strconv.ParseInt(f[2], 10, 64)186 c := Commit{Hash: f[0], Author: f[1], When: time.Unix(at, 0).UTC(), Subject: f[3]}187 for _, p := range strings.Split(strings.TrimLeft(files, "\n"), "\x00") {188 for ; p != "" && p != "."; p = path.Dir(p) {189 if _, ok := last[p]; ok {190 break // set by a newer commit, and so are its parents191 }192 last[p] = c193 }194 }195 }196 return last, nil197}198199// Stat is a commit's line counts against its first parent.200type Stat struct{ Added, Deleted int }201202var (203 insRe = regexp.MustCompile(`(\d+) insertion`)204 delRe = regexp.MustCompile(`(\d+) deletion`)205)206207// ShortStats returns line counts for the newest n commits on rev, measured208// against the first parent like the commit pages.209func (r Repo) ShortStats(ctx context.Context, rev string, n int) (map[string]Stat, error) {210 out, err := r.run(ctx, "log", "-n", strconv.Itoa(n), "--format=%x1e%H", "--shortstat", "--diff-merges=first-parent", "--end-of-options", rev)211 if err != nil {212 return nil, err213 }214 stats := map[string]Stat{}215 for _, rec := range strings.Split(string(out), "\x1e")[1:] {216 hash, rest, _ := strings.Cut(rec, "\n")217 var s Stat218 if m := insRe.FindStringSubmatch(rest); m != nil {219 s.Added, _ = strconv.Atoi(m[1])220 }221 if m := delRe.FindStringSubmatch(rest); m != nil {222 s.Deleted, _ = strconv.Atoi(m[1])223 }224 stats[strings.TrimSpace(hash)] = s225 }226 return stats, nil227}228229// CommitsSince returns the commits on rev since a time, newest first, with230// hash, author, time (UTC) and subject only.231func (r Repo) CommitsSince(ctx context.Context, rev string, since time.Time) ([]Commit, error) {232 out, err := r.run(ctx, "log", "--format=%H%x1f%an%x1f%at%x1f%s%x1e", "--since="+since.UTC().Format(time.RFC3339), "--end-of-options", rev)233 if err != nil {234 return nil, err235 }236 var cs []Commit237 for _, rec := range strings.Split(string(out), "\x1e") {238 f := strings.Split(strings.TrimLeft(rec, "\n"), "\x1f")239 if len(f) != 4 {240 continue241 }242 at, _ := strconv.ParseInt(f[2], 10, 64)243 cs = append(cs, Commit{Hash: f[0], Author: f[1], When: time.Unix(at, 0).UTC(), Subject: f[3]})244 }245 return cs, nil246}