diff --git a/CHANGES.md b/CHANGES.md index ef626e792a..2e5d39803e 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -13,6 +13,7 @@ We adhere to the [keepachangelog](https://keepachangelog.com/en/1.0.0/) format ( ### Changes - Bump default Eclipse JDT formatter version from `4.40` to `4.41`. +- GitPrePushHookInstaller takes optional parameter for pre push hook directory, instead of always writing to .git/hooks. ([#3115](https://github.com/diffplug/spotless/pull/3115) - Bump default `gherkin` version `42.0.0` -> `42.0.1`. ([#3088](https://github.com/diffplug/spotless/pull/3088)) - Bump default `jackson` version `2.22.2` -> `2.22.3`. ([#3101](https://github.com/diffplug/spotless/pull/3101)) - Bump default `palantir-java-format` version `2.98.0` -> `2.99.0`. ([#3103](https://github.com/diffplug/spotless/pull/3103)) diff --git a/lib/src/main/java/com/diffplug/spotless/GitPrePushHookInstaller.java b/lib/src/main/java/com/diffplug/spotless/GitPrePushHookInstaller.java index fe262e8afd..936fdd4b25 100644 --- a/lib/src/main/java/com/diffplug/spotless/GitPrePushHookInstaller.java +++ b/lib/src/main/java/com/diffplug/spotless/GitPrePushHookInstaller.java @@ -1,5 +1,5 @@ /* - * Copyright 2025 DiffPlug + * Copyright 2025-2026 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,6 +24,8 @@ import java.nio.file.Files; import java.util.Locale; +import javax.annotation.Nullable; + import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; /** @@ -51,6 +53,11 @@ public abstract class GitPrePushHookInstaller { */ protected final File root; + /** + * Optional directory set in core.hooksPath. + */ + @Nullable protected final File hooksRoot; + /** * Constructor to initialize the GitPrePushHookInstaller with a logger and repository root path. * @@ -58,8 +65,20 @@ public abstract class GitPrePushHookInstaller { * @param root The root directory of the Git repository. */ protected GitPrePushHookInstaller(GitPreHookLogger logger, File root) { + this(logger, root, null); + } + + /** + * Constructor to initialize the GitPrePushHookInstaller with a logger,repository root path and optional hooks root. + * + * @param logger The logger for recording messages. + * @param root The root directory of the Git repository. + * @param hooksRoot Optional hooks directory set by core.hooksPath. + */ + protected GitPrePushHookInstaller(GitPreHookLogger logger, File root, @Nullable File hooksRoot) { this.logger = requireNonNull(logger, "logger can not be null"); this.root = requireNonNull(root, "root file can not be null"); + this.hooksRoot = hooksRoot; } /** @@ -123,7 +142,10 @@ private void doInstall() throws Exception { } var hookContent = ""; - final var gitHookFile = root.toPath().resolve(".git/hooks/pre-push").toFile(); + final var gitHookFile = (hooksRoot != null ? hooksRoot.toPath() : root.toPath().resolve(".git/hooks")) + .resolve("pre-push") + .toFile(); + if (!gitHookFile.exists()) { logger.info("Git pre-push hook not found, creating it"); if (!gitHookFile.getParentFile().exists() && !gitHookFile.getParentFile().mkdirs()) { diff --git a/lib/src/main/java/com/diffplug/spotless/GitPrePushHookInstallerGradle.java b/lib/src/main/java/com/diffplug/spotless/GitPrePushHookInstallerGradle.java index 3cc61e566d..a8de97be90 100644 --- a/lib/src/main/java/com/diffplug/spotless/GitPrePushHookInstallerGradle.java +++ b/lib/src/main/java/com/diffplug/spotless/GitPrePushHookInstallerGradle.java @@ -1,5 +1,5 @@ /* - * Copyright 2025 DiffPlug + * Copyright 2025-2026 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,6 +19,8 @@ import java.io.File; +import javax.annotation.Nullable; + /** * Implementation of {@link GitPrePushHookInstaller} specifically for Gradle-based projects. * This class installs a Git pre-push hook that uses Gradle's `gradlew` executable to check and apply Spotless formatting. @@ -26,7 +28,11 @@ public class GitPrePushHookInstallerGradle extends GitPrePushHookInstaller { public GitPrePushHookInstallerGradle(GitPreHookLogger logger, File root) { - super(logger, root); + this(logger, root, null); + } + + public GitPrePushHookInstallerGradle(GitPreHookLogger logger, File root, @Nullable File hooksRoot) { + super(logger, root, hooksRoot); } /** diff --git a/plugin-gradle/CHANGES.md b/plugin-gradle/CHANGES.md index a053b13358..1f8b20a9d2 100644 --- a/plugin-gradle/CHANGES.md +++ b/plugin-gradle/CHANGES.md @@ -6,6 +6,7 @@ We adhere to the [keepachangelog](https://keepachangelog.com/en/1.0.0/) format ( ### Changes - Bump default `eclipse` version from `4.40` to `4.41`. +- spotlessInstallGitPrePushHook now respects Git’s core.hooksPath when installing the pre-push hook, instead of always writing to .git/hooks. ([#3115](https://github.com/diffplug/spotless/pull/3115) - Bump default `gherkin` version `42.0.0` -> `42.0.1`. ([#3088](https://github.com/diffplug/spotless/pull/3088)) - Bump default `jackson` version `2.22.2` -> `2.22.3`. ([#3101](https://github.com/diffplug/spotless/pull/3101)) - Bump default `palantir-java-format` version `2.98.0` -> `2.99.0`. ([#3103](https://github.com/diffplug/spotless/pull/3103)) diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessInstallPrePushHookTask.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessInstallPrePushHookTask.java index 6cd3d15458..9166904fd4 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessInstallPrePushHookTask.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessInstallPrePushHookTask.java @@ -1,5 +1,5 @@ /* - * Copyright 2025 DiffPlug + * Copyright 2025-2026 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,13 +15,22 @@ */ package com.diffplug.gradle.spotless; +import java.io.ByteArrayOutputStream; import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; + +import javax.inject.Inject; import org.gradle.api.DefaultTask; import org.gradle.api.provider.Property; import org.gradle.api.tasks.Internal; import org.gradle.api.tasks.TaskAction; +import org.gradle.process.ExecOperations; import org.gradle.work.DisableCachingByDefault; +import org.jspecify.annotations.NonNull; import com.diffplug.spotless.GitPrePushHookInstaller.GitPreHookLogger; import com.diffplug.spotless.GitPrePushHookInstallerGradle; @@ -45,14 +54,18 @@ public abstract class SpotlessInstallPrePushHookTask extends DefaultTask { @Internal abstract Property getIsRootExecution(); + @Inject + protected abstract ExecOperations getExecOperations(); + /** - * Executes the task to install the Git pre-push hook. + * Installs the Spotless pre-push hook for a supported Git repository. * - *

This method creates an instance of {@link GitPrePushHookInstallerGradle}, - * providing a logger to record informational and error messages during the installation process. - * The installer then installs the hook in the root directory of the Gradle project. + *

The task runs only for the root project. It asks Git to resolve the + * effective hook path, validates the destination, and delegates the actual + * installation to {@link GitPrePushHookInstallerGradle}. Unsupported + * repositories or destinations are logged and skipped. * - * @throws Exception if an error occurs during the hook installation process. + * @throws Exception if resolving the hook path or installing the hook fails */ @TaskAction public void performAction() throws Exception { @@ -62,6 +75,98 @@ public void performAction() throws Exception { return; } + File rootDir = getRootDir().get(); + + final boolean isWorkTree; + try { + isWorkTree = isGitWorkTree(rootDir); + } catch (org.gradle.api.GradleException exception) { + getLogger().warn("Skipping Spotless pre-push hook installation - could not run Git to check repository config {}: {}", + rootDir, exception.getMessage()); + return; + } + + if (!isWorkTree || !isSupportedGitRepository(rootDir)) { + getLogger().warn("Skipping Spotless pre-push hook installation - directory {} is not a supported Git repository", rootDir); + return; + } + + File prePushHookFile = resolvePrePushHookFile(rootDir); + File prePushHookRootDir = prePushHookFile.getParentFile(); + + if (!isSupportedDestinationDir(rootDir, prePushHookRootDir, prePushHookFile)) { + getLogger().warn( + "Skipping Spotless pre-push hook installation - not supported destination dir {}.", prePushHookRootDir); + return; + } + + getLogger().debug("Found pre push hook root from config: {}", prePushHookRootDir); + + createInstaller(rootDir, prePushHookRootDir).install(); + } + + private boolean isSupportedGitRepository(File root) { + return Files.isRegularFile(root.toPath().resolve(".git/config")); + } + + /** + * Checks whether the resolved hook destination is safe for this installer. + * + *

The hooks directory must be inside the project and must either exist + * as a directory or not exist yet. The pre-push hook must either not exist + * or be a regular file; symbolic links are rejected to avoid writing + * through them. + * + * @throws IOException if a canonical path cannot be resolved + */ + private boolean isSupportedDestinationDir(File rootDir, File hooksDir, File hookFile) throws IOException { + return hooksDir.getCanonicalFile().toPath().startsWith(rootDir.getCanonicalFile().toPath()) + && (!hooksDir.exists() || hooksDir.isDirectory()) + && !Files.isSymbolicLink(hookFile.toPath()) + && (!hookFile.exists() || hookFile.isFile()); + } + + private boolean isGitWorkTree(File root) { + var outputStream = new ByteArrayOutputStream(); + var errorStream = new ByteArrayOutputStream(); + + var result = getExecOperations().exec(spec -> { + spec.setWorkingDir(root); + spec.commandLine("git", "rev-parse", "--is-inside-work-tree"); + spec.setStandardOutput(outputStream); + spec.setErrorOutput(errorStream); + spec.setIgnoreExitValue(true); + }); + + return result.getExitValue() == 0 + && outputStream.toString(StandardCharsets.UTF_8).trim().equals("true"); + } + + private File resolvePrePushHookFile(File root) { + var outputStream = new ByteArrayOutputStream(); + + getExecOperations().exec(spec -> { + spec.setWorkingDir(root); + spec.commandLine("git", "rev-parse", "--git-path", "hooks/pre-push"); + spec.setStandardOutput(outputStream); + }); + + String pathOutput = outputStream.toString(StandardCharsets.UTF_8); + var path = Path.of(normalizePath(pathOutput)); + return (path.isAbsolute() ? path : root.toPath().resolve(path)).normalize().toFile(); + } + + private static @NonNull String normalizePath(String pathOutput) { + if (pathOutput.endsWith("\n")) { + pathOutput = pathOutput.substring(0, pathOutput.length() - 1); + if (pathOutput.endsWith("\r")) { + pathOutput = pathOutput.substring(0, pathOutput.length() - 1); + } + } + return pathOutput; + } + + private @NonNull GitPrePushHookInstallerGradle createInstaller(File rootDir, File prePushHookRootDir) { final var logger = new GitPreHookLogger() { @Override public void info(String format, Object... arguments) { @@ -79,7 +184,6 @@ public void error(String format, Object... arguments) { } }; - final var installer = new GitPrePushHookInstallerGradle(logger, getRootDir().get()); - installer.install(); + return new GitPrePushHookInstallerGradle(logger, rootDir, prePushHookRootDir); } } diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/SpotlessInstallPrePushHookTaskTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/SpotlessInstallPrePushHookTaskTest.java index f739ab0c63..2ad638e2d1 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/SpotlessInstallPrePushHookTaskTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/SpotlessInstallPrePushHookTaskTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2025 DiffPlug + * Copyright 2025-2026 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,6 +17,9 @@ import static org.assertj.core.api.Assertions.assertThat; +import java.io.IOException; +import java.nio.file.Files; + import org.junit.jupiter.api.Test; class SpotlessInstallPrePushHookTaskTest extends GradleIntegrationHarness { @@ -24,20 +27,12 @@ class SpotlessInstallPrePushHookTaskTest extends GradleIntegrationHarness { @Test public void should_create_pre_hook_file_when_hook_file_does_not_exists() throws Exception { // given - setFile(".git/config").toContent(""); + gitCommand("init", "--quiet"); newFile(".git/hooks").mkdirs(); - setFile("build.gradle").toLines( - "plugins {", - " id 'java'", - " id 'com.diffplug.spotless'", - "}", - "repositories { mavenCentral() }"); + setGradleFile(); // when - var output = gradleRunner() - .withArguments("spotlessInstallGitPrePushHook", "--system-prop=org.gradle.configuration-cache=true") - .build() - .getOutput(); + var output = getExecutionOutput(); // then assertThat(output).contains("Installing git pre-push hook"); @@ -54,20 +49,12 @@ public void should_create_pre_hook_file_when_hook_file_does_not_exists() throws @Test public void should_append_to_existing_pre_hook_file_when_hook_file_exists() throws Exception { // given - setFile(".git/config").toContent(""); - setFile("build.gradle").toLines( - "plugins {", - " id 'java'", - " id 'com.diffplug.spotless'", - "}", - "repositories { mavenCentral() }"); + gitCommand("init", "--quiet"); setFile(".git/hooks/pre-push").toResource("git_pre_hook/pre-push.existing"); + setGradleFile(); // when - final var output = gradleRunner() - .withArguments("spotlessInstallGitPrePushHook", "--system-prop=org.gradle.configuration-cache=true") - .build() - .getOutput(); + final var output = getExecutionOutput(); // then assertThat(output).contains("Installing git pre-push hook"); @@ -79,4 +66,122 @@ public void should_append_to_existing_pre_hook_file_when_hook_file_exists() thro .replace("${applyCommand}", "spotlessApply"); assertFile(".git/hooks/pre-push").hasContent(content); } + + @Test + public void should_use_hooksPath_if_set_in_config() throws Exception { + // given + gitCommand("init", "--quiet"); + gitCommand("config", "--local", "core.hooksPath", ".githooks"); + setGradleFile(); + + // when + final var output = getExecutionOutput(); + + // then + assertThat(output).contains("Installing git pre-push hook"); + assertThat(output).contains("Git pre-push hook installed successfully to the file " + newFile(".githooks/pre-push")); + + final var content = getTestResource("git_pre_hook/pre-push.created-tpl") + .replace("${executor}", "gradle") + .replace("${checkCommand}", "spotlessCheck") + .replace("${applyCommand}", "spotlessApply"); + assertFile(".githooks/pre-push").hasContent(content); + } + + @Test + public void should_skip_when_not_in_git_worktree() throws Exception { + setGradleFile(); + + // when + final var output = getExecutionOutput(); + + // then + assertThat(output).containsPattern("Skipping Spotless pre-push hook installation - directory .* is not a supported Git repository"); + } + + @Test + public void should_skip_when_prehook_config_not_in_parent_project() throws Exception { + gitCommand("init", "--quiet"); + var outsideHooks = rootFolder().toPath().resolveSibling(rootFolder().getName() + "-outside-hooks"); + gitCommand("config", "--local", "core.hooksPath", outsideHooks.toString()); + setGradleFile(); + + // when + final var output = getExecutionOutput(); + + // then + assertThat(outsideHooks).doesNotExist(); + assertThat(output).containsPattern("Skipping Spotless pre-push hook installation - not supported destination dir"); + } + + @Test + public void should_skip_when_prehook_file_a_directory() throws Exception { + gitCommand("init", "--quiet"); + gitCommand("config", "--local", "core.hooksPath", ".githooks"); + Files.createDirectories(newFile(".githooks/pre-push").toPath()); + setGradleFile(); + + // when + final var output = getExecutionOutput(); + + // then + assertThat(output).containsPattern("Skipping Spotless pre-push hook installation - not supported destination dir"); + } + + @Test + public void should_skip_when_prehook_config_a_symlink() throws Exception { + gitCommand("init", "--quiet"); + gitCommand("config", "--local", "core.hooksPath", ".githooks"); + + var target = setFile("target-hook").toContent("original content"); + Files.createDirectories(newFile(".githooks").toPath()); + + var hook = newFile(".githooks/pre-push").toPath(); + Files.createSymbolicLink(hook, target.toPath()); + + setGradleFile(); + + // when + final var output = getExecutionOutput(); + + // then + assertThat(Files.isSymbolicLink(hook)).isTrue(); + assertThat(Files.readString(target.toPath())).isEqualTo("original content"); + assertThat(output).containsPattern("Skipping Spotless pre-push hook installation - not supported destination dir"); + } + + private String getExecutionOutput() throws IOException { + return gradleRunner() + .withArguments("spotlessInstallGitPrePushHook", "--system-prop=org.gradle.configuration-cache=true") + .build() + .getOutput(); + } + + private void setGradleFile() { + setFile("build.gradle").toLines( + "plugins {", + " id 'java'", + " id 'com.diffplug.spotless'", + "}", + "repositories { mavenCentral() }"); + } + + private void gitCommand(String... args) throws Exception { + var command = new java.util.ArrayList(); + command.add("git"); + command.addAll(java.util.List.of(args)); + + var process = new ProcessBuilder(command) + .directory(rootFolder()) + .redirectErrorStream(true) + .start(); + + String output; + try (var stream = process.getInputStream()) { + output = new String(stream.readAllBytes(), java.nio.charset.StandardCharsets.UTF_8); + } + assertThat(process.waitFor()) + .as("git %s: %s", String.join(" ", args), output) + .isZero(); + } }