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
2 changes: 1 addition & 1 deletion UPSTREAM.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
57 changes: 57 additions & 0 deletions cmd/git-validation/contract_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
64 changes: 43 additions & 21 deletions git/commits.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down
3 changes: 1 addition & 2 deletions git/commits_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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())
Expand Down
106 changes: 99 additions & 7 deletions git/contract_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand All @@ -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 {
Expand All @@ -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)
}
Expand All @@ -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)
}
}
}
Loading