From f253bd1402a670c741ee5af81fe8358f7ebe9dc0 Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Tue, 1 Dec 2026 19:45:49 +0300 Subject: [PATCH 1/2] Skip diff coverage in a build outside a git work tree A build of a source release, such as a git archive export, has no .git, so no line can count as changed. cribro still ran test under the JaCoCo agent, which costs about 20% of its wall time, and then printed Diff coverage: no base ref resolved, so no line counts as changed. Pass -Pcribro.diffBase=, or set an upstream branch, or fetch origin/HEAD, origin/main, or origin/master. once per module, advising a fetch into a repository that does not exist. Where git is not installed, diffCoverage failed the build after the tests passed, with "cannot run git in ". Whether the build lies in a work tree is now decided at configuration time from the file system and the environment, with no git process: a .git directory or file at or above the root directory, as in a clone, a linked worktree, or a submodule, or GIT_DIR in the environment. Outside a work tree the Gradle plugin turns the agent off on test and disables jacocoTestReport, as -Pcribro.diffCoverageEnabled=false does, and finalizes test with diffCoverage alone; the Maven extension attaches no agent. Deciding at execution time was rejected: whether the agent is enabled is an input of test, so turning it off in doFirst would cache an uninstrumented result under the key of an instrumented run. With GIT_DIR and no .git, git keeps running in the build's root directory, so a relative GIT_DIR or GIT_WORK_TREE resolves as before. User-visible: Outside a git work tree, test runs without the JaCoCo agent, and the build prints one line, "Diff coverage: skipped, since is not in a git work tree.", at the QUIET level in Gradle and at the end of the session in Maven; no git command runs. Outside a git work tree, changedLines writes a file with the header "not in a git work tree" and no line, so pitestDiff is skipped. In Maven, GIT_DIR in the environment with no .git now counts as a work tree, where cribro used to report that the build was not in one. Fixes #36 Co-Authored-By: Claude Opus 5.5 --- .../io/github/cribrodev/DiffCoverage.java | 8 + .../main/java/io/github/cribrodev/Git.java | 21 +++ .../java/io/github/cribrodev/GitTest.java | 49 ++++++ .../io/github/cribrodev/ChangedLinesTask.java | 12 +- .../io/github/cribrodev/CribroPlugin.java | 29 +++- .../io/github/cribrodev/DiffCoverageTask.java | 13 +- .../java/io/github/cribrodev/GitService.java | 32 +++- .../resources/io/github/cribrodev/guide.md | 4 + .../cribrodev/ChangedLinesTaskRunTest.java | 25 ++- .../cribrodev/CribroSettingsPluginTest.java | 69 ++++++++ .../io/github/cribrodev/GitServiceTest.java | 34 +++- .../github/cribrodev/OutsideWorkTreeTest.java | 157 ++++++++++++++++++ .../cribrodev/maven/CoverageReport.java | 10 +- .../cribrodev/maven/CribroMojoListener.java | 9 +- .../github/cribrodev/maven/CribroState.java | 2 +- .../io/github/cribrodev/maven/guide.md | 4 + .../cribrodev/maven/MavenIntegrationTest.java | 25 +++ 17 files changed, 481 insertions(+), 22 deletions(-) create mode 100644 cribro-gradle-plugin/src/test/java/io/github/cribrodev/OutsideWorkTreeTest.java diff --git a/cribro-core/src/main/java/io/github/cribrodev/DiffCoverage.java b/cribro-core/src/main/java/io/github/cribrodev/DiffCoverage.java index b01cd45..ba7fedc 100644 --- a/cribro-core/src/main/java/io/github/cribrodev/DiffCoverage.java +++ b/cribro-core/src/main/java/io/github/cribrodev/DiffCoverage.java @@ -53,6 +53,14 @@ public static String noBase(String flag) { + ChangedLines.noBaseHint(flag); } + /** + * Returns the text printed in place of a report where the build lies in no git work tree, as in + * a source release, so that no line can count as changed. + */ + public static String notInWorkTree(File directory) { + return "Diff coverage: skipped, since " + directory + " is not in a git work tree."; + } + /** * Returns whether any of the changed files lies under one of the source roots, so that a caller * with many modules prepares a report only for those the change reached. diff --git a/cribro-core/src/main/java/io/github/cribrodev/Git.java b/cribro-core/src/main/java/io/github/cribrodev/Git.java index 53ee9e9..ddd6c02 100644 --- a/cribro-core/src/main/java/io/github/cribrodev/Git.java +++ b/cribro-core/src/main/java/io/github/cribrodev/Git.java @@ -83,6 +83,27 @@ public static File findRepositoryRoot(File start) { return null; } + /** + * Returns the directory to run git in for a build at {@code start}, or null where git would find + * no work tree, judged from the file system and the environment alone, so that no git process + * runs. + * + *

