From cb70d591e552827d11d6e63cb065883296fe7578 Mon Sep 17 00:00:00 2001 From: closer-claudio Date: Sun, 15 Nov 2026 19:05:06 -0800 Subject: [PATCH] Whitespace is checked commit by commit: a merge is not blamed, a first commit is checked The dangling-whitespace rule ran `git log --check X^..X` on each commit. Two things followed from writing the commit as that range. A merge was failed for commits that are not in the range validated. `X^..X` is every commit X has that its first parent has not: for a merge, all that the second parent brings. A branch that merges main into itself, where main holds a commit with a trailing blank, was reported, on `--range main..feature`, as a merge with whitespace errors, with `git show --check ` to see them, which shows nothing. The error is main's, merged long ago. A first commit was never checked. The range cannot be written for a commit with no parent, so the rule listed the whole history of every commit, one more git a commit, to learn whether it was the first, and skipped it: a first commit with a trailing blank passed. git.Check now runs `git log --check X^!`, the commit without its parents' histories. It is one git, with no listing of the history before it. A merge answers for nothing: what it brings in is not its own, and git shows no change for a merge. A first commit is checked as any other, whatever the user's log.showRoot, which the command sets: with it off git shows nothing for a first commit. A commit a shallow clone was cut at is not a first commit. git shows it with no parent, as adding the whole tree, so `X^!` finds there every whitespace error of the history before it. The old listing took it for the first commit and skipped it; it is still skipped, and `-D` still records it. It is told from a first commit by its own object, which names a parent git does not show; a clone as deep as the history lists its first commit as where it was cut, and that one names none. A clone of depth 1, as actions/checkout makes by default, passes a run with no range as it did. Two verdicts move: - a merge that brings in commits with whitespace errors passes; - a first commit with whitespace errors fails, where a range reaches it. With the reader's change before this one, a range of n commits with nothing to report starts 2 + n gits, where it started 2 + 22n. A commit git finds something in costs one more, to see whether git shows it a parent, and a second to read its object when git shows it none. UPSTREAM.md's row on `-D` names the skipped check for what it now is. TestContractCheckFindsWhitespaceErrors holds a first commit, a merge of others' errors and a merge that adds a line itself; TestContractCheckOfAFirstCommitAndOfACut holds log.showRoot off, clones of depth 1 and 2 over a first commit with a trailing blank, and clones that hold the first commit, one at the very depth of the history; TestContractWhitespaceIsEachCommitsOwn holds the two verdicts and the clone of depth 1 through the command. Against the check as it was, the first and the third fail. Measured one at a time, the file restored: with a cut commit checked as a first one, the clones of depth 1 and 2 fail in the second and the clone of depth 1 in the third; with log.showRoot left to the user, the first commit passes in the second. For https://github.com/forkcloser/git-validation/issues/50. Co-Authored-By: Claude Fable 5.2 Signed-off-by: closer-claudio --- UPSTREAM.md | 2 +- cmd/git-validation/contract_test.go | 57 +++++++++++++++ git/commits.go | 64 +++++++++++------ git/commits_test.go | 3 +- git/contract_test.go | 106 ++++++++++++++++++++++++++-- 5 files changed, 201 insertions(+), 31 deletions(-) diff --git a/UPSTREAM.md b/UPSTREAM.md index 5f97dbc..1447725 100644 --- a/UPSTREAM.md +++ b/UPSTREAM.md @@ -23,7 +23,7 @@ Fork of https://github.com/vbatts/git-validation (`main`). | On Windows, `GIT_CHECK_EXCLUDE` works (git's version was compared by a parser that refused `2.42.0.windows.2`); hashicorp/go-version leaves the dependencies | https://github.com/forkcloser/git-validation/pull/8 | | Logs through `log/slog` (colored on a terminal, JSON otherwise) instead of logrus; errors name the git command that failed | https://github.com/forkcloser/git-validation/pull/12 | | Flags parsed by kong: long flags take two dashes (`--run`, `--range`; `-run` is refused), `-v`/`-D`/`-q`/`-d` gain long forms, `--no-travis-pr-only` | https://github.com/forkcloser/git-validation/pull/16 | -| `-D` records each git command run, the skipped check of an initial commit and the commit a rangeless run starts from, as debug records through `log/slog` | https://github.com/forkcloser/git-validation/pull/20 | +| `-D` records each git command run, the skipped whitespace check of a commit a shallow clone was cut at and the commit a rangeless run starts from, as debug records through `log/slog` | https://github.com/forkcloser/git-validation/pull/20 | | A `--run` name no rule has is refused, naming it and listing the rules there are, where it ran nothing and passed; a `message_regexp` value that does not compile is refused before any commit is read, with the regexp package's words, where it panicked on the first commit; the final count is of commits with a failing result, not of results; "using commit range" is logged at debug | https://github.com/forkcloser/git-validation/pull/24 | | The short-subject rule counts characters, not bytes, against its limits; a `--range` git cannot resolve is an error naming the range and the failed git command in a repository with its whole history, nothing validated | https://github.com/forkcloser/git-validation/pull/39 | | A `--range` git cannot resolve is an error in a shallow clone too, where it used to validate what the clone had from its oldest commit, so a depth of one passed the head commit alone; the error names the end the clone does not have and what to fetch (`fetch-depth: 0`, `git fetch --deepen` or `--unshallow`), and a shallow clone deep enough for the range runs as before | https://github.com/forkcloser/git-validation/pull/47 | diff --git a/cmd/git-validation/contract_test.go b/cmd/git-validation/contract_test.go index 0a0bd95..bc9d165 100644 --- a/cmd/git-validation/contract_test.go +++ b/cmd/git-validation/contract_test.go @@ -240,6 +240,63 @@ func TestContractWhitespaceErrorsAreNamed(t *testing.T) { } } +// TestContractWhitespaceIsEachCommitsOwn: a merge is not failed for the +// whitespace errors of the commits it brings in, which are not in the +// range; a first commit is checked as any other; the commit a shallow +// clone was cut at is not failed for the tree before it. +// +//nolint:paralleltest // newRepo sets the environment with t.Setenv +func TestContractWhitespaceIsEachCommitsOwn(t *testing.T) { + r := newRepo(t) + + root := r.commit("a", "a \n", "Root with a trailing blank", true) + + r.git("checkout", "-q", "-b", "feature") + + work := r.commit("f", "f\n", "Feature work", true) + + r.git("checkout", "-q", "main") + r.commit("c", "c \n", "On main, with a trailing blank", true) + r.git("checkout", "-q", "feature") + r.git("merge", "-q", "--no-ff", "-m", "Merge main into feature", "main") + + merge := r.git("rev-parse", "--short", "HEAD") + + // What the branch adds to main: its own commit, and the merge. + code, out := r.run(nil, "--run", "dangling-whitespace", "-v", "--range", "main..feature") + if code != 0 { + t.Errorf("a branch that merged main, whose own commit is clean: exit %d, want 0:\n%s", code, out) + } + + for _, line := range []string{ + " * " + merge + " \"Merge main into feature\" ... PASS\n", + " * " + work + " \"Feature work\" ... PASS\n", + } { + if !strings.Contains(out, line) { + t.Errorf("output lacks %q:\n%s", line, out) + } + } + + // The whole of main reaches its first commit. + code, out = r.run(nil, "--run", "dangling-whitespace", "-v", "--range", "main") + if line := " * " + root + " \"Root with a trailing blank\" ... FAIL\n"; code != 1 || !strings.Contains(out, line) { + t.Errorf("a first commit with a trailing blank: exit %d, want 1 and %q:\n%s", code, line, out) + } + + // A clone of depth 1, as a CI checks out: its one commit was cut from + // its parents, and is not failed for the tree they left it. + r.git("checkout", "-q", "main") + + last := r.commit("d", "d\n", "A clean change", true) + clone := repo{t: t, dir: filepath.Join(t.TempDir(), "clone")} + r.git("clone", "-q", "--no-local", "--depth", "1", r.dir, clone.dir) + + code, out = clone.run(nil, "--run", "dangling-whitespace", "-v") + if line := " * " + last + " \"A clean change\" ... PASS\n"; code != 0 || !strings.Contains(out, line) { + t.Errorf("a clone of depth 1 over a tree with trailing blanks: exit %d, want 0 and %q:\n%s", code, line, out) + } +} + // TestContractVerboseAndQuiet: -v prints every rule's result under its // commit; -q prints nothing for a passing commit and one line per failing // rule, the hash and the reason, with -v or without; QUIET in the diff --git a/git/commits.go b/git/commits.go index 7c68eb3..ef4a01d 100644 --- a/git/commits.go +++ b/git/commits.go @@ -196,29 +196,20 @@ func versionNumbers(gitVersion string) ([]int, error) { return numbers, nil } -// Check warns if changes introduce whitespace errors. -// Returns non-zero if any issues are found. +// Check runs `git log --check` on the commit alone: the output is what git +// found, and the error its exit, 2 when there are whitespace errors. A commit +// with no parent is checked whole. A merge answers for nothing: the commits +// it brings in are not its own, and git shows no change for a merge. Nor +// does a commit a shallow clone was cut at: its parents are not here to +// tell its change from the tree it started from. func Check(ctx context.Context, commit string) ([]byte, error) { - logs, err := LogUntil(ctx, commit) - if err != nil { - return nil, err - } - - if len(logs) == 1 { - slog.DebugContext( - ctx, - "skipping the whitespace check of the initial commit, which has no parent", - "commit", - commit, - ) + var err error - return []byte{}, nil - } - - args := []string{ - "--no-pager", "log", "--check", - fmt.Sprintf("%s^..%s", commit, commit), - } + // commit^! is the commit without its parents' histories. commit^..commit + // cannot be written for a first commit, and for a merge it is every + // commit the second parent brings. With log.showRoot off in the user's + // configuration git shows nothing for a first commit. + args := []string{"-c", "log.showRoot=true", "--no-pager", "log", "--check", commit + "^!"} if excludeEnvList := os.Getenv("GIT_CHECK_EXCLUDE"); excludeEnvList != "" { var gitNewEnough bool @@ -249,12 +240,43 @@ func Check(ctx context.Context, commit string) ([]byte, error) { err = ended(ctx, err) if err != nil { + // git shows a commit whose parents are not here as adding the whole + // tree, so what it found there is any commit's before it. + if cutAt(ctx, commit) { + slog.DebugContext( + ctx, + "skipping the whitespace check of a commit whose parents are not in this shallow clone", + "commit", commit, + ) + + return nil, nil + } + return out, fmt.Errorf("git log --check %s: %w", commit, err) } return out, nil } +// cutAt reports whether commit is one a shallow clone was cut at: its own +// object names a parent, and git shows it none. A first commit names none. +func cutAt(ctx context.Context, commit string) bool { + shown, err := command(ctx, "rev-list", "--parents", "--max-count=1", commit).Output() + if ended(ctx, err) != nil || len(strings.Fields(string(shown))) != 1 { + return false + } + + object, err := command(ctx, "cat-file", "commit", commit).Output() + if ended(ctx, err) != nil { + return false + } + + // The headers end at the first empty line; a message may hold anything. + headers, _, _ := strings.Cut(string(object), "\n\n") + + return strings.HasPrefix(headers, "parent ") || strings.Contains(headers, "\nparent ") +} + // Show returns the diff of a commit. // // NOTE: This could be expensive for very large commits. diff --git a/git/commits_test.go b/git/commits_test.go index 040d733..1a0c682 100644 --- a/git/commits_test.go +++ b/git/commits_test.go @@ -75,8 +75,7 @@ func TestCommandsAreRecordedAtDebug(t *testing.T) { for _, want := range []string{ `msg="running git" cmd="git --no-pager rev-parse --verify HEAD"`, - `msg="running git" cmd="git --no-pager log --oneline --no-show-signature ` + head + `"`, - `msg="skipping the whitespace check of the initial commit, which has no parent" commit=` + head, + `msg="running git" cmd="git -c log.showRoot=true --no-pager log --check ` + head + `^!"`, } { if !strings.Contains(records.String(), want) { t.Errorf("no record %s in:\n%s", want, records.String()) diff --git a/git/contract_test.go b/git/contract_test.go index 13545d3..112211b 100644 --- a/git/contract_test.go +++ b/git/contract_test.go @@ -335,10 +335,11 @@ func TestContractCommitsListsARange(t *testing.T) { } // TestContractCheckFindsWhitespaceErrors: Check runs `git log --check` on -// the commit against its parent: a change adding trailing whitespace -// fails with git's exit status 2, a clean change passes, the root commit -// is not checked; GIT_CHECK_EXCLUDE, colon-separated, leaves named paths -// out of the check, empty entries ignored. +// the commit alone: a change adding trailing whitespace fails with git's +// exit status 2, a clean change passes, a first commit is checked as any +// other; a merge answers for none of the commits it brings in, and git +// shows no change of its own to check; GIT_CHECK_EXCLUDE, colon-separated, +// leaves named paths out of the check, empty entries ignored. func TestContractCheckFindsWhitespaceErrors(t *testing.T) { r := newRepo(t) @@ -352,8 +353,10 @@ func TestContractCheckFindsWhitespaceErrors(t *testing.T) { vendored := r.commit(filepath.Join("vendor", "d.txt"), []byte("vendored \n"), "Vendored") - if _, err := git.Check(t.Context(), root); err != nil { - t.Errorf("the root commit: %v, want it skipped", err) + var exit *exec.ExitError + + if _, err := git.Check(t.Context(), root); !errors.As(err, &exit) || exit.ExitCode() != 2 { + t.Errorf("a first commit adding trailing whitespace: %v, want git's exit status 2", err) } if _, err := git.Check(t.Context(), clean); err != nil { @@ -365,7 +368,6 @@ func TestContractCheckFindsWhitespaceErrors(t *testing.T) { t.Fatal("a commit adding trailing whitespace: no error") } - var exit *exec.ExitError if !errors.As(err, &exit) || exit.ExitCode() != 2 { t.Errorf("a commit adding trailing whitespace: %v, want git's exit status 2", err) } @@ -383,4 +385,94 @@ func TestContractCheckFindsWhitespaceErrors(t *testing.T) { if _, err := git.Check(t.Context(), dirty); err == nil { t.Error("the dirty commit outside the excluded paths: no error") } + + t.Setenv("GIT_CHECK_EXCLUDE", "") + + // A branch cut before the dirty commits, which merges main into itself: + // the merge brings them in, and they are not its own. + r.git("checkout", "-q", "-b", "feature", clean) + r.commit("e.txt", []byte("feature\n"), "Feature") + r.git("merge", "-q", "--no-ff", "--no-edit", "main") + + if _, err := git.Check(t.Context(), r.git("rev-parse", "HEAD")); err != nil { + t.Errorf("a merge of commits with trailing whitespace: %v, want none: they are not the merge's", err) + } + + // A merge that adds a line of its own: git shows no change for a merge. + r.git("checkout", "-q", "-b", "other", clean) + r.commit("f.txt", []byte("other\n"), "Other") + r.git("merge", "-q", "--no-ff", "--no-commit", "feature") + + evil := r.commit("g.txt", []byte("added by the merge \n"), "Merge with a change of its own") + + if parents := strings.Fields(r.git("log", "-1", "--pretty=format:%P", evil)); len(parents) != 2 { + t.Fatalf("the premise: a merge, got parents %v", parents) + } + + if _, err := git.Check(t.Context(), evil); err != nil { + t.Errorf("a merge that adds trailing whitespace itself: %v; git shows no change for a merge", err) + } +} + +// TestContractCheckOfAFirstCommitAndOfACut: a first commit is checked +// whatever log.showRoot says; the commit a shallow clone was cut at is +// not a first commit, and answers for nothing, as its own change cannot +// be told from the tree before it; a clone deep enough to hold the first +// commit checks it, at the very depth of the history too. +// +//nolint:paralleltest // newRepo sets the environment with t.Setenv, and the test enters each clone +func TestContractCheckOfAFirstCommitAndOfACut(t *testing.T) { + r := newRepo(t) + + root := r.commit("a.txt", []byte("a trailing space \n"), "Root") + r.commit("b.txt", []byte("b\n"), "B") + r.commit("c.txt", []byte("c\n"), "C") + head := r.commit("d.txt", []byte("d\n"), "D") + + var exit *exec.ExitError + + r.git("config", "log.showRoot", "false") + + if _, err := git.Check(t.Context(), root); !errors.As(err, &exit) || exit.ExitCode() != 2 { + t.Errorf("a first commit adding trailing whitespace, log.showRoot off: %v, want git's exit status 2", err) + } + + for _, depth := range []string{"1", "2"} { + clone := repo{t: t, dir: filepath.Join(t.TempDir(), "clone")} + r.git("clone", "-q", "--no-local", "--depth", depth, r.dir, clone.dir) + t.Chdir(clone.dir) + + if shallow := clone.git("rev-parse", "--is-shallow-repository"); shallow != "true" { + t.Fatalf("the premise: a shallow clone, got %s", shallow) + } + + cut := clone.git("rev-list", "--max-parents=0", "HEAD") + if cut == root { + t.Fatalf("the premise: a clone of depth %s cut after the first commit", depth) + } + + if _, err := git.Check(t.Context(), cut); err != nil { + t.Errorf( + "depth %s, the commit the clone was cut at: %v, want none: the tree before it is not its own", + depth, + err, + ) + } + + if _, err := git.Check(t.Context(), head); err != nil { + t.Errorf("depth %s, a clean commit: %v", depth, err) + } + } + + // At the depth of the history git still calls the clone shallow, and + // lists the first commit as where it was cut. + for _, depth := range []string{"4", "10"} { + whole := repo{t: t, dir: filepath.Join(t.TempDir(), "clone")} + r.git("clone", "-q", "--no-local", "--depth", depth, r.dir, whole.dir) + t.Chdir(whole.dir) + + if _, err := git.Check(t.Context(), root); !errors.As(err, &exit) || exit.ExitCode() != 2 { + t.Errorf("depth %s, a clone that holds the first commit: %v, want git's exit status 2", depth, err) + } + } }