package thin import ( "context" "encoding/json" "math" "os/exec" "strings" "amadan.net/oficina/equipo/internal/runner/workspace" "amadan.net/oficina/equipo/internal/wire" ) // changeFiles reuses Review's NUL-safe parsers, without changing its // measurement or its conservative 200-file merge-authority bound. func changeFiles(ctx context.Context, git, gitDir, base, sha string) *wire.ChangeFiles { if base != "" && !shaPattern.MatchString(base) || !shaPattern.MatchString(sha) { return nil } run := func(args ...string) (string, bool) { cmd := exec.CommandContext(ctx, git, append([]string{"--git-dir=" + gitDir, "-c", "core.quotePath=false"}, args...)...) env := workspace.GitEnvironment() env["HOME"] = "/nonexistent" for k, v := range env { cmd.Env = append(cmd.Env, k+"="+v) } out, clipped, err := boundedOutput(cmd, factsOutput) return string(out), err == nil && !clipped } pair := []string{base, sha} if base == "" { parents, ok := run("rev-list", "--parents", "-n", "1", sha) if !ok || strings.TrimSpace(parents) != sha { return nil } pair = []string{"--root", "--no-commit-id", sha} } else if _, ok := run("merge-base", "--is-ancestor", base, sha); !ok { return nil } raw, ok1 := run(append([]string{"diff-tree", "-r", "-z", "--raw", "-M", "--no-abbrev", "--no-ext-diff", "--no-textconv"}, pair...)...) num, ok2 := run(append([]string{"diff-tree", "-r", "-z", "--numstat", "-M", "--no-ext-diff", "--no-textconv"}, pair...)...) if !ok1 || !ok2 { return nil } return changeFileListings(base, sha, raw, num) } func changeFileListings(base, sha, raw, num string) *wire.ChangeFiles { entries, ok1 := parseRaw(raw) stats, ok2 := parseNumstat(num) if !ok1 || !ok2 || len(entries) != len(stats) { return nil } f := &wire.ChangeFiles{Base: base, SHA: sha, Files: len(entries), Entries: []wire.ChangedFile{}} for i, e := range entries { s := stats[i] if s.path != e.New || s.old != e.Old || s.added > math.MaxInt-f.Additions || s.deleted > math.MaxInt-f.Deletions { return nil } f.Additions += s.added f.Deletions += s.deleted if s.binary { f.Binary++ } status := "" switch e.Status[0] { case 'A': status = wire.ChangeFileAdded case 'D': status = wire.ChangeFileDeleted case 'M', 'T': status = wire.ChangeFileModified case 'R': status = wire.ChangeFileRenamed default: return nil } if len(f.Entries) < wire.MaxChangeEntries { if !wire.ValidChangePath(e.New) || e.Old != "" && !wire.ValidChangePath(e.Old) { return nil } f.Entries = append(f.Entries, wire.ChangedFile{Path: e.New, OldPath: e.Old, Status: status, Additions: s.added, Deletions: s.deleted, Binary: s.binary}) } } for { f.Truncated = len(f.Entries) < f.Files encoded, _ := json.Marshal(f) if len(encoded) <= wire.MaxChangeFilesBytes { break } f.Entries = f.Entries[:len(f.Entries)-1] } if !wire.ValidChangeFiles(f) { return nil } return f }