Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
94 changes: 57 additions & 37 deletions git/commits.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"errors"
"fmt"
"log/slog"
"maps"
"os"
"os/exec"
"slices"
Expand All @@ -23,32 +24,7 @@ func Commits(ctx context.Context, commitrange string) ([]CommitEntry, error) {
return nil, fmt.Errorf("validating the commit range: %w", err)
}

cmdArgs := []string{"git", "rev-list", commitrange}

output, err := command(ctx, cmdArgs[1:]...).Output()

err = ended(ctx, err)
if err != nil {
return nil, fmt.Errorf("%s: %w", strings.Join(cmdArgs, " "), err)
}

if len(output) == 0 {
return nil, nil
}

commitHashes := strings.Split(strings.TrimSpace(string(output)), "\n")

commits := make([]CommitEntry, len(commitHashes))
for i, commitHash := range commitHashes {
c, err := LogCommit(ctx, commitHash)
if err != nil {
return commits, err
}

commits[i] = *c
}

return commits, nil
return entries(ctx, commitrange)
}

// errRange is a --range git cannot resolve: a typo, a ref that is not
Expand Down Expand Up @@ -319,25 +295,69 @@ func LogUntil(ctx context.Context, commit string) ([]string, error) {

// LogCommit assembles the full information on a commit from its commit hash.
func LogCommit(ctx context.Context, commit string) (*CommitEntry, error) {
c := CommitEntry{}
found, err := entries(ctx, "-1", commit)
if err != nil {
return nil, err
}

for k, v := range FieldNames {
cmd := command(ctx, "--no-pager", "log", "-1", `--pretty=format:`+k+``, commit)
if len(found) != 1 {
return nil, fmt.Errorf("git log -1 %s: %w: %d", commit, errEntries, len(found))
}

cmd.Stderr = os.Stderr
return &found[0], nil
}

out, err := cmd.Output()
// errEntries is a git log that did not print the commits asked of it, field
// for field.
var errEntries = errors.New("git log did not print whole commits")

err = ended(ctx, err)
if err != nil {
return nil, fmt.Errorf("%s: %w", strings.Join(cmd.Args, " "), err)
// entries is the commits git log lists for the revisions, newest first, every
// field of FieldNames read: one git for all of them. The fields are printed
// with a NUL between them and between commits, which no field holds, so that
// a body with any line in it is read whole.
func entries(ctx context.Context, revisions ...string) ([]CommitEntry, error) {
formats := slices.Sorted(maps.Keys(FieldNames))

// Under log.showSignature git prints what it found of a signature ahead
// of each commit, inside the first field.
args := append(
[]string{"--no-pager", "log", "-z", "--no-show-signature", "--pretty=format:" + strings.Join(formats, "%x00")},
revisions...,
)

cmd := command(ctx, args...)

cmd.Stderr = os.Stderr

out, err := cmd.Output()

err = ended(ctx, err)
if err != nil {
return nil, fmt.Errorf("%s: %w", strings.Join(cmd.Args, " "), err)
}

if len(out) == 0 {
return nil, nil
}

fields := strings.Split(string(out), "\x00")
if len(fields)%len(formats) != 0 {
return nil, fmt.Errorf("%s: %w: %d fields", strings.Join(cmd.Args, " "), errEntries, len(fields))
}

found := make([]CommitEntry, 0, len(fields)/len(formats))

for commit := range slices.Chunk(fields, len(formats)) {
entry := CommitEntry{}

for idx, format := range formats {
entry[FieldNames[format]] = strings.TrimSpace(strings.ReplaceAll(commit[idx], "\r\n", "\n"))
}

commitMessage := strings.ReplaceAll(string(out), "\r\n", "\n")
c[v] = strings.TrimSpace(commitMessage)
found = append(found, entry)
}

return &c, nil
return found, nil
}

// FetchHeadCommit returns the hash of FETCH_HEAD.
Expand Down
26 changes: 26 additions & 0 deletions git/commits_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,32 @@ func TestCommandsAreRecordedAtDebug(t *testing.T) {
}
}

// A range costs the same two gits whatever its length: the one that checks
// it resolves, and one log for every field of every commit.
func TestCommitsRunsTwoGitsWhateverTheRange(t *testing.T) {
newRepository(t, "one", "two", "three", "four", "five")

for _, revisions := range []string{"HEAD~1..HEAD", "HEAD"} {
var records bytes.Buffer

previous := slog.Default()

slog.SetDefault(slog.New(slog.NewTextHandler(&records, &slog.HandlerOptions{Level: slog.LevelDebug})))

commits, err := Commits(t.Context(), revisions)

slog.SetDefault(previous)

if err != nil {
t.Fatal(err)
}

if ran := strings.Count(records.String(), `msg="running git"`); ran != 2 {
t.Errorf("%s, %d commits: %d gits ran, want 2:\n%s", revisions, len(commits), ran, records.String())
}
}
}

// newRepository makes a repository in a temporary directory with one signed-off
// commit per subject, oldest first, and makes it the working directory. The
// user's and the system's git configuration stay out of it (no signing, no
Expand Down
104 changes: 104 additions & 0 deletions git/contract_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,27 @@ func TestContractLogCommitIsGitsView(t *testing.T) {
)
}

// A message git did not clean keeps its CRLF, and the entry folds it.
r.git(
"commit",
"-q",
"--allow-empty",
"--cleanup=verbatim",
"-m",
"Verbatim subject\r\n\r\nline one\r\nline two\r\n",
)
verbatim := r.git("rev-parse", "HEAD")
r.git("reset", "-q", "--hard", second)

v, err := git.LogCommit(t.Context(), verbatim)
if err != nil {
t.Fatal(err)
}

if (*v)["body"] != "line one\nline two" {
t.Errorf("a body written with CRLF: %q, want its lines folded to LF", (*v)["body"])
}

r.git("checkout", "-q", "-b", "side", first)
side := r.commit("c", []byte("c\n"), "Side subject")
r.git("checkout", "-q", "main")
Expand All @@ -163,6 +184,89 @@ func TestContractLogCommitIsGitsView(t *testing.T) {
}
}