The directory is the one {@link #findRepositoryRoot} returns. Where no directory holds {@code + * .git}, {@code GIT_DIR} in the environment git runs with still makes a work tree, and the + * directory is then {@code start} itself, so that git resolves a relative {@code GIT_DIR} or + * {@code GIT_WORK_TREE} against it as it would for the build. + * + * @param environment the variables git runs with, as given to {@link #Git(File, Map)} + */ + public static File findWorkTree(File start, Map environment) { + File root = findRepositoryRoot(start); + if (root != null) { + return root; + } + String gitDir = environment.get("GIT_DIR"); + return gitDir == null || gitDir.isEmpty() ? null : start.getAbsoluteFile(); + } + /** Returns the repository the commands run in, which is also where its files are read from. */ public File repositoryRoot() { return repositoryRoot; diff --git a/cribro-core/src/test/java/io/github/cribrodev/GitTest.java b/cribro-core/src/test/java/io/github/cribrodev/GitTest.java index a98bd0b..efd2ded 100644 --- a/cribro-core/src/test/java/io/github/cribrodev/GitTest.java +++ b/cribro-core/src/test/java/io/github/cribrodev/GitTest.java @@ -209,6 +209,55 @@ void theNearestRepositoryWinsOverOneFurtherUp() throws Exception { assertEquals(nested.toFile(), Git.findRepositoryRoot(module.toFile()), "root of nested/module"); } + @Test + void aDirectoryWithNoDotGitAboveAndNoGitDirIsInNoWorkTree() throws Exception { + Path module = Files.createDirectories(directory.resolve("module")); + + assertNull( + Git.findWorkTree(module.toFile(), Map.of("GIT_INDEX_FILE", "index")), + "findWorkTree(module) with GIT_INDEX_FILE alone set"); + } + + @Test + void anEmptyGitDirCountsAsUnset() throws Exception { + Path module = Files.createDirectories(directory.resolve("module")); + + assertNull(Git.findWorkTree(module.toFile(), Map.of("GIT_DIR", "")), "findWorkTree(module)"); + } + + @Test + void aDotGitFileMarksAWorkTree() throws Exception { + // A linked worktree or a submodule marks its root with a .git file rather than a directory. + Files.writeString(directory.resolve(".git"), "gitdir: elsewhere\n"); + Path module = Files.createDirectories(directory.resolve("module")); + + assertEquals(directory.toFile(), Git.findWorkTree(module.toFile(), Map.of()), "findWorkTree(module)"); + } + + @Test + void gitDirWithoutGitWorkTreeRunsGitInTheStart() throws Exception { + Path module = Files.createDirectories(directory.resolve("module")); + + assertEquals( + module.toFile(), + Git.findWorkTree(module.toFile(), Map.of("GIT_DIR", "/elsewhere/.git")), + "findWorkTree(module)"); + } + + /** + * git runs in the returned directory with the environment unchanged, so a relative {@code + * GIT_WORK_TREE} has to keep the directory it is relative to. + */ + @Test + void gitDirWithAGitWorkTreeStillRunsGitInTheStart() throws Exception { + Path module = Files.createDirectories(directory.resolve("parent/module")); + + assertEquals( + module.toFile(), + Git.findWorkTree(module.toFile(), Map.of("GIT_DIR", "../.git", "GIT_WORK_TREE", "..")), + "findWorkTree(parent/module)"); + } + @Test void aRelativeStartIsResolvedBeforeTheWalk() throws Exception { File relative = new File(""); diff --git a/cribro-gradle-plugin/src/main/java/io/github/cribrodev/ChangedLinesTask.java b/cribro-gradle-plugin/src/main/java/io/github/cribrodev/ChangedLinesTask.java index d1839fb..aed6ab8 100644 --- a/cribro-gradle-plugin/src/main/java/io/github/cribrodev/ChangedLinesTask.java +++ b/cribro-gradle-plugin/src/main/java/io/github/cribrodev/ChangedLinesTask.java @@ -56,7 +56,17 @@ public abstract class ChangedLinesTask extends DefaultTask { @TaskAction public void write() throws IOException { - Git git = getGit().get().git(); + GitService service = getGit().get(); + Git git = service.git(); + if (git == null) { + if (service.firstToReportSkip()) { + // QUIET, as diffCoverage prints it: whichever task runs first prints the line for both. + getLogger().quiet(DiffCoverage.notInWorkTree(service.directory())); + } + ChangedLinesFile.write( + getOutputFile().get().getAsFile().toPath(), List.of("not in a git work tree"), List.of()); + return; + } ChangedLines diff = git.changedLines(getBaseRef().getOrNull()); if (diff == null) { getLogger().warn("No base ref resolved, so no line counts as changed. {}", diff --git a/cribro-gradle-plugin/src/main/java/io/github/cribrodev/CribroPlugin.java b/cribro-gradle-plugin/src/main/java/io/github/cribrodev/CribroPlugin.java index 8c22a57..e592312 100644 --- a/cribro-gradle-plugin/src/main/java/io/github/cribrodev/CribroPlugin.java +++ b/cribro-gradle-plugin/src/main/java/io/github/cribrodev/CribroPlugin.java @@ -24,6 +24,7 @@ import java.util.ArrayList; import java.util.Collection; import java.util.List; +import java.util.Map; import java.util.Set; import java.util.concurrent.Callable; import org.gradle.api.Plugin; @@ -155,25 +156,34 @@ void projectEvaluated() { /** Registers the tasks and returns the overrides of the build's own settings. */ private static Runnable configure(Project project) { ProviderFactory providers = project.getProviders(); + // A build outside a git work tree, such as one from a source release, has no line to count as + // changed. It is told at configuration time: whether `test` runs with the agent is an input of + // `test`, so a later switch would cache an uninstrumented result under an instrumented key. + File workTree = Git.findWorkTree(project.getRootDir(), gitEnvironment(providers)); + boolean inWorkTree = workTree != null; // -Pcribro.diffCoverageEnabled=false keeps the tasks and drops the instrumentation of `test`, which // costs about 20% of its wall time, for a run that is not about coverage. - boolean diffCoverageEnabled = + boolean diffCoverageRequested = providers .gradleProperty("cribro.diffCoverageEnabled") .map(it -> it.isEmpty() || Boolean.parseBoolean(it)) .getOrElse(true); + boolean diffCoverageEnabled = diffCoverageRequested && inWorkTree; Provider diffBase = providers.gradleProperty("cribro.diffBase"); String jacocoVersion = providers.gradleProperty("cribro.jacocoVersion").getOrNull(); - File repositoryRoot = repositoryRoot(project.getRootDir()); + File repositoryRoot = inWorkTree ? workTree : project.getRootDir().getAbsoluteFile(); project .getGradle() .getSharedServices() .registerIfAbsent( DiffCoverageTask.GIT_SERVICE, GitService.class, - spec -> spec.getParameters().getRepositoryRoot().set(repositoryRoot)); + spec -> { + spec.getParameters().getRepositoryRoot().set(repositoryRoot); + spec.getParameters().getInWorkTree().set(inWorkTree); + }); SourceSetContainer sourceSets = project.getExtensions().getByType(SourceSetContainer.class); SourceSet main = sourceSets.getByName(SourceSet.MAIN_SOURCE_SET_NAME); @@ -289,6 +299,9 @@ && compareVersions(jacoco.getToolVersion(), JACOCO_VERSION) < 0) { // Running the report as part of the test run keeps the XML in step with the // execution data, so diffCoverage cannot read line numbers from an earlier run. t.finalizedBy(jacocoTestReport); + } else if (diffCoverageRequested) { + // Outside a work tree, diffCoverage prints that it skipped the report. + t.finalizedBy(diffCoverage); } }); jacocoTestReport.configure( @@ -542,12 +555,12 @@ private static int part(String[] parts, int index) { } /** - * Returns the directory holding {@code .git}, which git prints the paths of a diff against, or - * {@code start} where no directory above it holds one. + * Returns {@code GIT_DIR}, the variable that makes a work tree without {@code .git}, read through + * Gradle so that the configuration cache is invalidated when it changes. */ - static File repositoryRoot(File start) { - File root = Git.findRepositoryRoot(start); - return root != null ? root : start.getAbsoluteFile(); + private static Map gitEnvironment(ProviderFactory providers) { + String gitDir = providers.environmentVariable("GIT_DIR").getOrNull(); + return gitDir == null ? Map.of() : Map.of("GIT_DIR", gitDir); } private static Provider intProperty( diff --git a/cribro-gradle-plugin/src/main/java/io/github/cribrodev/DiffCoverageTask.java b/cribro-gradle-plugin/src/main/java/io/github/cribrodev/DiffCoverageTask.java index 29b907c..c1221d8 100644 --- a/cribro-gradle-plugin/src/main/java/io/github/cribrodev/DiffCoverageTask.java +++ b/cribro-gradle-plugin/src/main/java/io/github/cribrodev/DiffCoverageTask.java @@ -16,6 +16,7 @@ package io.github.cribrodev; import java.io.IOException; +import java.nio.file.Files; import java.util.List; import org.gradle.api.DefaultTask; import org.gradle.api.file.ConfigurableFileCollection; @@ -117,7 +118,9 @@ public void report() throws IOException { } /** - * Returns the text this run prints, which is empty where the change reached none of the module. + * Returns the text this run prints, which is empty where the change reached none of the module, + * and outside a git work tree is the line saying so for the first task of the build that reports + * it and empty for the others. * *

Returning the text rather than logging it is what lets a test read the report: the scope * line naming the ref that resolved, the message of a run that measured nothing, and the note @@ -128,7 +131,13 @@ public void report() throws IOException { * modification time stands for when the execution data was recorded. */ String describeRun() throws IOException { - return DiffCoverage.in(getGit().get().git()) + GitService service = getGit().get(); + Git git = service.git(); + if (git == null) { + Files.deleteIfExists(getOutputFile().get().getAsFile().toPath()); + return service.firstToReportSkip() ? DiffCoverage.notInWorkTree(service.directory()) : ""; + } + return DiffCoverage.in(git) .baseRef(getBaseRef().getOrNull()) .sourceRoots(getSourceRoots().get()) .reports(List.copyOf(getReportFiles().getFiles())) diff --git a/cribro-gradle-plugin/src/main/java/io/github/cribrodev/GitService.java b/cribro-gradle-plugin/src/main/java/io/github/cribrodev/GitService.java index f2f88ec..a7a8916 100644 --- a/cribro-gradle-plugin/src/main/java/io/github/cribrodev/GitService.java +++ b/cribro-gradle-plugin/src/main/java/io/github/cribrodev/GitService.java @@ -15,7 +15,10 @@ */ package io.github.cribrodev; +import java.io.File; +import java.util.concurrent.atomic.AtomicBoolean; import org.gradle.api.file.DirectoryProperty; +import org.gradle.api.provider.Property; import org.gradle.api.services.BuildService; import org.gradle.api.services.BuildServiceParameters; @@ -32,15 +35,42 @@ public abstract class GitService implements BuildService /** The repository every command of this service runs in. */ public interface Parameters extends BuildServiceParameters { DirectoryProperty getRepositoryRoot(); + + /** + * Whether {@link #getRepositoryRoot()} lies in a git work tree; unset counts as true. Where it + * is false, the root is the build's root directory and no git command runs. + */ + Property getInWorkTree(); } + private final AtomicBoolean skipReported = new AtomicBoolean(); + private Git git; - /** Returns git in the repository the parameters name, the same instance on every call. */ + /** + * Returns git in the repository the parameters name, the same instance on every call, or null + * where the build lies in no git work tree. + */ public synchronized Git git() { + if (!getParameters().getInWorkTree().getOrElse(true)) { + return null; + } if (git == null) { git = new Git(getParameters().getRepositoryRoot().get().getAsFile()); } return git; } + + /** Returns the directory the parameters name, which lies in no work tree where git() is null. */ + public File directory() { + return getParameters().getRepositoryRoot().get().getAsFile(); + } + + /** + * Returns true on the first call of the build and false on every later one, so that the tasks of + * every project print that the build lies in no work tree once. + */ + public boolean firstToReportSkip() { + return skipReported.compareAndSet(false, true); + } } diff --git a/cribro-gradle-plugin/src/main/resources/io/github/cribrodev/guide.md b/cribro-gradle-plugin/src/main/resources/io/github/cribrodev/guide.md index 7fad88d..24b01f3 100644 --- a/cribro-gradle-plugin/src/main/resources/io/github/cribrodev/guide.md +++ b/cribro-gradle-plugin/src/main/resources/io/github/cribrodev/guide.md @@ -126,6 +126,10 @@ The changed lines are the diff between the working tree and the merge base of `H `origin/HEAD`, `origin/main`, or `origin/master`. An upstream that is this branch pushed to a fork is skipped. For a stacked change, pass the parent branch: `-Pcribro.diffBase=`. +A build outside a git work tree, such as one from a source release, has no line to count as changed: `test` runs without +JaCoCo, no git command runs, and the build prints one line saying that diff coverage was skipped. A `.git` file, as in a +linked worktree, and `GIT_DIR` in the environment each mark a work tree. + ## Properties | Property | Default | Effect | diff --git a/cribro-gradle-plugin/src/test/java/io/github/cribrodev/ChangedLinesTaskRunTest.java b/cribro-gradle-plugin/src/test/java/io/github/cribrodev/ChangedLinesTaskRunTest.java index 79a7016..12b9ccb 100644 --- a/cribro-gradle-plugin/src/test/java/io/github/cribrodev/ChangedLinesTaskRunTest.java +++ b/cribro-gradle-plugin/src/test/java/io/github/cribrodev/ChangedLinesTaskRunTest.java @@ -45,6 +45,11 @@ class ChangedLinesTaskRunTest { @TempDir Path directory; private Path write(String baseRef) throws IOException { + return write(baseRef, null); + } + + /** Runs the task, with the in-work-tree parameter of the service left unset where it is null. */ + private Path write(String baseRef, Boolean inWorkTree) throws IOException { Project project = ProjectBuilder.builder().withProjectDir(directory.toFile()).build(); ChangedLinesTask task = project.getTasks().register("changedLines", ChangedLinesTask.class).get(); @@ -56,8 +61,10 @@ private Path write(String baseRef) throws IOException { .registerIfAbsent( "git", GitService.class, - service -> - service.getParameters().getRepositoryRoot().set(directory.toFile()))); + service -> { + service.getParameters().getRepositoryRoot().set(directory.toFile()); + service.getParameters().getInWorkTree().set(inWorkTree); + })); task.getSourceRoots().set(List.of("src/main/java")); task.getBaseRef().set(baseRef); Path output = directory.resolve("build/diff/changed-lines.txt"); @@ -111,6 +118,20 @@ void aRepositoryWithNoBaseLeavesAFileWithNoLines() throws Exception { () -> assertEquals(Map.of(), ChangedLinesFile.read(file))); } + /** pitestDiff skips a module whose file lists no line, so this run mutates nothing. */ + @Test + void aBuildOutsideAWorkTreeLeavesAFileWithNoLines() throws Exception { + Path source = directory.resolve("src/main/java/A.java"); + Files.createDirectories(source.getParent()); + Files.writeString(source, "class A {}\n"); + + Path file = write(null, false); + + assertAll( + () -> assertEquals("not in a git work tree", ChangedLinesFile.readHeader(file)), + () -> assertEquals(Map.of(), ChangedLinesFile.read(file))); + } + private void repositoryWithAnEmptyCommit() throws IOException, InterruptedException { run("init", "--initial-branch=master", "."); run("-c", "user.email=t@example.com", "-c", "user.name=T", "commit", "--allow-empty", "-m", "seed"); diff --git a/cribro-gradle-plugin/src/test/java/io/github/cribrodev/CribroSettingsPluginTest.java b/cribro-gradle-plugin/src/test/java/io/github/cribrodev/CribroSettingsPluginTest.java index a243465..ec78fbf 100644 --- a/cribro-gradle-plugin/src/test/java/io/github/cribrodev/CribroSettingsPluginTest.java +++ b/cribro-gradle-plugin/src/test/java/io/github/cribrodev/CribroSettingsPluginTest.java @@ -23,7 +23,9 @@ import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; import org.gradle.testkit.runner.BuildResult; import org.gradle.testkit.runner.GradleRunner; import org.junit.jupiter.api.Test; @@ -432,6 +434,7 @@ void aProjectConfiguredFromATaskActionOfAnotherGetsTheOverrides() throws IOExcep + PRINT_COVERAGE_WIRING, UTF_8); + markAsWorkTree(); BuildResult result = run(null, ":lib:printCoverageWiring"); assertEquals( @@ -457,6 +460,7 @@ void aProjectThatDisablesJacocoOnTestGetsTheOverrides() throws IOException { + PRINT_COVERAGE_WIRING, UTF_8); + markAsWorkTree(); BuildResult result = run(null, ":app:printCoverageWiring"); assertEquals( @@ -478,6 +482,7 @@ void aJavaPluginAppliedAfterTheScriptRanGetsTheOverrides() throws IOException { + PRINT_COVERAGE_WIRING, UTF_8); + markAsWorkTree(); BuildResult result = run(null, ":app:printCoverageWiring"); assertEquals( @@ -488,6 +493,70 @@ void aJavaPluginAppliedAfterTheScriptRanGetsTheOverrides() throws IOException { result.getOutput().lines().toList()); } + @Test + void aBuildOutsideAWorkTreeRunsTestWithoutJacocoAndThenDiffCoverage() throws IOException { + writeBuild(" id 'io.github.cribro-dev.cribro'\n"); + Files.writeString( + build.resolve("app/build.gradle"), "plugins { id 'java' }\n" + PRINT_COVERAGE_WIRING, UTF_8); + + BuildResult result = + runner(null, ":app:printCoverageWiring").withEnvironment(environmentWithout("GIT_DIR")).build(); + + assertEquals( + List.of( + "jacoco on test: false", + "test finalized by: [:app:diffCoverage]", + "jacocoTestReport finalized by: []"), + result.getOutput().lines().toList()); + } + + @Test + void aBuildOutsideAWorkTreeWithDiffCoverageDisabledFinalizesNothing() throws IOException { + writeBuild(" id 'io.github.cribro-dev.cribro'\n"); + Files.writeString( + build.resolve("app/build.gradle"), "plugins { id 'java' }\n" + PRINT_COVERAGE_WIRING, UTF_8); + + BuildResult result = + runner(null, ":app:printCoverageWiring", "-Pcribro.diffCoverageEnabled=false") + .withEnvironment(environmentWithout("GIT_DIR")) + .build(); + + assertEquals( + List.of( + "jacoco on test: false", "test finalized by: []", "jacocoTestReport finalized by: []"), + result.getOutput().lines().toList()); + } + + @Test + void gitDirInTheEnvironmentMakesAWorkTreeWithoutDotGit() throws IOException { + writeBuild(" id 'io.github.cribro-dev.cribro'\n"); + Files.writeString( + build.resolve("app/build.gradle"), "plugins { id 'java' }\n" + PRINT_COVERAGE_WIRING, UTF_8); + Map environment = environmentWithout("GIT_DIR"); + environment.put("GIT_DIR", home.resolve("repository.git").toString()); + + BuildResult result = runner(null, ":app:printCoverageWiring").withEnvironment(environment).build(); + + assertEquals( + List.of( + "jacoco on test: true", + "test finalized by: [:app:jacocoTestReport]", + "jacocoTestReport finalized by: [:app:diffCoverage]"), + result.getOutput().lines().toList()); + } + + /** Marks the build's directory as the root of a work tree, as a clone's {@code .git} does. */ + private void markAsWorkTree() throws IOException { + Files.createDirectory(build.resolve(".git")); + } + + /** The environment of this JVM without the named variable. */ + private static Map environmentWithout(String name) { + Map environment = new HashMap<>(System.getenv()); + environment.remove(name); + return environment; + } + /** * Registers {@code printCoverageWiring}, which prints whether JaCoCo instruments {@code test} and * which tasks finalize {@code test} and {@code jacocoTestReport}. diff --git a/cribro-gradle-plugin/src/test/java/io/github/cribrodev/GitServiceTest.java b/cribro-gradle-plugin/src/test/java/io/github/cribrodev/GitServiceTest.java index 5ffb824..9a1ce29 100644 --- a/cribro-gradle-plugin/src/test/java/io/github/cribrodev/GitServiceTest.java +++ b/cribro-gradle-plugin/src/test/java/io/github/cribrodev/GitServiceTest.java @@ -16,8 +16,12 @@ package io.github.cribrodev; import static java.nio.charset.StandardCharsets.UTF_8; +import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.io.InputStream; @@ -48,6 +52,11 @@ class GitServiceTest { @TempDir Path directory; private GitService service() { + return service(null); + } + + /** Returns the service, with the in-work-tree parameter left unset where it is null. */ + private GitService service(Boolean inWorkTree) { Project project = ProjectBuilder.builder().withProjectDir(directory.toFile()).build(); return project .getGradle() @@ -55,10 +64,33 @@ private GitService service() { .registerIfAbsent( "git", GitService.class, - service -> service.getParameters().getRepositoryRoot().set(directory.toFile())) + service -> { + service.getParameters().getRepositoryRoot().set(directory.toFile()); + service.getParameters().getInWorkTree().set(inWorkTree); + }) .get(); } + /** + * The repository is real, so the null comes from the parameter alone: the plugin sets it from + * the file system, and no git process may run outside a work tree, where git may be missing. + */ + @Test + void aBuildOutsideAWorkTreeGetsNoGit() throws Exception { + repositoryWithOneCommit(); + + assertNull(service(false).git(), "git() of a service with inWorkTree=false"); + } + + @Test + void onlyTheFirstTaskOfTheBuildReportsTheSkip() { + GitService service = service(false); + + assertAll( + () -> assertTrue(service.firstToReportSkip(), "first call of firstToReportSkip()"), + () -> assertFalse(service.firstToReportSkip(), "second call of firstToReportSkip()")); + } + @Test void aRepeatedCommandKeepsTheAnswerOfItsFirstRunForTheBuild() throws Exception { repositoryWithOneCommit(); diff --git a/cribro-gradle-plugin/src/test/java/io/github/cribrodev/OutsideWorkTreeTest.java b/cribro-gradle-plugin/src/test/java/io/github/cribrodev/OutsideWorkTreeTest.java new file mode 100644 index 0000000..915f3d0 --- /dev/null +++ b/cribro-gradle-plugin/src/test/java/io/github/cribrodev/OutsideWorkTreeTest.java @@ -0,0 +1,157 @@ +/* + * Copyright (C) 2026 cribro contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.github.cribrodev; + +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.junit.jupiter.api.Assertions.assertAll; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import org.gradle.testkit.runner.GradleRunner; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** + * A build outside a git work tree, such as one from a source release, runs {@code test} without + * the JaCoCo agent and says once that diff coverage was skipped; a linked worktree is a work tree. + * + *

The builds resolve JUnit from Maven Central, so the tests need the network, as {@link + * KotlinBuildTest} does. + */ +class OutsideWorkTreeTest { + + @TempDir Path directory; + + @Test + void aBuildOutsideAWorkTreeRunsTestWithoutTheAgentAndSaysSoOnce() throws Exception { + Path build = directory.resolve("export"); + writeBuild(build); + + String output = test(build, environmentWithoutGit()); + + List skipped = + output.lines().filter(line -> line.startsWith("Diff coverage:")).collect(Collectors.toList()); + assertAll( + () -> + assertEquals( + List.of(DiffCoverage.notInWorkTree(build.toRealPath().toFile())), + skipped, + "diff coverage lines of a build with modules a and b; whole output:\n" + output), + () -> assertFalse(Files.exists(build.resolve("a/build/jacoco/test.exec")), "a/build/jacoco/test.exec exists"), + () -> assertFalse(Files.exists(build.resolve("b/build/jacoco/test.exec")), "b/build/jacoco/test.exec exists")); + } + + @Test + void aLinkedWorktreeRunsTestWithTheAgent() throws Exception { + Path main = directory.resolve("main"); + writeBuild(main); + git(main, "init", "-q", "--initial-branch=main"); + git(main, "add", "-A"); + git(main, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "-m", "base"); + Path linked = directory.resolve("linked"); + git(main, "worktree", "add", "-q", linked.toString()); + + String output = test(linked, environmentWithoutGit()); + + assertAll( + () -> assertTrue(Files.exists(linked.resolve("a/build/jacoco/test.exec")), "a/build/jacoco/test.exec exists"), + () -> + assertFalse( + output.contains("is not in a git work tree"), + "output of a build in a linked worktree:\n" + output)); + } + + /** Writes a build of two modules, a and b, each with one passing JUnit test. */ + private static void writeBuild(Path build) throws IOException { + write( + build.resolve("settings.gradle"), + "plugins { id '" + CribroSettingsPlugin.ID + "' }\n" + + "rootProject.name = 'demo'\n" + + "include 'a', 'b'\n"); + write( + build.resolve("build.gradle"), + """ + subprojects { + apply plugin: 'java' + repositories { mavenCentral() } + dependencies { + testImplementation platform('org.junit:junit-bom:5.14.4') + testImplementation 'org.junit.jupiter:junit-jupiter' + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' + } + test { useJUnitPlatform() } + } + """); + for (String module : List.of("a", "b")) { + write( + build.resolve(module + "/src/test/java/demo/" + module + "/PassingTest.java"), + """ + package demo.%s; + + import org.junit.jupiter.api.Test; + + class PassingTest { + @Test + void passes() {} + } + """ + .formatted(module)); + } + } + + private static void write(Path file, String text) throws IOException { + Files.createDirectories(file.getParent()); + Files.writeString(file, text, UTF_8); + } + + /** The environment of this JVM without the variables that point git at a repository. */ + private static Map environmentWithoutGit() { + Map environment = new HashMap<>(System.getenv()); + environment.remove("GIT_DIR"); + environment.remove("GIT_WORK_TREE"); + return environment; + } + + private static String test(Path build, Map environment) { + return GradleRunner.create() + .withProjectDir(build.toFile()) + .withPluginClasspath() + .withEnvironment(environment) + .withArguments("--quiet", "test") + .build() + .getOutput(); + } + + private static void git(Path directory, String... arguments) + throws IOException, InterruptedException { + List command = new ArrayList<>(); + command.add("git"); + command.addAll(List.of(arguments)); + Process process = + new ProcessBuilder(command).directory(directory.toFile()).redirectErrorStream(true).start(); + String output = new String(process.getInputStream().readAllBytes(), UTF_8); + assertEquals(0, process.waitFor(), () -> String.join(" ", command) + "\n" + output); + } +} diff --git a/cribro-maven-plugin/src/main/java/io/github/cribrodev/maven/CoverageReport.java b/cribro-maven-plugin/src/main/java/io/github/cribrodev/maven/CoverageReport.java index 7af2486..3e2f568 100644 --- a/cribro-maven-plugin/src/main/java/io/github/cribrodev/maven/CoverageReport.java +++ b/cribro-maven-plugin/src/main/java/io/github/cribrodev/maven/CoverageReport.java @@ -97,6 +97,11 @@ String describe() throws IOException { notes.add(run.note); } } + Git git = state.git(); + if (git == null) { + notes.add(DiffCoverage.notInWorkTree(new File(session.getExecutionRootDirectory()))); + return String.join("\n", notes); + } ExecutionDataStore data = new ExecutionDataStore(); List sessions = new ArrayList<>(); Set measuredRuns = read(runs, data, sessions); @@ -113,11 +118,6 @@ String describe() throws IOException { return String.join("\n", notes); } addFailures(runs, projects); - Git git = state.git(); - if (git == null) { - notes.add("Diff coverage: " + session.getExecutionRootDirectory() + " is not in a git work tree."); - return String.join("\n", notes); - } // The top-level POM is where a build sets the base for every module; pitest-diff reads it there too. String base = CribroProperties.get(session, session.getTopLevelProject(), ChangedLines.BASE_PROPERTY); diff --git a/cribro-maven-plugin/src/main/java/io/github/cribrodev/maven/CribroMojoListener.java b/cribro-maven-plugin/src/main/java/io/github/cribrodev/maven/CribroMojoListener.java index 7f0a5f3..2922921 100644 --- a/cribro-maven-plugin/src/main/java/io/github/cribrodev/maven/CribroMojoListener.java +++ b/cribro-maven-plugin/src/main/java/io/github/cribrodev/maven/CribroMojoListener.java @@ -80,6 +80,13 @@ public void beforeMojoExecution(MojoExecutionEvent event) { return; } long start = System.currentTimeMillis(); + CribroState state = CribroState.of(session); + if (state.git() == null) { + // No line can count as changed outside a work tree, so the tests run without the agent; the + // run is still recorded, so that the report says why it skipped. + state.started(TestRun.unmeasured(project, start, null)); + return; + } TestRun run; try { run = attach(session, project, event.getMojo(), start); @@ -97,7 +104,7 @@ public void beforeMojoExecution(MojoExecutionEvent event) { + ": " + e); } - CribroState.of(session).started(run); + state.started(run); } private TestRun attach(MavenSession session, MavenProject project, Object mojo, long start) diff --git a/cribro-maven-plugin/src/main/java/io/github/cribrodev/maven/CribroState.java b/cribro-maven-plugin/src/main/java/io/github/cribrodev/maven/CribroState.java index 987603f..553c4c4 100644 --- a/cribro-maven-plugin/src/main/java/io/github/cribrodev/maven/CribroState.java +++ b/cribro-maven-plugin/src/main/java/io/github/cribrodev/maven/CribroState.java @@ -85,7 +85,7 @@ List runs(List projects) { synchronized Git git() { if (!gitLookedUp) { gitLookedUp = true; - File root = Git.findRepositoryRoot(topDirectory); + File root = Git.findWorkTree(topDirectory, System.getenv()); git = root != null ? new Git(root) : null; } return git; diff --git a/cribro-maven-plugin/src/main/resources/io/github/cribrodev/maven/guide.md b/cribro-maven-plugin/src/main/resources/io/github/cribrodev/maven/guide.md index f5911b4..54044c0 100644 --- a/cribro-maven-plugin/src/main/resources/io/github/cribrodev/maven/guide.md +++ b/cribro-maven-plugin/src/main/resources/io/github/cribrodev/maven/guide.md @@ -136,6 +136,10 @@ The changed lines are the diff between the working tree and the merge base of `H `origin/HEAD`, `origin/main`, or `origin/master`. An upstream that is this branch pushed to a fork is skipped. For a stacked change, pass the parent branch: `-Dcribro.diffBase=`. +A build outside a git work tree, such as one from a source release, has no line to count as changed: the tests run +without JaCoCo, no git command runs, and the build prints one line saying that diff coverage was skipped. A `.git` file, +as in a linked worktree, and `GIT_DIR` in the environment each mark a work tree. + ## Properties Pass a property with `-D`, or set it in `.mvn/maven.config` or in the `` of the POM, the top-level one for diff --git a/cribro-maven-plugin/src/test/java/io/github/cribrodev/maven/MavenIntegrationTest.java b/cribro-maven-plugin/src/test/java/io/github/cribrodev/maven/MavenIntegrationTest.java index 970880e..ed4fd4d 100644 --- a/cribro-maven-plugin/src/test/java/io/github/cribrodev/maven/MavenIntegrationTest.java +++ b/cribro-maven-plugin/src/test/java/io/github/cribrodev/maven/MavenIntegrationTest.java @@ -20,6 +20,7 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; +import io.github.cribrodev.DiffCoverage; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; @@ -103,6 +104,28 @@ void aBuildThatLoadsCribroAsAnExtensionReportsCoverageBeforeItsSummary() throws "BUILD SUCCESS"); } + @Test + void aBuildOutsideAWorkTreeRunsItsTestsWithoutTheAgent() throws Exception { + Path project = directory.resolve("export"); + write(project.resolve(".mvn/extensions.xml"), extensionsXml()); + write(project.resolve("pom.xml"), pom("export", "", "-Xmx256m")); + write(project.resolve("src/main/java/org/apache/commons/lang3/ArrayUtils.java"), CHANGED_CLASS); + write(project.resolve("src/test/java/org/apache/commons/lang3/ArrayUtilsTest.java"), TEST_CLASS); + + String test = maven(project, 0, "test"); + + assertAll( + () -> + assertBefore( + test, + DiffCoverage.notInWorkTree(project.toRealPath().toFile()), + "BUILD SUCCESS"), + () -> + assertFalse( + Files.exists(project.resolve("target/cribro/jacoco.exec")), + "target/cribro/jacoco.exec exists")); + } + /** * The changed class shares its name with a class of commons-lang3, which PIT runs on, so the * mutation report only names its lines where PIT keeps its own classpath away from the tests. @@ -593,6 +616,8 @@ private String run(Path workingDirectory, int exitCode, String... command) builder.environment().put("JAVA_HOME", System.getProperty("java.home")); builder.environment().remove("MAVEN_OPTS"); builder.environment().remove("MAVEN_ARGS"); + builder.environment().remove("GIT_DIR"); + builder.environment().remove("GIT_WORK_TREE"); Process process = builder.start(); process.getOutputStream().close(); int actual = process.waitFor(); From 4ab5051847e0d3dfe6eede8cd6705208192c17cf Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Wed, 2 Dec 2026 13:12:01 +0300 Subject: [PATCH 2/2] Preserve build coverage when Cribro skips an archive Skipping Cribro instrumentation also disabled a Gradle project's own JaCoCo setup. A direct pitestDiff invocation could still resolve PIT dependencies while Gradle saved the configuration cache. Leave project-owned coverage in place and keep PIT inputs out of the archive task graph. Share configuration-time Git discovery between Gradle and Maven, and cover the skip notice and stale-report cleanup with a fresh Gradle process that cannot launch Git. --- README.md | 32 +- agent/cribro/SKILL.md | 23 +- .../io/github/cribrodev/ChangedLines.java | 6 +- .../main/java/io/github/cribrodev/Git.java | 289 +++++++++++- .../java/io/github/cribrodev/GitTest.java | 425 +++++++++++++++++- .../src/dist/cribro.init.gradle | 4 +- .../io/github/cribrodev/CribroPlugin.java | 102 +++-- .../cribrodev/CribroSettingsPlugin.java | 8 +- .../io/github/cribrodev/DiffCoverageTask.java | 10 +- .../java/io/github/cribrodev/GitService.java | 9 +- .../java/io/github/cribrodev/GitWorkTree.java | 40 ++ .../resources/io/github/cribrodev/guide.md | 9 +- .../io/github/cribrodev/CribroPluginTest.java | 11 +- .../cribrodev/CribroSettingsPluginTest.java | 185 ++++++-- .../io/github/cribrodev/OlderGradleTest.java | 6 + .../github/cribrodev/OutsideWorkTreeTest.java | 412 ++++++++++++++++- .../cribrodev/maven/CoverageReport.java | 7 +- .../cribrodev/maven/CribroMojoListener.java | 14 +- .../io/github/cribrodev/maven/guide.md | 9 +- .../cribrodev/maven/MavenIntegrationTest.java | 95 +++- 20 files changed, 1487 insertions(+), 209 deletions(-) create mode 100644 cribro-gradle-plugin/src/main/java/io/github/cribrodev/GitWorkTree.java diff --git a/README.md b/README.md index 7e7744f..543f9ac 100644 --- a/README.md +++ b/README.md @@ -4,8 +4,8 @@ [![Gradle Plugin Portal](https://img.shields.io/gradle-plugin-portal/v/io.github.cribro-dev.cribro)](https://plugins.gradle.org/plugin/io.github.cribro-dev.cribro) cribro reports which lines a branch changed that no test executes, and which changed lines no test would notice -breaking. It works in Gradle and Maven builds with Java or Kotlin sources: `test` ends with a diff coverage report from -JaCoCo, and a separate task runs PIT mutation testing on the changed lines only. The reports are plain text sized for +breaking. In a Git work tree, `test` in a Gradle or Maven build ends with a diff coverage report from JaCoCo, and a +separate task runs PIT mutation testing on changed Java or Kotlin lines only. The reports are plain text sized for an AI agent, so an agent that changed the code reads them in the build output and writes the tests that are missing. There is no HTML report of its own. @@ -51,9 +51,9 @@ changes. ## Gradle -For a Gradle build, cribro is a settings plugin, `io.github.cribro-dev.cribro`. It attaches JaCoCo to the `test` -task of every Java project, which then ends with the diff coverage report, and adds a `pitestDiff` task that runs PIT -on the changed lines. +For a Gradle build, cribro is a settings plugin, `io.github.cribro-dev.cribro`. In a Git work tree, it attaches JaCoCo +to the `test` task of every Java project and prints a diff coverage report. The `pitestDiff` task runs PIT on the +changed lines. ### Gradle requirements @@ -252,8 +252,8 @@ is `:postgresql`. The guide lists the paths. For the root project, the task path The plugin registers `cribro` on the root project, and adds a `cribroProjectElements` configuration to every project; `cribro` resolves that configuration of each project to list the projects that have the tasks. Applied as a settings plugin or through the init script, cribro works with Isolated Projects, tried on Gradle 9.8.2. On Gradle 8, Isolated -Projects fails the `cribro` task where a subproject has the same group and name as the root project. For every project -with the `java` plugin, it: +Projects fails the `cribro` task where a subproject has the same group and name as the root project. In a Git work +tree, for every project with the `java` plugin, it: - applies `jacoco`, enables it on the `test` task, and has `test` finalized by `jacocoTestReport` with the XML report, then by `diffCoverage`. These override the build's own settings after its scripts run, so a build that disables @@ -266,11 +266,14 @@ with the `java` plugin, it: bring one; - runs PIT in a separate JVM from the `test` task's launcher, with its JVM arguments and system properties. +Outside a Git work tree, cribro leaves project-owned JaCoCo coverage in place and skips diff coverage and mutation +testing. With automatic diff coverage enabled, a test build prints the skip notice once. + ## Maven -For a Maven build, cribro is a Maven extension and plugin, `io.github.cribro-dev:cribro-maven-plugin`. Loaded as an -extension, it attaches JaCoCo to the tests of surefire's `default-test` execution and prints the diff coverage report -before Maven's build summary. Its goal `cribro:pitest-diff` runs PIT on the changed lines. +For a Maven build, cribro is a Maven extension and plugin, `io.github.cribro-dev:cribro-maven-plugin`. In a Git work +tree, the extension attaches JaCoCo to the tests of Surefire's `default-test` execution and prints the diff coverage +report before Maven's build summary. Its goal `cribro:pitest-diff` runs PIT on the changed lines. ### Maven requirements @@ -390,13 +393,16 @@ the Gradle ones with `-D` in place of `-P`. ### What cribro changes in a Maven build -Loaded as an extension, cribro: +Loaded as an extension in a Git work tree, cribro: - adds a JaCoCo agent to the `argLine` of surefire's `default-test` execution just before it runs, whatever the POM sets there. Where the `argLine` already attaches a JaCoCo agent, as `jacoco-maven-plugin`'s `prepare-agent` does, cribro reads that agent's file instead; -- writes `target/cribro/jacoco.xml` and `target/cribro/diff-coverage.txt` in each module the change reached; -- declares `cribro-maven-plugin` in every module that does not declare it, so that the `cribro:` prefix resolves. +- writes `target/cribro/jacoco.xml` and `target/cribro/diff-coverage.txt` in each module the change reached. + +Outside a Git work tree, cribro honors the POM's JaCoCo configuration and skips diff coverage and mutation testing. +With automatic diff coverage enabled, a test build prints the skip notice once. The extension declares +`cribro-maven-plugin` in every module that does not declare it, so that the `cribro:` prefix resolves in any layout. `cribro:pitest-diff` runs PIT in a separate JVM, with the classpath, JVM, `argLine`, system properties, environment variables, working directory, groups, includes, and excludes of surefire's `default-test` execution. diff --git a/agent/cribro/SKILL.md b/agent/cribro/SKILL.md index a77f10c..128c38f 100644 --- a/agent/cribro/SKILL.md +++ b/agent/cribro/SKILL.md @@ -5,12 +5,13 @@ description: Measure how well the tests of a Gradle or Maven Java or Kotlin proj # Diff coverage and diff mutation testing -cribro adds diff coverage to `test` and diff mutation testing to every Java or Kotlin project of a Gradle or Maven build. A build -with a `pom.xml` follows the [Maven](#maven) section; the rest of this section is for Gradle builds. A changed file is +In a Git work tree, cribro measures diff coverage with `test` and runs diff mutation testing on Java or Kotlin projects. +A build with a `pom.xml` follows the [Maven](#maven) section. A changed file is matched to its coverage counters and its mutants by the package it declares and its file name, not by its directory, so a Kotlin file whose directory does not follow its package is measured all the same. -In a Gradle build, cribro adds a `pitestDiff` task. A build can apply it itself: its `settings.gradle` or +In a Gradle build, cribro adds a `pitestDiff` task. Pass `-Pcribro.pitestTargetTests=` to that task. +A build can apply cribro itself: its `settings.gradle` or `settings.gradle.kts` names `io.github.cribro-dev.cribro`. Otherwise the init script at `~/.gradle/cribro/cribro.init.gradle` applies it without changing the build. @@ -30,12 +31,14 @@ The init-script form also works in a build that applies cribro itself. The guide tasks, gives every later command in the form this build needs, and says how to act on each report. It comes from the plugin that will run, so it matches its version. -The usual sequence: +## Reporting sequence -1. After changing `src/main` and its tests, run the `test` command the guide prints. It ends with the changed lines no - test executed; write a test for each, or justify leaving it untested. -2. Once the changed lines are covered, run the `pitestDiff` command the guide prints, with - `-Pcribro.pitestTargetTests=`. Each surviving mutant is a changed line whose behavior no test asserts. +1. After changing `src/main` and its tests, run the `test` command the guide prints. Use the report to find changed + lines no test executed, then write a test for each or justify leaving it untested. If the build prints + `Diff coverage: skipped, since

is not in a git work tree.`, report that diff coverage was skipped and end + the sequence. +2. Once the changed lines are covered, run the mutation testing command the guide prints for the relevant test + classes. Each surviving mutant is a changed line whose behavior no test asserts. Where a Gradle build does not apply cribro and `~/.gradle/cribro/cribro.init.gradle` does not exist, cribro is not installed: tell the user, and point them at . @@ -56,7 +59,7 @@ Otherwise: mvn -Dmaven.ext.class.path="$HOME"/.m2/cribro/cribro-maven.jar -q cribro:guide ``` -Then follow the same sequence with the commands the guide prints: `test` ends with the diff coverage report, and -`cribro:pitest-diff` with `-Dcribro.pitestTargetTests=` reports surviving mutants. Where neither the build +Follow the [reporting sequence](#reporting-sequence) with the Maven commands from the guide. Pass +`-Dcribro.pitestTargetTests=` to `cribro:pitest-diff`. Where neither the build nor `~/.m2/cribro/cribro-maven.jar` provides cribro, it is not installed: tell the user, and point them at . diff --git a/cribro-core/src/main/java/io/github/cribrodev/ChangedLines.java b/cribro-core/src/main/java/io/github/cribrodev/ChangedLines.java index a32d57e..7b46baf 100644 --- a/cribro-core/src/main/java/io/github/cribrodev/ChangedLines.java +++ b/cribro-core/src/main/java/io/github/cribrodev/ChangedLines.java @@ -99,11 +99,12 @@ public List unreadable() { * explicit ref, the upstream branch is tried, then the default branches of {@code origin}. * * @param explicit the ref the caller named, or null - * @throws CribroException where the explicit ref does not resolve, because diffing against - * something else would report the wrong lines as changed + * @throws CribroException where Git cannot read its repository or the explicit ref does not + * resolve */ public static ChangedLines measure(Git git, String explicit) { if (explicit != null && !resolves(git, explicit)) { + git.output("rev-parse", "--git-dir"); throw new CribroException(BASE_PROPERTY + " " + explicit + " does not resolve to a commit"); } String upstream = git.outputOrNull(UPSTREAM_NAME); @@ -122,6 +123,7 @@ public static ChangedLines measure(Git git, String explicit) { candidate, mergeBase, changedLines(git, mergeBase, unreadable), unreadable); } } + git.output("rev-parse", "--git-dir"); return null; } diff --git a/cribro-core/src/main/java/io/github/cribrodev/Git.java b/cribro-core/src/main/java/io/github/cribrodev/Git.java index ddd6c02..d0f5b5f 100644 --- a/cribro-core/src/main/java/io/github/cribrodev/Git.java +++ b/cribro-core/src/main/java/io/github/cribrodev/Git.java @@ -20,12 +20,15 @@ import java.io.InputStream; import java.io.UncheckedIOException; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.NoSuchFileException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; +import java.util.regex.Pattern; /** * Runs git as a child process in one repository, once per argument list. @@ -37,6 +40,9 @@ */ public final class Git { + private static final Pattern HEAD_SIGNATURE = + Pattern.compile("ref:[\\t\\n\\x0B\\f\\r ]*refs/|[0-9a-fA-F]{40}"); + /** What one git command printed. */ private static final class Output { /** The trimmed standard output, or null where git reported failure. */ @@ -71,8 +77,8 @@ public Git(File repositoryRoot) { } /** - * Returns the nearest directory at or above {@code start} that holds {@code .git}, which git - * prints the paths of a diff against, or null where none does. + * Returns the first directory at or above {@code start} that holds {@code .git}, or null + * where none does. Use {@link #findWorkTree} to check whether Git can use the marker. */ public static File findRepositoryRoot(File start) { for (File dir = start.getAbsoluteFile(); dir != null; dir = dir.getParentFile()) { @@ -84,24 +90,274 @@ public static File findRepositoryRoot(File start) { } /** - * Returns the directory to run git in for a build at {@code start}, or null where git would find - * no work tree, judged from the file system and the environment alone, so that no git process - * runs. + * Returns the directory to run Git in for a build at {@code start}, or null when Git finds + * no work tree there. + * + *

A {@code GIT_DIR} target, a {@code .git} marker, or metadata directly in the directory + * hierarchy supplies a candidate for a read-only Git probe. An empty {@code GIT_DIR} returns null + * without a probe. A missing {@code GIT_DIR} target or a broken {@code .git} pointer cannot + * supply repository metadata. * - *

The directory is the one {@link #findRepositoryRoot} returns. Where no directory holds {@code - * .git}, {@code GIT_DIR} in the environment git runs with still makes a work tree, and the - * directory is then {@code start} itself, so that git resolves a relative {@code GIT_DIR} or - * {@code GIT_WORK_TREE} against it as it would for the build. + *

With overrides, tries {@code start} first unless moving to an enclosing checkout preserves + * the meaning of {@code GIT_WORK_TREE} and one of two conditions holds. The checkout owns the + * selected metadata, or the overrides select the checkout as the work tree and choose the same + * metadata from both directories. Without overrides, uses the discovered work-tree root if it + * selects the same repository. If no candidate confirms membership, a failed probe with + * plausible metadata keeps its candidate for commands that require Git. * - * @param environment the variables git runs with, as given to {@link #Git(File, Map)} + * @param environment the variables Git runs with, as given to {@link #Git(File, Map)} */ public static File findWorkTree(File start, Map environment) { - File root = findRepositoryRoot(start); - if (root != null) { - return root; - } String gitDir = environment.get("GIT_DIR"); - return gitDir == null || gitDir.isEmpty() ? null : start.getAbsoluteFile(); + if ("".equals(gitDir)) { + return null; + } + File build = start.getAbsoluteFile(); + File hint = findRepositoryHint(build, environment); + if (hint == null && gitDir == null) { + return null; + } + + if (gitDir != null || environment.containsKey("GIT_WORK_TREE")) { + return findExplicitWorkTree(build, hint, gitDir, environment); + } + Git git = new Git(build, environment); + switch (git.workTreeMembership()) { + case ROOT: + return build; + case SUBDIRECTORY: + return git.implicitWorkTreeRoot(hint); + case PROBE_FAILED: + return git.hasPlausibleMetadata(repositoryMetadata(hint)) ? hint : null; + default: + return null; + } + } + + private static File findExplicitWorkTree( + File build, File hint, String gitDir, Map environment) { + File discoveredMetadata = hint == null ? null : repositoryMetadata(hint); + File checkout = null; + if (gitDir != null) { + checkout = findRepositoryRoot(build); + } else if (!hint.equals(discoveredMetadata)) { + checkout = hint; + } + + List candidates = List.of(build); + if (checkout != null && !checkout.equals(build)) { + candidates = + prefersCheckout(checkout, build, gitDir, environment.get("GIT_WORK_TREE")) + ? List.of(checkout, build) + : List.of(build, checkout); + } + File fallback = null; + for (File candidate : candidates) { + File metadata = gitDir == null ? discoveredMetadata : resolve(candidate, gitDir); + if (metadata == null || !metadata.exists()) { + continue; + } + Git git = new Git(candidate, environment); + switch (git.workTreeMembership()) { + case ROOT: + case SUBDIRECTORY: + return candidate; + case PROBE_FAILED: + if (fallback == null && git.hasPlausibleMetadata(metadata)) { + fallback = candidate; + } + break; + default: + break; + } + } + return fallback; + } + + private static boolean prefersCheckout(File checkout, File build, String gitDir, String workTree) { + File fromCheckout = gitDir == null ? null : metadataDirectory(resolve(checkout, gitDir)); + boolean checkoutOwnsMetadata = + gitDir == null + || sameDirectory(fromCheckout, metadataDirectory(repositoryMetadata(checkout))); + if (workTree == null) { + return checkoutOwnsMetadata; + } + File checkoutWorkTree = resolve(checkout, workTree); + if (!sameDirectory(checkoutWorkTree, resolve(build, workTree))) { + return false; + } + return checkoutOwnsMetadata + || (sameDirectory(checkoutWorkTree, checkout) + && sameDirectory(fromCheckout, metadataDirectory(resolve(build, gitDir)))); + } + + private static boolean sameDirectory(File left, File right) { + if (left == null || right == null) { + return false; + } + try { + return Files.isSameFile(left.toPath(), right.toPath()); + } catch (IOException unavailable) { + return false; + } + } + + private enum WorkTreeMembership { + ROOT, + SUBDIRECTORY, + NO_WORK_TREE, + PROBE_FAILED + } + + private WorkTreeMembership workTreeMembership() { + String membership; + try { + membership = outputOrNull("rev-parse", "--show-prefix", "--is-inside-work-tree"); + } catch (CribroException unavailable) { + return WorkTreeMembership.PROBE_FAILED; + } + if (membership == null) { + return WorkTreeMembership.PROBE_FAILED; + } + if (membership.equals("true")) { + return WorkTreeMembership.ROOT; + } + if (membership.endsWith("\ntrue")) { + return WorkTreeMembership.SUBDIRECTORY; + } + return WorkTreeMembership.NO_WORK_TREE; + } + + private File implicitWorkTreeRoot(File hint) { + try { + String workTree = outputOrNull("rev-parse", "--show-toplevel", "--is-inside-work-tree"); + if (workTree == null || !workTree.endsWith("\ntrue")) { + return repositoryRoot; + } + int newline = workTree.lastIndexOf('\n'); + int pathEnd = + File.separatorChar == '\\' && newline > 0 && workTree.charAt(newline - 1) == '\r' + ? newline - 1 + : newline; + File root = new File(workTree.substring(0, pathEnd)); + if (Files.isSameFile(hint.toPath(), root.toPath())) { + return hint; + } + String[] repositoryQuery = {"rev-parse", "--absolute-git-dir", "--is-inside-work-tree"}; + String repository = outputOrNull(repositoryQuery); + String rootRepository = new Git(root, environment).outputOrNull(repositoryQuery); + return repository != null && repository.equals(rootRepository) ? root : repositoryRoot; + } catch (IOException | CribroException unavailable) { + return repositoryRoot; + } + } + + private static File repositoryMetadata(File hint) { + File marker = new File(hint, ".git"); + return marker.exists() ? marker : hint; + } + + private boolean hasPlausibleMetadata(File metadata) { + File directory = metadataDirectory(metadata); + if (directory == null + || !directory.isDirectory() + || !hasPlausibleHead(new File(directory, "HEAD"))) { + return false; + } + String commonOverride = environment.get("GIT_COMMON_DIR"); + File commonMarker = new File(directory, "commondir"); + File common = directory; + if (commonOverride != null) { + common = resolve(repositoryRoot, commonOverride); + } else if (commonMarker.exists()) { + String commonPath = readMetadataPath(commonMarker); + if (commonPath == null || commonPath.isEmpty()) { + return false; + } + common = resolve(directory, commonPath); + } + String objectsOverride = environment.get("GIT_OBJECT_DIRECTORY"); + File objects = + objectsOverride == null + ? new File(common, "objects") + : resolve(repositoryRoot, objectsOverride); + return objects.isDirectory() && new File(common, "refs").isDirectory(); + } + + private static File metadataDirectory(File metadata) { + if (metadata.isDirectory()) { + return metadata; + } + String pointer = readMetadataPath(metadata); + if (pointer == null || !pointer.startsWith("gitdir: ") || pointer.length() == 8) { + return null; + } + return resolve(metadata.getParentFile(), pointer.substring(8)); + } + + private static boolean hasPlausibleHead(File head) { + try { + if (Files.isSymbolicLink(head.toPath())) { + return Files.readSymbolicLink(head.toPath()) + .toString() + .replace(File.separatorChar, '/') + .startsWith("refs/"); + } + if (!head.isFile()) { + return false; + } + try (InputStream input = Files.newInputStream(head.toPath())) { + String prefix = new String(input.readNBytes(255), StandardCharsets.UTF_8); + return HEAD_SIGNATURE.matcher(prefix).lookingAt(); + } + } catch (NoSuchFileException missing) { + return false; + } catch (IOException unreadable) { + return true; + } + } + + private static File resolve(File relativeTo, String name) { + File path = new File(name); + return path.isAbsolute() ? path : new File(relativeTo, name); + } + + private static String readMetadataPath(File file) { + if (!file.isFile()) { + return null; + } + int maxPointerBytes = 1 << 20; + try (InputStream input = Files.newInputStream(file.toPath())) { + byte[] content = input.readNBytes(maxPointerBytes + 1); + if (content.length > maxPointerBytes) { + return null; + } + int end = content.length; + while (end > 0 && (content[end - 1] == '\n' || content[end - 1] == '\r')) { + end--; + } + return new String(content, 0, end, StandardCharsets.UTF_8); + } catch (IOException unreadable) { + return null; + } + } + + private static File findRepositoryHint(File start, Map environment) { + boolean externalMetadata = + environment.containsKey("GIT_OBJECT_DIRECTORY") || environment.containsKey("GIT_COMMON_DIR"); + for (File dir = start; dir != null; dir = dir.getParentFile()) { + if (new File(dir, ".git").exists()) { + return dir; + } + File head = new File(dir, "HEAD"); + if ((head.isFile() || Files.isSymbolicLink(head.toPath())) + && (externalMetadata + || new File(dir, "objects").isDirectory() + || new File(dir, "commondir").isFile())) { + return dir; + } + } + return null; } /** Returns the repository the commands run in, which is also where its files are read from. */ @@ -138,7 +394,8 @@ public String outputOrNull(String... arguments) { * for that ref. * * @param baseRef the ref the caller named, or null to try the defaults - * @throws CribroException where the explicit ref does not resolve + * @throws CribroException where Git cannot read its repository or the explicit ref does not + * resolve */ public ChangedLines changedLines(String baseRef) { return diffs diff --git a/cribro-core/src/test/java/io/github/cribrodev/GitTest.java b/cribro-core/src/test/java/io/github/cribrodev/GitTest.java index efd2ded..595b65a 100644 --- a/cribro-core/src/test/java/io/github/cribrodev/GitTest.java +++ b/cribro-core/src/test/java/io/github/cribrodev/GitTest.java @@ -15,6 +15,7 @@ */ package io.github.cribrodev; +import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNull; @@ -31,7 +32,12 @@ import java.util.Set; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.DisabledOnOs; +import org.junit.jupiter.api.condition.OS; import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.NullSource; +import org.junit.jupiter.params.provider.ValueSource; /** * One git command runs, and one diff is measured, once per instance, and a failing command is told @@ -219,43 +225,420 @@ void aDirectoryWithNoDotGitAboveAndNoGitDirIsInNoWorkTree() throws Exception { } @Test - void anEmptyGitDirCountsAsUnset() throws Exception { - Path module = Files.createDirectories(directory.resolve("module")); + void anEmptyGitDirSelectsNoWorkTreeEvenInACheckout() throws Exception { + initializeCheckout(directory); - assertNull(Git.findWorkTree(module.toFile(), Map.of("GIT_DIR", "")), "findWorkTree(module)"); + assertNull( + Git.findWorkTree(directory.toFile(), workTreeEnvironment(Map.of("GIT_DIR", ""))), + "checkout with GIT_DIR empty"); } @Test - void aDotGitFileMarksAWorkTree() throws Exception { - // A linked worktree or a submodule marks its root with a .git file rather than a directory. - Files.writeString(directory.resolve(".git"), "gitdir: elsewhere\n"); - Path module = Files.createDirectories(directory.resolve("module")); + void aBuildInsideACheckoutUsesTheRootOfThatCheckout() throws Exception { + initializeCheckout(directory); + Path module = Files.createDirectories(directory.resolve("parent/module")); - assertEquals(directory.toFile(), Git.findWorkTree(module.toFile(), Map.of()), "findWorkTree(module)"); + assertEquals( + directory.toRealPath().toFile(), + Git.findWorkTree(module.toFile(), workTreeEnvironment(Map.of())).getCanonicalFile(), + "work tree for " + module); } @Test - void gitDirWithoutGitWorkTreeRunsGitInTheStart() throws Exception { - Path module = Files.createDirectories(directory.resolve("module")); + @DisabledOnOs(OS.WINDOWS) + void aWorkTreePathCanEndInASpace() throws Exception { + Path checkout = Files.createDirectory(directory.resolve("checkout ")); + initializeCheckout(checkout); + Path module = Files.createDirectory(checkout.resolve("module")); assertEquals( - module.toFile(), - Git.findWorkTree(module.toFile(), Map.of("GIT_DIR", "/elsewhere/.git")), - "findWorkTree(module)"); + checkout.toFile(), + Git.findWorkTree(module.toFile(), workTreeEnvironment(Map.of())), + "work tree for " + module); } - /** - * git runs in the returned directory with the environment unchanged, so a relative {@code - * GIT_WORK_TREE} has to keep the directory it is relative to. - */ @Test - void gitDirWithAGitWorkTreeStillRunsGitInTheStart() throws Exception { - Path module = Files.createDirectories(directory.resolve("parent/module")); + void aDotGitFileCanSelectAUsableLinkedWorktree() throws Exception { + Path main = Files.createDirectory(directory.resolve("main")); + Git fixture = initializeCheckout(main); + Path linked = directory.resolve("linked"); + fixture.output("worktree", "add", "-b", "linked", linked.toString()); + Path module = Files.createDirectory(linked.resolve("module")); + + assertEquals( + linked.toRealPath().toFile(), + Git.findWorkTree(module.toFile(), workTreeEnvironment(Map.of())).getCanonicalFile(), + "work tree for " + module); + } + + @Test + void aDotGitFileThatPointsToMissingMetadataSelectsNoWorkTree() throws Exception { + Files.writeString(directory.resolve(".git"), "gitdir: absent\n"); + + assertNull( + Git.findWorkTree(directory.toFile(), workTreeEnvironment(Map.of())), + ".git pointing to missing metadata"); + } + + @Test + void gitDirPointingAtMissingMetadataSelectsNoWorkTreeEvenInACheckout() throws Exception { + initializeCheckout(directory); + + assertNull( + Git.findWorkTree(directory.toFile(), workTreeEnvironment(Map.of("GIT_DIR", "absent"))), + "checkout overridden by GIT_DIR=absent"); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void separateBareMetadataRequiresAnExplicitWorkTree(boolean absolute) throws Exception { + Path main = Files.createDirectory(directory.resolve("main")); + Git fixture = initializeCheckout(main); + Path export = Files.createDirectory(directory.resolve("export")); + Path bare = directory.resolve("repository.git"); + fixture.output("clone", "--bare", ".", bare.toString()); + String gitDir = absolute ? bare.toString() : export.relativize(bare).toString(); + String workTree = absolute ? export.toString() : "."; + + assertNull( + Git.findWorkTree(export.toFile(), workTreeEnvironment(Map.of("GIT_DIR", gitDir))), + "archive with only GIT_DIR=" + gitDir); + assertEquals( + export.toFile(), + Git.findWorkTree( + export.toFile(), workTreeEnvironment(Map.of("GIT_DIR", gitDir, "GIT_WORK_TREE", workTree))), + "archive with GIT_DIR=" + gitDir + " and GIT_WORK_TREE=" + workTree); + } + + @Test + void aDotGitDirectoryConfiguredAsBareDoesNotMakeItsParentAWorkTree() throws Exception { + Git fixture = initializeCheckout(directory); + fixture.output("config", "core.bare", "true"); + + assertNull( + Git.findWorkTree(directory.toFile(), workTreeEnvironment(Map.of())), + ".git directory with core.bare=true"); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void anExplicitWorkTreeCanUseBareMetadataAtTheBuildRoot(boolean absolute) throws Exception { + Git fixture = new Git(directory.toFile(), workTreeEnvironment(Map.of())); + fixture.output("init", "--bare", "--initial-branch=main"); + String workTree = absolute ? directory.toString() : "."; + + assertEquals( + directory.toFile(), + Git.findWorkTree(directory.toFile(), workTreeEnvironment(Map.of("GIT_WORK_TREE", workTree))), + "bare metadata at the build root with GIT_WORK_TREE=" + workTree); + assertNull( + Git.findWorkTree(directory.toFile(), workTreeEnvironment(Map.of())), + "bare metadata at the build root without GIT_WORK_TREE"); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void aGitDirThatWorksFromTheCheckoutRootKeepsCommandsThere(boolean absolute) throws Exception { + initializeCheckout(directory); + Path module = Files.createDirectory(directory.resolve("module")); + String gitDir = absolute ? directory.resolve(".git").toString() : ".git"; + Map environment = workTreeEnvironment(Map.of("GIT_DIR", gitDir)); + + assertEquals( + directory.toFile(), + Git.findWorkTree(module.toFile(), environment), + "nested build with GIT_DIR=" + gitDir); + } + + @Test + void aRelativeGitDirStillFindsItsCheckoutAboveAnIntermediateBareRepository() throws Exception { + initializeCheckout(directory); + Path intermediate = Files.createDirectory(directory.resolve("intermediate")); + new Git(intermediate.toFile(), workTreeEnvironment(Map.of())).output("init", "--bare"); + Path module = Files.createDirectory(intermediate.resolve("module")); + + assertEquals( + directory.toFile(), + Git.findWorkTree(module.toFile(), workTreeEnvironment(Map.of("GIT_DIR", ".git"))), + "nested build with relative GIT_DIR and intermediate bare metadata"); + } + + @ParameterizedTest + @ValueSource(strings = {".", ".."}) + void aRelativeWorkTreeOverrideKeepsItsMeaningWhenCheckoutMetadataIsShared(String workTree) + throws Exception { + initializeCheckout(directory); + Path module = Files.createDirectory(directory.resolve("module")); + Map environment = + workTreeEnvironment( + Map.of("GIT_DIR", directory.resolve(".git").toString(), "GIT_WORK_TREE", workTree)); + + File commands = Git.findWorkTree(module.toFile(), environment); + + assertAll( + () -> assertEquals(module.toFile(), commands, "command directory for GIT_WORK_TREE=" + workTree), + () -> + assertEquals( + module.resolve(workTree).toRealPath().toFile(), + new File(new Git(commands, environment).output("rev-parse", "--show-toplevel")) + .getCanonicalFile(), + "effective work tree for GIT_WORK_TREE=" + workTree)); + } + + @Test + void separateMetadataCanExplicitlySelectTheEnclosingCheckoutAsItsWorkTree() throws Exception { + initializeCheckout(directory); + Path module = Files.createDirectory(directory.resolve("module")); + Path alternate = Files.createDirectory(directory.resolve("alternate")); + initializeCheckout(alternate); + Map environment = + workTreeEnvironment( + Map.of( + "GIT_DIR", alternate.resolve(".git").toString(), + "GIT_WORK_TREE", directory.toString())); + + assertEquals( + directory.toFile(), + Git.findWorkTree(module.toFile(), environment), + "independent metadata and explicit enclosing work tree"); + } + + @Test + void aGitDirMatchingTheTargetOfAnEnclosingGitFileUsesThatCheckout() throws Exception { + Path main = Files.createDirectory(directory.resolve("main")); + Git fixture = initializeCheckout(main); + Path linked = directory.resolve("linked"); + fixture.output("worktree", "add", "-b", "linked", linked.toString()); + Path module = Files.createDirectory(linked.resolve("module")); + String gitDir = + new Git(linked.toFile(), workTreeEnvironment(Map.of())).output("rev-parse", "--absolute-git-dir"); + + assertEquals( + linked.toFile(), + Git.findWorkTree(module.toFile(), workTreeEnvironment(Map.of("GIT_DIR", gitDir))), + "explicit GIT_DIR matching the linked .git file target"); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void aConfirmedWorkTreeOutranksARefusedCandidate(boolean invalidBuildMetadata) throws Exception { + initializeCheckout(directory); + Path module = Files.createDirectory(directory.resolve("module")); + Path checkoutAlternative = Files.createDirectory(directory.resolve("alternative")); + Path buildAlternative = Files.createDirectory(module.resolve("alternative")); + initializeCheckout(checkoutAlternative); + initializeCheckout(buildAlternative); + Path invalid = invalidBuildMetadata ? buildAlternative : checkoutAlternative; + Files.writeString(invalid.resolve(".git/config"), "[core]\n bare = invalid-boolean\n"); + Map environment = workTreeEnvironment(Map.of("GIT_DIR", "alternative/.git")); + + assertThrows( + CribroException.class, + () -> + new Git(invalid.getParent().toFile(), environment) + .output("rev-parse", "--is-inside-work-tree")); + assertEquals( + (invalidBuildMetadata ? directory : module).toFile(), + Git.findWorkTree(module.toFile(), environment), + "usable relative GIT_DIR with invalid metadata under " + invalid.getParent()); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void aCheckoutGitRefusesToReadKeepsTheNormalCoveragePath(boolean linked) throws Exception { + Path checkout = directory; + if (linked) { + Path main = Files.createDirectory(directory.resolve("main")); + Git fixture = initializeCheckout(main); + checkout = directory.resolve("linked"); + fixture.output("worktree", "add", "-b", "linked", checkout.toString()); + } else { + initializeCheckout(checkout); + } + Path module = Files.createDirectory(checkout.resolve("module")); + Map environment = + workTreeEnvironment(Map.of("GIT_TEST_ASSUME_DIFFERENT_OWNER", "1", "LC_ALL", "C")); + + CribroException failure = + assertThrows( + CribroException.class, + () -> + new Git(module.toFile(), environment) + .output("rev-parse", "--show-prefix", "--is-inside-work-tree")); + assertTrue(failure.getMessage().contains("dubious ownership"), failure::getMessage); + assertEquals( + checkout.toFile(), + Git.findWorkTree(module.toFile(), environment), + "checkout whose Git probe refuses ownership"); + } + + @ParameterizedTest + @ValueSource(strings = {"", "not a Git ref", "ref: HEAD", "439ab4"}) + void malformedHeadIsNotPlausibleMetadata(String head) throws Exception { + initializeCheckout(directory); + Path metadata = directory.resolve(".git"); + Files.writeString(metadata.resolve("HEAD"), head); + + assertAll( + () -> + assertNull( + Git.findWorkTree(directory.toFile(), workTreeEnvironment(Map.of())), + "unusable HEAD through .git"), + () -> + assertNull( + Git.findWorkTree( + directory.toFile(), workTreeEnvironment(Map.of("GIT_DIR", metadata.toString()))), + "unusable HEAD through GIT_DIR")); + } + + @ParameterizedTest + @ValueSource(strings = {"ref:refs/heads/main", "ref:\trefs/heads/main", "detached"}) + void recognizedHeadFormsKeepTheDiagnosticForARefusedCheckout(String headForm) throws Exception { + Git fixture = initializeCheckout(directory); + String head = headForm.equals("detached") ? fixture.output("rev-parse", "HEAD") : headForm; + Files.writeString(directory.resolve(".git/HEAD"), head + "\n"); + Map environment = + workTreeEnvironment(Map.of("GIT_TEST_ASSUME_DIFFERENT_OWNER", "1", "LC_ALL", "C")); + + CribroException refusal = + assertThrows( + CribroException.class, + () -> new Git(directory.toFile(), environment).output("rev-parse", "--is-inside-work-tree")); + + assertAll( + () -> assertTrue(refusal.getMessage().contains("dubious ownership"), refusal::getMessage), + () -> + assertEquals( + directory.toFile(), + Git.findWorkTree(directory.toFile(), environment), + "checkout with recognized HEAD whose Git probe refuses ownership")); + } + + @ParameterizedTest + @NullSource + @ValueSource(strings = "HEAD") + void changedLinesReportsAGitRefusalWhenItCannotResolveTheBase(String base) throws Exception { + initializeCheckout(directory); + Git git = + new Git( + directory.toFile(), + workTreeEnvironment(Map.of("GIT_TEST_ASSUME_DIFFERENT_OWNER", "1", "LC_ALL", "C"))); + + CribroException failure = assertThrows(CribroException.class, () -> git.changedLines(base)); + + assertTrue(failure.getMessage().contains("dubious ownership"), failure::getMessage); + } + + @Test + void relativeGitOverridesAreResolvedFromTheBuildDirectoryInsideACheckout() throws Exception { + initializeCheckout(directory); + Path module = Files.createDirectory(directory.resolve("module")); assertEquals( module.toFile(), - Git.findWorkTree(module.toFile(), Map.of("GIT_DIR", "../.git", "GIT_WORK_TREE", "..")), - "findWorkTree(parent/module)"); + Git.findWorkTree( + module.toFile(), workTreeEnvironment(Map.of("GIT_DIR", "../.git", "GIT_WORK_TREE", "."))), + "work tree selected relative to " + module); + } + + @Test + void aBareRepositoryInsideACheckoutDoesNotInheritTheOuterWorkTree() throws Exception { + initializeCheckout(directory); + Path nested = Files.createDirectory(directory.resolve("nested")); + new Git(nested.toFile(), workTreeEnvironment(Map.of())).output("init", "--bare"); + + assertAll( + () -> + assertNull( + Git.findWorkTree(nested.toFile(), workTreeEnvironment(Map.of())), + "bare repository inside a regular checkout"), + () -> + assertEquals( + nested.toFile(), + Git.findWorkTree( + nested.toFile(), workTreeEnvironment(Map.of("GIT_WORK_TREE", "."))), + "bare repository inside a regular checkout with an explicit work tree")); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void aConfiguredAncestorWorkTreeKeepsUsingTheNestedRepository(boolean ancestorHasRepository) + throws Exception { + if (ancestorHasRepository) { + initializeCheckout(directory); + } + Path nested = Files.createDirectory(directory.resolve("nested")); + Git fixture = initializeCheckout(nested); + String gitDir = fixture.output("rev-parse", "--absolute-git-dir"); + fixture.output("config", "core.worktree", "../.."); + Map environment = workTreeEnvironment(Map.of()); + + File commandDirectory = Git.findWorkTree(nested.toFile(), environment); + + assertAll( + () -> assertEquals(nested.toFile(), commandDirectory, "command directory for " + gitDir), + () -> + assertEquals( + gitDir, + new Git(commandDirectory, environment).outputOrNull("rev-parse", "--absolute-git-dir"), + "repository reached from " + commandDirectory)); + } + + @Test + void anEmptyDotGitDirectoryDoesNotHideTheEnclosingWorkTree() throws Exception { + Git fixture = initializeCheckout(directory); + Path module = Files.createDirectory(directory.resolve("module")); + Files.createDirectory(module.resolve(".git")); + Map environment = workTreeEnvironment(Map.of()); + + File commandDirectory = Git.findWorkTree(module.toFile(), environment); + + assertAll( + () -> + assertEquals( + directory.toRealPath().toFile(), + commandDirectory.getCanonicalFile(), + "work tree for " + module + " with an empty .git directory"), + () -> + assertEquals( + fixture.output("rev-parse", "--absolute-git-dir"), + new Git(commandDirectory, environment).outputOrNull("rev-parse", "--absolute-git-dir"), + "repository reached from " + commandDirectory)); + } + + @Test + void aWorkTreeOverrideAloneDoesNotSupplyRepositoryMetadata() throws Exception { + assertNull( + Git.findWorkTree(directory.toFile(), workTreeEnvironment(Map.of("GIT_WORK_TREE", "."))), + "source archive with GIT_WORK_TREE=."); + } + + private Git initializeCheckout(Path root) throws IOException { + Git fixture = new Git(root.toFile(), workTreeEnvironment(Map.of())); + fixture.output("init", "--initial-branch=main"); + Files.writeString(root.resolve("seed.txt"), "seed\n"); + fixture.output("add", "seed.txt"); + fixture.output( + "-c", + "user.name=Test", + "-c", + "user.email=test@example.com", + "-c", + "maintenance.auto=false", + "commit", + "-m", + "seed"); + return fixture; + } + + private Map workTreeEnvironment(Map overrides) { + Map environment = new HashMap<>(System.getenv()); + environment.keySet().removeIf(name -> name.regionMatches(true, 0, "GIT_", 0, 4)); + String noConfig = directory.resolve("no-git-config").toString(); + environment.put("GIT_CONFIG_GLOBAL", noConfig); + environment.put("GIT_CONFIG_SYSTEM", noConfig); + environment.putAll(overrides); + return environment; } @Test diff --git a/cribro-gradle-plugin/src/dist/cribro.init.gradle b/cribro-gradle-plugin/src/dist/cribro.init.gradle index 8e5fb29..ef20187 100644 --- a/cribro-gradle-plugin/src/dist/cribro.init.gradle +++ b/cribro-gradle-plugin/src/dist/cribro.init.gradle @@ -1,6 +1,6 @@ // Applies cribro to a build that does not apply it itself, which adds diffCoverage, changedLines, and -// pitestDiff to every Java project, has `test` print diff coverage, and adds the `cribro` task that -// prints how to use them: +// pitestDiff to every Java project and has `test` print diff coverage in a Git work tree. +// The `cribro` task prints how to use them: // ./gradlew --init-script /path/to/cribro.init.gradle -q cribro // The plugin is read from a cribro.jar beside this script where there is one, and otherwise // version @version@ is resolved from the Gradle Plugin Portal; a -SNAPSHOT version needs the jar to apply cribro. diff --git a/cribro-gradle-plugin/src/main/java/io/github/cribrodev/CribroPlugin.java b/cribro-gradle-plugin/src/main/java/io/github/cribrodev/CribroPlugin.java index e592312..9d3deef 100644 --- a/cribro-gradle-plugin/src/main/java/io/github/cribrodev/CribroPlugin.java +++ b/cribro-gradle-plugin/src/main/java/io/github/cribrodev/CribroPlugin.java @@ -24,7 +24,6 @@ import java.util.ArrayList; import java.util.Collection; import java.util.List; -import java.util.Map; import java.util.Set; import java.util.concurrent.Callable; import org.gradle.api.Plugin; @@ -54,15 +53,14 @@ /** * Adds {@code diffCoverage}, {@code changedLines}, and {@code pitestDiff} to every project that - * applies the {@code java} plugin, which the Kotlin JVM plugin does too, and has the {@code test} - * task report which of the lines the branch changed it executed. Every project, Java or not, gets - * the {@code cribroProjectElements} configuration, which tells the {@code cribro} task whether the - * project applies the java plugin. + * applies the {@code java} plugin, which the Kotlin JVM plugin does too. In a Git work tree, the + * {@code test} task reports which of the lines the branch changed it executed. Every project gets + * the {@code cribroProjectElements} configuration, which tells the {@code cribro} task whether + * the project applies the Java plugin. * *

{@link CribroSettingsPlugin} applies it, often from an init script to a build that knows - * nothing about it, so it overrides the build's own JaCoCo settings for the {@code test} task: a - * build that applies JaCoCo with the report switched off still gets the per-module XML report that - * diff coverage reads. + * nothing about it. In a Git work tree, it overrides the build's JaCoCo settings for {@code test} + * to produce the per-module XML report that diff coverage reads. */ public abstract class CribroPlugin implements Plugin { @@ -89,6 +87,8 @@ public abstract class CribroPlugin implements Plugin { private final List pendingOverrides = new ArrayList<>(); + private Provider buildWorkTree; + /** Whether {@link #projectEvaluated()} has run. */ private boolean evaluated; @@ -132,7 +132,7 @@ public void apply(Project project) { .withType( JavaPlugin.class, java -> { - Runnable overrides = configure(project); + Runnable overrides = configure(project, buildWorkTree); if (evaluated) { overrides.run(); } else { @@ -141,6 +141,10 @@ public void apply(Project project) { }); } + void workTree(Provider workTree) { + buildWorkTree = workTree; + } + /** * Applies the overrides of the build's own settings, and applies them at once to a java plugin * applied later. {@link CribroSettingsPlugin} calls it from {@code Gradle.afterProject}: Gradle @@ -154,12 +158,18 @@ void projectEvaluated() { } /** Registers the tasks and returns the overrides of the build's own settings. */ - private static Runnable configure(Project project) { + private static Runnable configure(Project project, Provider buildWorkTree) { ProviderFactory providers = project.getProviders(); // A build outside a git work tree, such as one from a source release, has no line to count as // changed. It is told at configuration time: whether `test` runs with the agent is an input of // `test`, so a later switch would cache an uninstrumented result under an instrumented key. - File workTree = Git.findWorkTree(project.getRootDir(), gitEnvironment(providers)); + Provider selection = + buildWorkTree != null + ? buildWorkTree + : providers.of( + GitWorkTree.class, + spec -> spec.getParameters().getBuildRoot().set(project.getRootDir())); + File workTree = selection.getOrNull(); boolean inWorkTree = workTree != null; // -Pcribro.diffCoverageEnabled=false keeps the tasks and drops the instrumentation of `test`, which // costs about 20% of its wall time, for a run that is not about coverage. @@ -168,7 +178,6 @@ private static Runnable configure(Project project) { .gradleProperty("cribro.diffCoverageEnabled") .map(it -> it.isEmpty() || Boolean.parseBoolean(it)) .getOrElse(true); - boolean diffCoverageEnabled = diffCoverageRequested && inWorkTree; Provider diffBase = providers.gradleProperty("cribro.diffBase"); String jacocoVersion = providers.gradleProperty("cribro.jacocoVersion").getOrNull(); @@ -218,20 +227,22 @@ private static Runnable configure(Project project) { task.setDescription( "Reports which of the lines this branch changed the last test run executed"); task.setGroup(LifecycleBasePlugin.VERIFICATION_GROUP); - // Read without a dependency on jacocoTestReport, so that running diffCoverage on its - // own reports on the last test run instead of running the tests again. - task.getReportFiles() - .from( - providers.provider( - () -> - project - .getTasks() - .named("jacocoTestReport", JacocoReport.class) - .get() - .getReports() - .getXml() - .getOutputLocation() - .get())); + if (inWorkTree) { + // Read without a dependency on jacocoTestReport, so that running diffCoverage on its + // own reports on the last test run instead of running the tests again. + task.getReportFiles() + .from( + providers.provider( + () -> + project + .getTasks() + .named("jacocoTestReport", JacocoReport.class) + .get() + .getReports() + .getXml() + .getOutputLocation() + .get())); + } task.getSourceRoots().set(mainSourceRoots); // A filtered run leaves the rest of the change looking unexecuted, so the scope is // printed beside the counts rather than left for the reader to remember. @@ -257,6 +268,12 @@ private static Runnable configure(Project project) { Runnable overrides = () -> { + if (!inWorkTree) { + if (diffCoverageRequested) { + testTask.configure(t -> t.finalizedBy(diffCoverage)); + } + return; + } // JaCoCo is applied only now, so that the build's own scripts show whether it uses it. boolean buildAppliesJacoco = project.getPluginManager().hasPlugin("jacoco"); project.getPluginManager().apply(JacocoPlugin.class); @@ -294,21 +311,18 @@ && compareVersions(jacoco.getToolVersion(), JACOCO_VERSION) < 0) { project.getTasks().named("jacocoTestReport", JacocoReport.class); testTask.configure( t -> { - t.getExtensions().getByType(JacocoTaskExtension.class).setEnabled(diffCoverageEnabled); - if (diffCoverageEnabled) { + t.getExtensions().getByType(JacocoTaskExtension.class).setEnabled(diffCoverageRequested); + if (diffCoverageRequested) { // Running the report as part of the test run keeps the XML in step with the // execution data, so diffCoverage cannot read line numbers from an earlier run. t.finalizedBy(jacocoTestReport); - } else if (diffCoverageRequested) { - // Outside a work tree, diffCoverage prints that it skipped the report. - t.finalizedBy(diffCoverage); } }); jacocoTestReport.configure( r -> { - r.setEnabled(diffCoverageEnabled); + r.setEnabled(diffCoverageRequested); r.getReports().getXml().getRequired().set(true); - if (diffCoverageEnabled) { + if (diffCoverageRequested) { r.finalizedBy(diffCoverage); } }); @@ -376,6 +390,15 @@ && compareVersions(jacoco.getToolVersion(), JACOCO_VERSION) < 0) { task -> { task.setDescription("Runs PIT mutation testing over the lines this branch changed"); task.setGroup(LifecycleBasePlugin.VERIFICATION_GROUP); + task.getChangedLinesFile().set(changedLines.flatMap(ChangedLinesTask::getOutputFile)); + task.getReportDir() + .set(project.getLayout().getBuildDirectory().dir("reports/pitest-diff")); + task.getRepositoryRoot().set(repositoryRoot); + if (!inWorkTree) { + // Configuration cache serialization resolves task inputs before checking onlyIf. + task.onlyIf("the build is in a git work tree", ignored -> false); + return; + } // Read while pitestDiff is configured: a provider derived from the test task's // provider would make pitestDiff run the whole test suite first. Test t = testTask.get(); @@ -389,7 +412,6 @@ && compareVersions(jacoco.getToolVersion(), JACOCO_VERSION) < 0) { task.getPitestClasspath().from(pitest); // This jar carries the changed-lines interceptor and the mutants listener. task.getPitestClasspath().from(pluginJar()); - task.getChangedLinesFile().set(changedLines.flatMap(ChangedLinesTask::getOutputFile)); task.getTestRuntimeClasspath().from(test.getRuntimeClasspath()); // pitest-junit5-plugin leaves the launcher to the tests, and a Gradle 8 build may // rely on the launcher Gradle injects into the test JVM, which PIT never sees. PIT @@ -403,9 +425,6 @@ && compareVersions(jacoco.getToolVersion(), JACOCO_VERSION) < 0) { task.getMainClassesDirs().from(main.getOutput().getClassesDirs()); task.getMainArtifacts().from(mainVariantArtifacts(testRuntime)); task.getMainSourceDirs().from((Callable>) () -> sourceDirs(main)); - task.getReportDir() - .set(project.getLayout().getBuildDirectory().dir("reports/pitest-diff")); - task.getRepositoryRoot().set(repositoryRoot); task.getTargetTests().set(providers.gradleProperty("cribro.pitestTargetTests")); task.getMutators() .set( @@ -554,15 +573,6 @@ private static int part(String[] parts, int index) { } } - /** - * Returns {@code GIT_DIR}, the variable that makes a work tree without {@code .git}, read through - * Gradle so that the configuration cache is invalidated when it changes. - */ - private static Map gitEnvironment(ProviderFactory providers) { - String gitDir = providers.environmentVariable("GIT_DIR").getOrNull(); - return gitDir == null ? Map.of() : Map.of("GIT_DIR", gitDir); - } - private static Provider intProperty( ProviderFactory providers, String name, int defaultValue) { return providers.gradleProperty(name).map(Integer::parseInt).orElse(defaultValue); diff --git a/cribro-gradle-plugin/src/main/java/io/github/cribrodev/CribroSettingsPlugin.java b/cribro-gradle-plugin/src/main/java/io/github/cribrodev/CribroSettingsPlugin.java index 9237f01..c70cc39 100644 --- a/cribro-gradle-plugin/src/main/java/io/github/cribrodev/CribroSettingsPlugin.java +++ b/cribro-gradle-plugin/src/main/java/io/github/cribrodev/CribroSettingsPlugin.java @@ -15,6 +15,7 @@ */ package io.github.cribrodev; +import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -61,11 +62,16 @@ public void apply(Settings settings) { ExtraPropertiesExtension extra = settings.getExtensions().getExtraProperties(); String initScript = extra.has(INIT_SCRIPT_PROPERTY) ? String.valueOf(extra.get(INIT_SCRIPT_PROPERTY)) : null; + Provider workTree = + settings.getProviders().of( + GitWorkTree.class, + spec -> spec.getParameters().getBuildRoot().set( + settings.getProviders().provider(() -> settings.getRootProject().getProjectDir()))); // Gradle.beforeProject runs for each project as Gradle configures it. allprojects would also // configure the projects that configure-on-demand skips, and Isolated Projects forbids it. settings .getGradle() - .beforeProject(project -> project.getPluginManager().apply(CribroPlugin.class)); + .beforeProject(project -> project.getPlugins().apply(CribroPlugin.class).workTree(workTree)); settings .getGradle() .afterProject(project -> project.getPlugins().getPlugin(CribroPlugin.class).projectEvaluated()); diff --git a/cribro-gradle-plugin/src/main/java/io/github/cribrodev/DiffCoverageTask.java b/cribro-gradle-plugin/src/main/java/io/github/cribrodev/DiffCoverageTask.java index c1221d8..65b19cf 100644 --- a/cribro-gradle-plugin/src/main/java/io/github/cribrodev/DiffCoverageTask.java +++ b/cribro-gradle-plugin/src/main/java/io/github/cribrodev/DiffCoverageTask.java @@ -100,8 +100,7 @@ public abstract class DiffCoverageTask extends DefaultTask { /** * The name the build registers {@link GitService} under. * - *

The registration and this reference share the constant because a reference that names an - * unregistered service fails only in a build that runs the task, which no test here does. + *

The task references the service by name, so it shares the registration's constant. */ public static final String GIT_SERVICE = "cribro.git"; @@ -118,9 +117,10 @@ public void report() throws IOException { } /** - * Returns the text this run prints, which is empty where the change reached none of the module, - * and outside a git work tree is the line saying so for the first task of the build that reports - * it and empty for the others. + * Returns the text this run prints, which is empty where the change reached none of the module. + * + *

Outside a Git work tree, returns the skip notice once per build. If a {@code changedLines} + * or {@code diffCoverage} task has already claimed the notice, returns an empty string. * *

Returning the text rather than logging it is what lets a test read the report: the scope * line naming the ref that resolved, the message of a run that measured nothing, and the note diff --git a/cribro-gradle-plugin/src/main/java/io/github/cribrodev/GitService.java b/cribro-gradle-plugin/src/main/java/io/github/cribrodev/GitService.java index a7a8916..ae7337a 100644 --- a/cribro-gradle-plugin/src/main/java/io/github/cribrodev/GitService.java +++ b/cribro-gradle-plugin/src/main/java/io/github/cribrodev/GitService.java @@ -37,8 +37,7 @@ public interface Parameters extends BuildServiceParameters { DirectoryProperty getRepositoryRoot(); /** - * Whether {@link #getRepositoryRoot()} lies in a git work tree; unset counts as true. Where it - * is false, the root is the build's root directory and no git command runs. + * Whether the service provides Git for {@link #getRepositoryRoot()}. Defaults to true. */ Property getInWorkTree(); } @@ -48,8 +47,8 @@ public interface Parameters extends BuildServiceParameters { private Git git; /** - * Returns git in the repository the parameters name, the same instance on every call, or null - * where the build lies in no git work tree. + * Returns the shared Git instance for the configured directory, or null when + * {@link Parameters#getInWorkTree()} is false. An unset parameter counts as true. */ public synchronized Git git() { if (!getParameters().getInWorkTree().getOrElse(true)) { @@ -61,7 +60,7 @@ public synchronized Git git() { return git; } - /** Returns the directory the parameters name, which lies in no work tree where git() is null. */ + /** Returns the directory configured in {@link Parameters#getRepositoryRoot()}. */ public File directory() { return getParameters().getRepositoryRoot().get().getAsFile(); } diff --git a/cribro-gradle-plugin/src/main/java/io/github/cribrodev/GitWorkTree.java b/cribro-gradle-plugin/src/main/java/io/github/cribrodev/GitWorkTree.java new file mode 100644 index 0000000..eb1be05 --- /dev/null +++ b/cribro-gradle-plugin/src/main/java/io/github/cribrodev/GitWorkTree.java @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2026 cribro contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.github.cribrodev; + +import java.io.File; +import org.gradle.api.Describable; +import org.gradle.api.provider.Property; +import org.gradle.api.provider.ValueSource; +import org.gradle.api.provider.ValueSourceParameters; + +/** Rechecks the Git work-tree selection when Gradle loads its cached task graph. */ +public abstract class GitWorkTree implements ValueSource, Describable { + + public interface Parameters extends ValueSourceParameters { + Property getBuildRoot(); + } + + @Override + public String getDisplayName() { + return "Git work-tree selection"; + } + + @Override + public File obtain() { + return Git.findWorkTree(getParameters().getBuildRoot().get(), System.getenv()); + } +} diff --git a/cribro-gradle-plugin/src/main/resources/io/github/cribrodev/guide.md b/cribro-gradle-plugin/src/main/resources/io/github/cribrodev/guide.md index 24b01f3..a414c59 100644 --- a/cribro-gradle-plugin/src/main/resources/io/github/cribrodev/guide.md +++ b/cribro-gradle-plugin/src/main/resources/io/github/cribrodev/guide.md @@ -126,16 +126,17 @@ The changed lines are the diff between the working tree and the merge base of `H `origin/HEAD`, `origin/main`, or `origin/master`. An upstream that is this branch pushed to a fork is skipped. For a stacked change, pass the parent branch: `-Pcribro.diffBase=`. -A build outside a git work tree, such as one from a source release, has no line to count as changed: `test` runs without -JaCoCo, no git command runs, and the build prints one line saying that diff coverage was skipped. A `.git` file, as in a -linked worktree, and `GIT_DIR` in the environment each mark a work tree. +Outside a Git work tree, cribro leaves the project's JaCoCo settings in place and skips diff coverage and mutation +testing. When automatic diff coverage is enabled, `test` prints one line for the build saying diff coverage was +skipped. A source release with no repository metadata can build without Git installed. Linked worktrees and valid +work trees selected through Git's environment variables support both reports. ## Properties | Property | Default | Effect | | --- | --- | --- | | `-Pcribro.diffBase=` | upstream, then `origin/HEAD`, `origin/main`, `origin/master` | The base of both reports | -| `-Pcribro.diffCoverageEnabled=false` | on | Runs `test` without JaCoCo and skips the report | +| `-Pcribro.diffCoverageEnabled=false` | on | Skips automatic diff coverage. In a Git work tree it also disables JaCoCo on `test` | | `-Pcribro.diffCoverageShowAll` | off | Prints the whole coverage report to the console | | `-Pcribro.diffCoverageMaxFiles=`, `-Pcribro.diffCoverageMaxLinesPerFile=`, `-Pcribro.diffCoverageMaxLines=` | `10`, `10`, `50` | How much of the coverage report the console shows | | `-Pcribro.pitestTargetTests=` | every test (`~.*`) | Tests allowed to kill a mutant | diff --git a/cribro-gradle-plugin/src/test/java/io/github/cribrodev/CribroPluginTest.java b/cribro-gradle-plugin/src/test/java/io/github/cribrodev/CribroPluginTest.java index f40eb8a..8776c51 100644 --- a/cribro-gradle-plugin/src/test/java/io/github/cribrodev/CribroPluginTest.java +++ b/cribro-gradle-plugin/src/test/java/io/github/cribrodev/CribroPluginTest.java @@ -46,8 +46,8 @@ class CribroPluginTest { @TempDir Path directory; /** - * Returns a project in the temporary directory that applies the java plugin and cribro, with - * the gradle.properties given. Resolving a configuration locks files under the Gradle user home + * Returns a project that applies Java and cribro with the given properties and a fixed work-tree + * selection. Resolving a configuration locks files under the Gradle user home * for the life of the JVM, so that home lies under the build directory rather than in the * temporary directory, which JUnit deletes after the test. */ @@ -59,7 +59,9 @@ private Project javaProject(String gradleProperties) throws IOException { .withGradleUserHomeDir(new File("build/tmp/projectBuilderUserHome")) .build(); project.getPluginManager().apply("java"); - project.getPluginManager().apply(CribroPlugin.class); + CribroPlugin plugin = project.getObjects().newInstance(CribroPlugin.class); + plugin.workTree(project.provider(project::getProjectDir)); + plugin.apply(project); return project; } @@ -74,8 +76,7 @@ private static SourceSet main(Project project) { class TheSourceRoots { /** - * Returns the roots changedLines reads. The temporary directory lies in no repository, so they - * are relative to the project directory. + * Returns the roots changedLines reads, relative to the temporary work tree. */ private List roots(Project project) { return project diff --git a/cribro-gradle-plugin/src/test/java/io/github/cribrodev/CribroSettingsPluginTest.java b/cribro-gradle-plugin/src/test/java/io/github/cribrodev/CribroSettingsPluginTest.java index ec78fbf..a169ddc 100644 --- a/cribro-gradle-plugin/src/test/java/io/github/cribrodev/CribroSettingsPluginTest.java +++ b/cribro-gradle-plugin/src/test/java/io/github/cribrodev/CribroSettingsPluginTest.java @@ -16,7 +16,11 @@ package io.github.cribrodev; import static java.nio.charset.StandardCharsets.UTF_8; +import static org.gradle.testkit.runner.TaskOutcome.SKIPPED; +import static org.gradle.testkit.runner.TaskOutcome.SUCCESS; +import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assumptions.assumeTrue; import java.io.IOException; @@ -37,8 +41,8 @@ * *

Each test runs Gradle on a build of a Java project {@code :app} and a project {@code :docs} * with no plugin. The init script is the one {@code dist} writes, copied with {@code cribro.jar} - * beside it, or alone where the test is about the missing jar; no test resolves anything from the - * network. + * beside it, or alone where the test is about the missing jar. The build with its own JaCoCo + * configuration resolves JaCoCo and JUnit from Maven Central. */ class CribroSettingsPluginTest { @@ -91,6 +95,7 @@ private GradleRunner runner(Path initScript, String... tasks) { arguments.add("--quiet"); arguments.addAll(List.of(tasks)); return GradleRunner.create() + .withEnvironment(fixtureEnvironment()) .withProjectDir(build.toFile()) .withPluginClasspath() .withArguments(arguments); @@ -499,14 +504,13 @@ void aBuildOutsideAWorkTreeRunsTestWithoutJacocoAndThenDiffCoverage() throws IOE Files.writeString( build.resolve("app/build.gradle"), "plugins { id 'java' }\n" + PRINT_COVERAGE_WIRING, UTF_8); - BuildResult result = - runner(null, ":app:printCoverageWiring").withEnvironment(environmentWithout("GIT_DIR")).build(); + BuildResult result = run(null, ":app:printCoverageWiring"); assertEquals( List.of( "jacoco on test: false", "test finalized by: [:app:diffCoverage]", - "jacocoTestReport finalized by: []"), + "jacocoTestReport: absent"), result.getOutput().lines().toList()); } @@ -517,43 +521,162 @@ void aBuildOutsideAWorkTreeWithDiffCoverageDisabledFinalizesNothing() throws IOE build.resolve("app/build.gradle"), "plugins { id 'java' }\n" + PRINT_COVERAGE_WIRING, UTF_8); BuildResult result = - runner(null, ":app:printCoverageWiring", "-Pcribro.diffCoverageEnabled=false") - .withEnvironment(environmentWithout("GIT_DIR")) - .build(); + run(null, ":app:printCoverageWiring", ":app:test", "-Pcribro.diffCoverageEnabled=false"); assertEquals( List.of( - "jacoco on test: false", "test finalized by: []", "jacocoTestReport finalized by: []"), + "jacoco on test: false", "test finalized by: []", "jacocoTestReport: absent"), result.getOutput().lines().toList()); } @Test - void gitDirInTheEnvironmentMakesAWorkTreeWithoutDotGit() throws IOException { + void anArchiveKeepsTheProjectsJacocoReportAndCoverageThreshold() throws IOException { writeBuild(" id 'io.github.cribro-dev.cribro'\n"); Files.writeString( - build.resolve("app/build.gradle"), "plugins { id 'java' }\n" + PRINT_COVERAGE_WIRING, UTF_8); - Map environment = environmentWithout("GIT_DIR"); - environment.put("GIT_DIR", home.resolve("repository.git").toString()); + build.resolve("app/build.gradle"), + """ + plugins { + id 'java' + id 'jacoco' + } + repositories { mavenCentral() } + dependencies { + testImplementation platform('org.junit:junit-bom:5.14.4') + testImplementation 'org.junit.jupiter:junit-jupiter' + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' + } + test { useJUnitPlatform() } + jacocoTestReport { + reports { xml.required = true } + } + jacocoTestCoverageVerification { + violationRules { + rule { + limit { + counter = 'LINE' + minimum = 1.0 + } + } + } + } + """, + UTF_8); + Path java = Files.createDirectories(build.resolve("app/src/main/java")); + Files.writeString( + java.resolve("Example.java"), + """ + class Example { + static int covered() { + return 1; + } + static int missed() { + return 2; + } + } + """, + UTF_8); + Path tests = Files.createDirectories(build.resolve("app/src/test/java")); + Files.writeString( + tests.resolve("ExampleTest.java"), + """ + import org.junit.jupiter.api.Test; + import static org.junit.jupiter.api.Assertions.assertEquals; + class ExampleTest { + @Test + void coversOneMethod() { + assertEquals(1, Example.covered()); + } + } + """, + UTF_8); - BuildResult result = runner(null, ":app:printCoverageWiring").withEnvironment(environment).build(); + BuildResult reportRun = runner(null, ":app:test", ":app:jacocoTestReport").build(); + Path report = build.resolve("app/build/reports/jacoco/test/jacocoTestReport.xml"); + String notice = "Diff coverage: skipped, since " + build.toRealPath() + " is not in a git work tree."; + assertAll( + () -> assertEquals(SUCCESS, reportRun.task(":app:test").getOutcome(), reportRun::getOutput), + () -> + assertEquals( + SUCCESS, reportRun.task(":app:jacocoTestReport").getOutcome(), reportRun::getOutput), + () -> { + String xml = Files.readString(report, UTF_8); + assertAll( + () -> assertTrue(xml.contains(" xml), + () -> assertTrue(xml.contains(" xml)); + }, + () -> + assertEquals( + List.of(notice), + reportRun.getOutput().lines().filter(line -> line.startsWith("Diff coverage:")).toList(), + reportRun::getOutput), + () -> { + BuildResult thresholdRun = runner(null, ":app:jacocoTestCoverageVerification").buildAndFail(); + assertTrue(thresholdRun.getOutput().contains("lines covered ratio"), thresholdRun::getOutput); + }); + } - assertEquals( - List.of( - "jacoco on test: true", - "test finalized by: [:app:jacocoTestReport]", - "jacocoTestReport finalized by: [:app:diffCoverage]"), - result.getOutput().lines().toList()); + @Test + void archivePitestDiffNeedsNoRepositoriesWithTheConfigurationCache() throws IOException { + writeBuild(" id 'io.github.cribro-dev.cribro'\n"); + + BuildResult result = + runner(null, ":app:pitestDiff", "--configuration-cache").build(); + + assertArchivePitestSkip(result); + } + + @Test + void archivePitestDiffNeedsNoCachedPitWithTheConfigurationCache() throws IOException { + writeBuild(" id 'io.github.cribro-dev.cribro'\n"); + Files.writeString( + build.resolve("app/build.gradle"), + "plugins { id 'java' }\nrepositories { mavenCentral() }\n", + UTF_8); + + BuildResult result = + runner(null, ":app:pitestDiff", "--configuration-cache", "--offline") + .withTestKitDir(home.toFile()) + .build(); + + assertArchivePitestSkip(result); + } + + @Test + void changedLinesAndTestShareOneSkipNoticeInAnArchive() throws IOException { + writeBuild(" id 'io.github.cribro-dev.cribro'\n"); + + BuildResult result = + runner(null, ":app:changedLines", ":app:test", ":app:pitestDiff", "--configuration-cache") + .build(); + + assertArchivePitestSkip(result); + } + + private void assertArchivePitestSkip(BuildResult result) throws IOException { + Path changedLines = build.resolve("app/build/diff/changed-lines.txt"); + String notice = "Diff coverage: skipped, since " + build.toRealPath() + " is not in a git work tree."; + assertAll( + () -> assertEquals(SKIPPED, result.task(":app:pitestDiff").getOutcome(), result::getOutput), + () -> assertEquals(SUCCESS, result.task(":app:changedLines").getOutcome(), result::getOutput), + () -> + assertEquals( + List.of(notice), + result.getOutput().lines().filter(line -> line.startsWith("Diff coverage:")).toList(), + result::getOutput), + () -> + assertEquals( + List.of("# not in a git work tree"), + Files.readAllLines(changedLines, UTF_8), + changedLines::toString)); } - /** Marks the build's directory as the root of a work tree, as a clone's {@code .git} does. */ - private void markAsWorkTree() throws IOException { - Files.createDirectory(build.resolve(".git")); + private void markAsWorkTree() { + new Git(build.toFile(), fixtureEnvironment()).output("init", "--quiet"); } - /** The environment of this JVM without the named variable. */ - private static Map environmentWithout(String name) { + private static Map fixtureEnvironment() { Map environment = new HashMap<>(System.getenv()); - environment.remove(name); + environment.keySet().removeIf(name -> name.regionMatches(true, 0, "GIT_", 0, 4)); return environment; } @@ -566,10 +689,14 @@ private static Map environmentWithout(String name) { tasks.register('printCoverageWiring') { doLast { def test = tasks.test - def report = tasks.jacocoTestReport - println "jacoco on test: ${test.jacoco.enabled}" + def report = tasks.findByName('jacocoTestReport') + println "jacoco on test: ${test.extensions.findByName('jacoco')?.enabled ?: false}" println "test finalized by: ${test.finalizedBy.getDependencies(test)*.path}" - println "jacocoTestReport finalized by: ${report.finalizedBy.getDependencies(report)*.path}" + if (report == null) { + println "jacocoTestReport: absent" + } else { + println "jacocoTestReport finalized by: ${report.finalizedBy.getDependencies(report)*.path}" + } } } """; diff --git a/cribro-gradle-plugin/src/test/java/io/github/cribrodev/OlderGradleTest.java b/cribro-gradle-plugin/src/test/java/io/github/cribrodev/OlderGradleTest.java index 0d125cd..8dab057 100644 --- a/cribro-gradle-plugin/src/test/java/io/github/cribrodev/OlderGradleTest.java +++ b/cribro-gradle-plugin/src/test/java/io/github/cribrodev/OlderGradleTest.java @@ -21,6 +21,8 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; +import java.util.HashMap; +import java.util.Map; import org.gradle.testkit.runner.BuildResult; import org.gradle.testkit.runner.GradleRunner; import org.junit.jupiter.api.Test; @@ -80,8 +82,12 @@ private String run(String buildScript) throws IOException { "plugins { id '" + CribroSettingsPlugin.ID + "' }\nrootProject.name = 'demo'\n", UTF_8); Files.writeString(build.resolve("build.gradle"), buildScript, UTF_8); + Map environment = new HashMap<>(System.getenv()); + environment.keySet().removeIf(name -> name.regionMatches(true, 0, "GIT_", 0, 4)); + new Git(build.toFile(), environment).output("init", "--quiet"); BuildResult result = GradleRunner.create() + .withEnvironment(environment) .withGradleVersion(GRADLE_VERSION) .withProjectDir(build.toFile()) .withPluginClasspath() diff --git a/cribro-gradle-plugin/src/test/java/io/github/cribrodev/OutsideWorkTreeTest.java b/cribro-gradle-plugin/src/test/java/io/github/cribrodev/OutsideWorkTreeTest.java index 915f3d0..c3d6367 100644 --- a/cribro-gradle-plugin/src/test/java/io/github/cribrodev/OutsideWorkTreeTest.java +++ b/cribro-gradle-plugin/src/test/java/io/github/cribrodev/OutsideWorkTreeTest.java @@ -16,6 +16,7 @@ package io.github.cribrodev; import static java.nio.charset.StandardCharsets.UTF_8; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -24,14 +25,19 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; +import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.stream.Collectors; +import org.gradle.testkit.runner.BuildResult; import org.gradle.testkit.runner.GradleRunner; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.DisabledOnOs; +import org.junit.jupiter.api.condition.OS; import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; /** * A build outside a git work tree, such as one from a source release, runs {@code test} without @@ -42,6 +48,18 @@ */ class OutsideWorkTreeTest { + private static final String SOURCE = "a/src/main/java/demo/a/Value.java"; + private static final String CHANGED_LINE = "demo/a/Value.java\t" + SOURCE + "\t4"; + private static final String JAVA_SOURCE = + """ + package demo.a; + public class Value { + public static int get() { + return %d; + } + } + """; + @TempDir Path directory; @Test @@ -49,40 +67,368 @@ void aBuildOutsideAWorkTreeRunsTestWithoutTheAgentAndSaysSoOnce() throws Excepti Path build = directory.resolve("export"); writeBuild(build); - String output = test(build, environmentWithoutGit()); + String output = runner(build, fixtureEnvironment(System.getenv()), "test").build().getOutput(); + + assertArchiveTestRun(build, output); + } + + @ParameterizedTest + @ValueSource(strings = {"no override", "missing relative GIT_DIR", "missing absolute GIT_DIR"}) + @DisabledOnOs(OS.WINDOWS) + void aBuildWithoutGitRunsItsTestsAndRemovesThePreviousDiffCoverageReport(String gitSelection) + throws Exception { + Path build = directory.resolve("export"); + writeBuild(build); + Path previousReport = build.resolve("a/build/reports/diff-coverage/test.txt"); + write( + previousReport, + """ + Diff coverage against HEAD (abcdef0), from :a:test + + All changed lines executed in 1 file. + + Total: 1/1 changed lines executed. All changed lines and branches are covered. + + Full JaCoCo report: + a/build/reports/jacoco/test/jacocoTestReport.xml + """); + Map overrides = switch (gitSelection) { + case "missing relative GIT_DIR" -> Map.of("GIT_DIR", "absent"); + case "missing absolute GIT_DIR" -> Map.of("GIT_DIR", directory.resolve("absent").toString()); + default -> Map.of(); + }; + + String output = runWithoutGit(build, overrides, 0); - List skipped = - output.lines().filter(line -> line.startsWith("Diff coverage:")).collect(Collectors.toList()); + assertAll( + () -> assertArchiveTestRun(build, output), + () -> assertFalse(Files.exists(previousReport), () -> previousReport + " after the build")); + } + + @Test + @DisabledOnOs(OS.WINDOWS) + void aCheckoutWithoutGitReportsTheLaunchErrorWhenDiffCoverageRuns() throws Exception { + Path build = directory.resolve("checkout"); + writeBuild(build); + commitBase(build, System.getenv()); + + String output = runWithoutGit(build, Map.of("GIT_DIR", ".git"), 1); + + Path testResults = build.resolve("a/build/test-results/test/TEST-demo.a.PassingTest.xml"); + assertAll( + () -> assertTrue(Files.isRegularFile(testResults), () -> testResults + " after the build"), + () -> assertTrue(output.contains("Execution failed for task ':a:diffCoverage'"), output), + () -> assertTrue(output.contains("cannot run git in "), output)); + } + + private String runWithoutGit(Path build, Map overrides, int exitCode) + throws IOException, InterruptedException { + write( + build.resolve("settings.gradle"), + """ + rootProject.name = 'demo' + include 'a', 'b' + try { + new ProcessBuilder('git', '--version').start().waitFor() + throw new GradleException('Git is available in the Gradle process') + } catch (IOException unavailable) { + println 'Git could not start' + } + """); + Path wrapper = Path.of("..", "gradle", "wrapper", "gradle-wrapper.jar").toAbsolutePath(); + Path initScript = Path.of(System.getProperty("cribro.dist"), "cribro.init.gradle"); + ProcessBuilder launcher = + new ProcessBuilder( + Path.of(System.getProperty("java.home"), "bin", "java").toString(), + "-classpath", + wrapper.toString(), + "org.gradle.wrapper.GradleWrapperMain", + "--quiet", + "--no-daemon", + "--init-script", + initScript.toString(), + "test") + .directory(build.toFile()) + .redirectErrorStream(true); + Map environment = launcher.environment(); + Map fixture = fixtureEnvironment(environment); + environment.clear(); + environment.putAll(fixture); + environment.putAll(overrides); + environment.put("PATH", Files.createDirectory(directory.resolve("empty-path")).toString()); + + Process process = launcher.start(); + String output = new String(process.getInputStream().readAllBytes(), UTF_8); + assertEquals(exitCode, process.waitFor(), output); + assertTrue(output.lines().anyMatch("Git could not start"::equals), output); + return output; + } + + private static void assertArchiveTestRun(Path build, String output) throws IOException { + Path testResults = build.resolve("a/build/test-results/test/TEST-demo.a.PassingTest.xml"); + String notice = "Diff coverage: skipped, since " + build.toRealPath() + " is not in a git work tree."; assertAll( () -> assertEquals( - List.of(DiffCoverage.notInWorkTree(build.toRealPath().toFile())), - skipped, + List.of(notice), + output.lines().filter(line -> line.startsWith("Diff coverage:")).toList(), "diff coverage lines of a build with modules a and b; whole output:\n" + output), + () -> assertTrue(Files.isRegularFile(testResults), () -> testResults + " after the build"), () -> assertFalse(Files.exists(build.resolve("a/build/jacoco/test.exec")), "a/build/jacoco/test.exec exists"), () -> assertFalse(Files.exists(build.resolve("b/build/jacoco/test.exec")), "b/build/jacoco/test.exec exists")); } @Test void aLinkedWorktreeRunsTestWithTheAgent() throws Exception { + Map environment = fixtureEnvironment(System.getenv()); Path main = directory.resolve("main"); writeBuild(main); - git(main, "init", "-q", "--initial-branch=main"); - git(main, "add", "-A"); - git(main, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "-m", "base"); - Path linked = directory.resolve("linked"); - git(main, "worktree", "add", "-q", linked.toString()); + commitBase(main, environment); + Path linked = linkedWorktree(main, environment); + write(linked.resolve(SOURCE), JAVA_SOURCE.formatted(2)); - String output = test(linked, environmentWithoutGit()); + String output = + runner(linked, environment, "test", ":a:changedLines", "-Pcribro.diffBase=HEAD") + .build().getOutput(); assertAll( () -> assertTrue(Files.exists(linked.resolve("a/build/jacoco/test.exec")), "a/build/jacoco/test.exec exists"), + () -> assertChangedLine(linked), + () -> assertCoverageReportNamesTheChangedLine(linked), () -> assertFalse( output.contains("is not in a git work tree"), "output of a build in a linked worktree:\n" + output)); } + @Test + void relativeGitDirWithAnIndexProvidesChangedLines() throws Exception { + Path build = directory.resolve("export"); + Map environment = fixtureEnvironment(System.getenv()); + writeBuild(build); + commitBase(build, environment); + Files.move(build.resolve(".git"), directory.resolve("metadata.git")); + write(build.resolve(SOURCE), JAVA_SOURCE.formatted(2)); + + testAndListChangedLines(build, Map.of("GIT_DIR", "../metadata.git")); + + assertAll( + () -> assertChangedLine(build), + () -> assertCoverageReportNamesTheChangedLine(build)); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void separateMetadataInsideAnUnrelatedCheckoutReportsTheBuildLocalChange(boolean explicitWorkTree) + throws Exception { + Path checkout = directory.resolve("checkout"); + write(checkout.resolve("seed.txt"), "outer checkout\n"); + commitBase(checkout, System.getenv()); + Path build = checkout.resolve("nested"); + writeBuild(build); + commitBase(build, System.getenv()); + if (explicitWorkTree) { + git(build, System.getenv(), "config", "core.bare", "true"); + } + Path metadata = Files.move(build.resolve(".git"), directory.resolve("metadata.git")); + write(build.resolve(SOURCE), JAVA_SOURCE.formatted(2)); + Map overrides = + explicitWorkTree + ? Map.of("GIT_DIR", metadata.toString(), "GIT_WORK_TREE", ".") + : Map.of("GIT_DIR", metadata.toString()); + + changedLines(build, overrides); + + assertChangedLine(build); + } + + @ParameterizedTest + @ValueSource(strings = {"relative GIT_DIR", "absolute GIT_DIR", "absolute GIT_WORK_TREE"}) + void aNestedBuildWithGitOverridesReportsTheCheckoutRelativeChange(String gitSelection) + throws Exception { + Path checkout = directory.resolve("checkout"); + Path build = checkout.resolve("nested"); + writeBuild(build); + commitBase(checkout, System.getenv()); + write(build.resolve(SOURCE), JAVA_SOURCE.formatted(2)); + Map overrides = switch (gitSelection) { + case "relative GIT_DIR" -> Map.of("GIT_DIR", ".git"); + case "absolute GIT_DIR" -> Map.of("GIT_DIR", checkout.resolve(".git").toString()); + default -> Map.of("GIT_WORK_TREE", checkout.toRealPath().toString()); + }; + + changedLines(build, overrides); + + assertChangedLine(build, "demo/a/Value.java\tnested/" + SOURCE + "\t4"); + } + + @ParameterizedTest + @ValueSource(strings = {"relative GIT_DIR", "absolute GIT_DIR", ".git"}) + void bareMetadataNeedsAnExplicitWorkTree(String layout) throws Exception { + Path build = directory.resolve("export"); + Map environment = fixtureEnvironment(System.getenv()); + writeBuild(build); + commitBase(build, environment); + Path metadata = build.resolve(".git"); + git(build, environment, "config", "core.bare", "true"); + Map overrides = new HashMap<>(); + if (!layout.equals(".git")) { + metadata = Files.move(metadata, directory.resolve("metadata.git")); + overrides.put("GIT_DIR", layout.equals("relative GIT_DIR") ? "../metadata.git" : metadata.toString()); + } + write(build.resolve(SOURCE), JAVA_SOURCE.formatted(2)); + + String output = + runnerWithOverrides( + build, overrides, "test", ":a:changedLines", "-Pcribro.diffBase=HEAD") + .build().getOutput(); + + assertArchiveTestRun(build, output); + assertEquals( + List.of("# not in a git work tree"), + Files.readAllLines(build.resolve("a/build/diff/changed-lines.txt")), + "changed-lines file with bare metadata"); + + overrides.put("GIT_WORK_TREE", "."); + testAndListChangedLines(build, overrides); + + assertAll( + () -> assertChangedLine(build), + () -> assertCoverageReportNamesTheChangedLine(build)); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void aWorkTreeCanUseTheMetadataInItsOwnRoot(boolean absoluteWorkTree) throws Exception { + Path build = directory.resolve("export"); + Map environment = fixtureEnvironment(System.getenv()); + writeBuild(build); + commitBase(build, environment); + git(build, environment, "config", "core.bare", "true"); + Path metadata = build.resolve(".git"); + try (var files = Files.list(metadata)) { + for (Path entry : files.toList()) { + Files.move(entry, build.resolve(entry.getFileName())); + } + } + Files.delete(metadata); + write(build.resolve(SOURCE), JAVA_SOURCE.formatted(2)); + + changedLines(build, Map.of("GIT_WORK_TREE", absoluteWorkTree ? build.toString() : ".")); + + assertChangedLine(build); + } + + @Test + void aChangedWorkTreeSelectionInvalidatesTheConfigurationCache() throws Exception { + Path build = directory.resolve("export"); + Map environment = fixtureEnvironment(System.getenv()); + writeBuild(build); + Files.writeString( + build.resolve("build.gradle"), + "\nlogger.quiet('Configuring the test build')\n", + StandardOpenOption.APPEND); + commitBase(build, environment); + write(build.resolve(SOURCE), JAVA_SOURCE.formatted(2)); + String[] tasks = {"--configuration-cache", ":a:changedLines", "-Pcribro.diffBase=HEAD"}; + + String configured = runner(build, environment, tasks).build().getOutput(); + assertTrue(configured.contains("Configuring the test build"), configured); + assertChangedLine(build); + String cached = runner(build, environment, tasks).build().getOutput(); + assertFalse(cached.contains("Configuring the test build"), cached); + + git(build, environment, "config", "core.bare", "true"); + runner(build, environment, tasks).build(); + assertEquals( + List.of("# not in a git work tree"), + Files.readAllLines(build.resolve("a/build/diff/changed-lines.txt")), + "changed-lines file after the metadata becomes bare"); + } + + private static void changedLines(Path build, Map overrides) { + runnerWithOverrides(build, overrides, ":a:changedLines", "-Pcribro.diffBase=HEAD").build(); + } + + private static void testAndListChangedLines(Path build, Map overrides) { + runnerWithOverrides(build, overrides, ":a:test", ":a:changedLines", "-Pcribro.diffBase=HEAD") + .build(); + } + + private static void assertChangedLine(Path build) throws IOException { + assertChangedLine(build, CHANGED_LINE); + } + + private static void assertChangedLine(Path build, String expected) throws IOException { + Path changedLines = build.resolve("a/build/diff/changed-lines.txt"); + assertEquals( + List.of(expected), + Files.readAllLines(changedLines).stream().filter(line -> !line.startsWith("#")).toList(), + changedLines::toString); + } + + private static void assertCoverageReportNamesTheChangedLine(Path build) throws IOException { + Path report = build.resolve("a/build/reports/diff-coverage/test.txt"); + List lines = Files.readAllLines(report); + assertEquals( + List.of(" " + SOURCE, " 4: not executed: return 2;"), + lines.stream() + .filter(line -> line.contains(SOURCE) || line.contains("4: not executed:")) + .toList(), + () -> report + ":\n" + String.join("\n", lines)); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void theLinkedWorktreeFixtureLeavesTheCallerRepositoryAndIndexAlone(boolean selectCallerWorkTree) + throws Exception { + Map clean = fixtureEnvironment(System.getenv()); + Path caller = directory.resolve("caller"); + Path source = caller.resolve("kept.txt"); + write(source, "base\n"); + commitBase(caller, clean); + Path index = caller.resolve(".git/index"); + Path alternateIndex = Files.copy(index, directory.resolve("caller-index")); + write(source, "uncommitted edit\n"); + String head = git(caller, clean, "rev-parse", "HEAD"); + byte[] indexBefore = Files.readAllBytes(index); + byte[] alternateBefore = Files.readAllBytes(alternateIndex); + + Map ambient = new HashMap<>(clean); + ambient.put("GIT_INDEX_FILE", alternateIndex.toString()); + if (selectCallerWorkTree) { + ambient.put("GIT_DIR", caller.resolve(".git").toString()); + ambient.put("GIT_WORK_TREE", caller.toString()); + } + Path main = directory.resolve("main"); + writeBuild(main); + commitBase(main, ambient); + Path linked = linkedWorktree(main, ambient); + + BuildResult result = runner(linked, ambient, "changedLines", "-Pcribro.diffBase=HEAD").build(); + assertAll( + () -> assertTrue(Files.isRegularFile(linked.resolve(".git")), () -> linked + " markers"), + () -> assertFalse(result.getOutput().contains("is not in a git work tree"), result::getOutput), + () -> assertEquals(head, git(caller, clean, "rev-parse", "HEAD"), "caller HEAD"), + () -> assertArrayEquals(indexBefore, Files.readAllBytes(index), "caller index"), + () -> assertArrayEquals(alternateBefore, Files.readAllBytes(alternateIndex), "caller alternate index"), + () -> assertEquals("uncommitted edit\n", Files.readString(source), "caller file")); + } + + private static Path linkedWorktree(Path main, Map environment) + throws IOException, InterruptedException { + Path linked = main.resolveSibling("linked"); + git(main, environment, "worktree", "add", "-q", linked.toString()); + return linked; + } + + private static void commitBase(Path build, Map environment) + throws IOException, InterruptedException { + git(build, environment, "init", "-q", "--initial-branch=main"); + git(build, environment, "add", "-A"); + git(build, environment, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "-m", "base"); + } + /** Writes a build of two modules, a and b, each with one passing JUnit test. */ private static void writeBuild(Path build) throws IOException { write( @@ -104,6 +450,7 @@ testImplementation platform('org.junit:junit-bom:5.14.4') test { useJUnitPlatform() } } """); + write(build.resolve(SOURCE), JAVA_SOURCE.formatted(1)); for (String module : List.of("a", "b")) { write( build.resolve(module + "/src/test/java/demo/" + module + "/PassingTest.java"), @@ -127,31 +474,50 @@ private static void write(Path file, String text) throws IOException { } /** The environment of this JVM without the variables that point git at a repository. */ - private static Map environmentWithoutGit() { - Map environment = new HashMap<>(System.getenv()); - environment.remove("GIT_DIR"); - environment.remove("GIT_WORK_TREE"); + private static Map fixtureEnvironment(Map ambient) { + Map environment = new HashMap<>(ambient); + environment.keySet().removeIf(name -> name.regionMatches(true, 0, "GIT_", 0, 4)); return environment; } - private static String test(Path build, Map environment) { + private static GradleRunner runner(Path build, Map environment, String... tasks) { + return runnerWithOverrides(build, environment, Map.of(), tasks); + } + + private static GradleRunner runnerWithOverrides( + Path build, Map overrides, String... tasks) { + return runnerWithOverrides(build, System.getenv(), overrides, tasks); + } + + private static GradleRunner runnerWithOverrides( + Path build, Map ambient, Map overrides, String... tasks) { + Map environment = fixtureEnvironment(ambient); + environment.putAll(overrides); + List arguments = new ArrayList<>(List.of("--quiet")); + arguments.addAll(List.of(tasks)); return GradleRunner.create() .withProjectDir(build.toFile()) .withPluginClasspath() .withEnvironment(environment) - .withArguments("--quiet", "test") - .build() - .getOutput(); + .withArguments(arguments); } - private static void git(Path directory, String... arguments) + private static String git(Path directory, Map environment, String... arguments) throws IOException, InterruptedException { List command = new ArrayList<>(); command.add("git"); + command.addAll(List.of("-c", "maintenance.auto=false")); command.addAll(List.of(arguments)); - Process process = - new ProcessBuilder(command).directory(directory.toFile()).redirectErrorStream(true).start(); + ProcessBuilder builder = + new ProcessBuilder(command).directory(directory.toFile()).redirectErrorStream(true); + builder.environment().clear(); + builder.environment().putAll(fixtureEnvironment(environment)); + String noConfig = directory.resolve("absent-git-config").toAbsolutePath().toString(); + builder.environment().put("GIT_CONFIG_GLOBAL", noConfig); + builder.environment().put("GIT_CONFIG_SYSTEM", noConfig); + Process process = builder.start(); String output = new String(process.getInputStream().readAllBytes(), UTF_8); assertEquals(0, process.waitFor(), () -> String.join(" ", command) + "\n" + output); + return output.strip(); } } diff --git a/cribro-maven-plugin/src/main/java/io/github/cribrodev/maven/CoverageReport.java b/cribro-maven-plugin/src/main/java/io/github/cribrodev/maven/CoverageReport.java index 3e2f568..452cecb 100644 --- a/cribro-maven-plugin/src/main/java/io/github/cribrodev/maven/CoverageReport.java +++ b/cribro-maven-plugin/src/main/java/io/github/cribrodev/maven/CoverageReport.java @@ -78,7 +78,12 @@ final class CoverageReport { this.state = state; } - /** Returns the text to print, which is empty where no test ran under cribro. */ + /** + * Returns the coverage report or skip notice for the recorded Surefire executions. + * + *

With no recorded execution, returns an empty string. Outside a Git work tree, a recorded + * execution yields the skip notice even if Surefire ran no tests. + */ String describe() throws IOException { List projects = session.getProjects(); List runs = state.runs(projects); diff --git a/cribro-maven-plugin/src/main/java/io/github/cribrodev/maven/CribroMojoListener.java b/cribro-maven-plugin/src/main/java/io/github/cribrodev/maven/CribroMojoListener.java index 2922921..c291052 100644 --- a/cribro-maven-plugin/src/main/java/io/github/cribrodev/maven/CribroMojoListener.java +++ b/cribro-maven-plugin/src/main/java/io/github/cribrodev/maven/CribroMojoListener.java @@ -40,14 +40,12 @@ import org.jacoco.agent.AgentJar; /** - * Attaches the JaCoCo agent to the test JVM of surefire's {@code default-test} execution, and - * records the run for the report. + * Records Surefire's {@code default-test} execution for automatic diff coverage. * - *

The agent goes into the {@code argLine} of the configured mojo, just before it runs, so it - * reaches the tests whatever the project wrote there: an {@code argLine} that replaces the one - * JaCoCo's own plugin sets, or none. Where the {@code argLine} already attaches a JaCoCo agent, as - * a project using {@code jacoco-maven-plugin} does, cribro reads that agent's file rather than - * attaching a second. + *

In a Git work tree, cribro attaches JaCoCo to the configured mojo's {@code argLine} just + * before Surefire runs. If the {@code argLine} already attaches JaCoCo, cribro reads that agent's + * file. Outside a work tree, cribro leaves the {@code argLine} as configured and records the + * execution for the skip notice. */ @Named("cribro") @Singleton @@ -82,8 +80,6 @@ public void beforeMojoExecution(MojoExecutionEvent event) { long start = System.currentTimeMillis(); CribroState state = CribroState.of(session); if (state.git() == null) { - // No line can count as changed outside a work tree, so the tests run without the agent; the - // run is still recorded, so that the report says why it skipped. state.started(TestRun.unmeasured(project, start, null)); return; } diff --git a/cribro-maven-plugin/src/main/resources/io/github/cribrodev/maven/guide.md b/cribro-maven-plugin/src/main/resources/io/github/cribrodev/maven/guide.md index 54044c0..292d3c7 100644 --- a/cribro-maven-plugin/src/main/resources/io/github/cribrodev/maven/guide.md +++ b/cribro-maven-plugin/src/main/resources/io/github/cribrodev/maven/guide.md @@ -136,9 +136,10 @@ The changed lines are the diff between the working tree and the merge base of `H `origin/HEAD`, `origin/main`, or `origin/master`. An upstream that is this branch pushed to a fork is skipped. For a stacked change, pass the parent branch: `-Dcribro.diffBase=`. -A build outside a git work tree, such as one from a source release, has no line to count as changed: the tests run -without JaCoCo, no git command runs, and the build prints one line saying that diff coverage was skipped. A `.git` file, -as in a linked worktree, and `GIT_DIR` in the environment each mark a work tree. +Outside a Git work tree, cribro leaves Surefire's `argLine` as configured in the POM and skips diff coverage and +mutation testing. When automatic diff coverage is enabled, the session prints one line saying diff coverage was +skipped after a Surefire test execution is recorded. A source release with no repository metadata can build without +Git installed. Linked worktrees and valid work trees selected through Git's environment variables support both reports. ## Properties @@ -148,7 +149,7 @@ Pass a property with `-D`, or set it in `.mvn/maven.config` or in the `` | upstream, then `origin/HEAD`, `origin/main`, `origin/master` | The base of both reports | -| `-Dcribro.diffCoverageEnabled=false` | on | Runs the tests without JaCoCo and skips the report | +| `-Dcribro.diffCoverageEnabled=false` | on | Skips automatic diff coverage and leaves Surefire's `argLine` as configured in the POM | | `-Dcribro.diffCoverageShowAll` | off | Prints the whole coverage report to the console | | `-Dcribro.diffCoverageMaxFiles=`, `-Dcribro.diffCoverageMaxLinesPerFile=`, `-Dcribro.diffCoverageMaxLines=` | `10`, `10`, `50` | How much of the coverage report the console shows | | `-Dcribro.pitestTargetTests=` | surefire's includes | Tests allowed to kill a mutant | diff --git a/cribro-maven-plugin/src/test/java/io/github/cribrodev/maven/MavenIntegrationTest.java b/cribro-maven-plugin/src/test/java/io/github/cribrodev/maven/MavenIntegrationTest.java index ed4fd4d..ec4390b 100644 --- a/cribro-maven-plugin/src/test/java/io/github/cribrodev/maven/MavenIntegrationTest.java +++ b/cribro-maven-plugin/src/test/java/io/github/cribrodev/maven/MavenIntegrationTest.java @@ -20,7 +20,6 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; -import io.github.cribrodev.DiffCoverage; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; @@ -29,16 +28,19 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import java.util.Map; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.function.Executable; import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; +import org.junit.jupiter.params.provider.ValueSource; /** - * Runs a real Maven on small projects in a git repository, with cribro loaded each way a build can - * load it. + * Measures changed lines in Maven builds and skips diff reports for builds without a Git work tree. * - *

Maven resolves cribro from the repository the build publishes to, and everything else from - * Maven Central. + *

The fixtures start Maven with each supported way of loading Cribro. Maven resolves Cribro from + * the repository the build publishes to, and everything else from Maven Central. */ class MavenIntegrationTest { @@ -113,13 +115,68 @@ void aBuildOutsideAWorkTreeRunsItsTestsWithoutTheAgent() throws Exception { write(project.resolve("src/test/java/org/apache/commons/lang3/ArrayUtilsTest.java"), TEST_CLASS); String test = maven(project, 0, "test"); + assertArchiveCoverageSkipped(project, test); + } + + private enum BareMetadata { + RELATIVE_GIT_DIR, + ABSOLUTE_GIT_DIR, + DOT_GIT + } + + @ParameterizedTest + @EnumSource(BareMetadata.class) + void aBuildWithBareMetadataSkipsDiffCoverageAndMutationTesting(BareMetadata layout) + throws Exception { + Path project = singleModule(); + run(project, 0, "git", "config", "core.bare", "true"); + Map environment = Map.of(); + if (layout != BareMetadata.DOT_GIT) { + Path metadata = Files.move(project.resolve(".git"), directory.resolve("metadata.git")); + Path gitDir = + layout == BareMetadata.RELATIVE_GIT_DIR ? project.relativize(metadata) : metadata; + environment = Map.of("GIT_DIR", gitDir.toString()); + } + String output = + maven(project, 0, environment, "-Dcribro.diffBase=HEAD", "test", "cribro:pitest-diff"); + + String pitNotice = "Skipped: " + project.toRealPath() + " is not in a git work tree."; assertAll( - () -> - assertBefore( - test, - DiffCoverage.notInWorkTree(project.toRealPath().toFile()), - "BUILD SUCCESS"), + () -> assertArchiveCoverageSkipped(project, output), + () -> assertBefore(output, pitNotice, "BUILD SUCCESS")); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void aBuildWithRelativeGitDirReportsItsChangedLines(boolean explicitWorkTree) throws Exception { + Path project = singleModule(); + run(project, 0, "git", "config", "core.bare", Boolean.toString(explicitWorkTree)); + Path metadata = Files.move(project.resolve(".git"), directory.resolve("metadata.git")); + String gitDir = project.relativize(metadata).toString(); + Map environment = + explicitWorkTree ? Map.of("GIT_DIR", gitDir, "GIT_WORK_TREE", ".") : Map.of("GIT_DIR", gitDir); + + String output = maven(project, 0, environment, "-Dcribro.diffBase=HEAD", "test"); + + assertBefore( + output, + String.join( + "\n", + " src/main/java/org/apache/commons/lang3/ArrayUtils.java", + " 2/3 changed lines executed, 1/2 branches covered", + " uncovered changed code:", + " 5: 1 of 2 branches covered: if (x < 0) {", + " 12: not executed: return x + 1;"), + "BUILD SUCCESS"); + } + + private static void assertArchiveCoverageSkipped(Path project, String output) throws IOException { + String notice = + "Diff coverage: skipped, since " + project.toRealPath() + " is not in a git work tree."; + assertAll( + () -> assertBefore(output, notice, "BUILD SUCCESS"), + () -> assertContains(output, "Tests run: 1, Failures: 0, Errors: 0, Skipped: 0"), () -> assertFalse( Files.exists(project.resolve("target/cribro/jacoco.exec")), @@ -572,6 +629,12 @@ private void commitAsBase(Path project) throws IOException, InterruptedException /** Runs Maven in the project and returns its output, after checking its exit code. */ private String maven(Path project, int exitCode, String... arguments) throws IOException, InterruptedException { + return maven(project, exitCode, Map.of(), arguments); + } + + private String maven( + Path project, int exitCode, Map gitEnvironment, String... arguments) + throws IOException, InterruptedException { Path settings = directory.resolve("settings.xml"); if (!Files.exists(settings)) { String url = new File(System.getProperty("cribro.it.repository")).toURI().toString(); @@ -602,11 +665,17 @@ private String maven(Path project, int exitCode, String... arguments) settings.toString(), "-Dmaven.repo.local=" + System.getProperty("cribro.it.localRepository"))); command.addAll(Arrays.asList(arguments)); - return run(project, exitCode, command.toArray(new String[0])); + return run(project, exitCode, gitEnvironment, command.toArray(new String[0])); } private String run(Path workingDirectory, int exitCode, String... command) throws IOException, InterruptedException { + return run(workingDirectory, exitCode, Map.of(), command); + } + + private String run( + Path workingDirectory, int exitCode, Map gitEnvironment, String... command) + throws IOException, InterruptedException { Path log = Files.createTempFile(directory, "out", ".log"); ProcessBuilder builder = new ProcessBuilder(command) @@ -616,8 +685,8 @@ private String run(Path workingDirectory, int exitCode, String... command) builder.environment().put("JAVA_HOME", System.getProperty("java.home")); builder.environment().remove("MAVEN_OPTS"); builder.environment().remove("MAVEN_ARGS"); - builder.environment().remove("GIT_DIR"); - builder.environment().remove("GIT_WORK_TREE"); + builder.environment().keySet().removeIf(name -> name.regionMatches(true, 0, "GIT_", 0, 4)); + builder.environment().putAll(gitEnvironment); Process process = builder.start(); process.getOutputStream().close(); int actual = process.waitFor();