// TestContractASignedCommitIsReadAsWritten: with log.showSignature set, git
// prints what it found of a commit's signature ahead of the commit. No field
// of the entry holds that line; the signature is in the fields that are its
// own.
//
//nolint:paralleltest // newRepo enters the repository with t.Chdir and t.Setenv
func TestContractASignedCommitIsReadAsWritten(t *testing.T) {
keygen, err := exec.LookPath("ssh-keygen")
if err != nil {
t.Skip("no ssh-keygen on PATH to make a signing key with")
}

r := newRepo(t)
keys := t.TempDir()
key := filepath.Join(keys, "key")

out, err := exec.CommandContext(t.Context(), keygen, "-q", "-t", "ed25519", "-N", "", "-C", "signer", "-f", key).
CombinedOutput()
if err != nil {
t.Fatalf("ssh-keygen: %v\n%s", err, out)
}

public, err := os.ReadFile(key + ".pub")
if err != nil {
t.Fatal(err)
}

signers := filepath.Join(keys, "signers")
if err = os.WriteFile(signers, []byte("signer@example.com "+string(public)), 0o600); err != nil {
t.Fatal(err)
}

r.git("config", "gpg.format", "ssh")
r.git("config", "user.signingkey", key+".pub")
r.git("config", "gpg.ssh.allowedSignersFile", signers)
r.git("config", "log.showSignature", "true")

if err = os.WriteFile(filepath.Join(r.dir, "a"), []byte("a\n"), 0o600); err != nil {
t.Fatal(err)
}

r.git("add", "-A")
r.git("commit", "-q", "-S", "-m", "A signed subject\n\nA signed body")

signed := r.git("rev-parse", "HEAD")

// The premise: git does print the line under this configuration.
if shown := r.git("log", "-1", "--pretty=format:%s"); !strings.Contains(shown, "signature") {
t.Fatalf("git log prints no signature line ahead of the commit: %q", shown)
}

one, err := git.LogCommit(t.Context(), signed)
if err != nil {
t.Fatal(err)
}

ranged, err := git.Commits(t.Context(), signed)
if err != nil || len(ranged) != 1 {
t.Fatalf("Commits: %v, %d commits, want one", err, len(ranged))
}

for _, entry := range []git.CommitEntry{*one, ranged[0]} {
for field, want := range map[string]string{
"commit": signed,
"subject": "A signed subject",
"body": "A signed body",
"refs": "HEAD -> main",
"verification_flag": "G",
"signer": "signer@example.com",
} {
if entry[field] != want {
t.Errorf("%s = %q, want %q", field, entry[field], want)
}
}

for field, value := range entry {
if strings.Contains(value, "signature") {
t.Errorf("%s holds git's signature line: %q", field, value)
}
}
}
}

// TestContractCommitsListsARange: Commits lists the commits `git rev-list`
// lists for the range, newest first; a single commit names its whole
// history; an empty range lists nothing and errs nothing; a range git
Expand Down
Loading