Skip to content

Commit ecbfb0e

Browse files
committed
Fix pre-commit hook path handling for projects in subdirectories
When the Gradle project root differs from the Git repository root (e.g., Gradle is in a subdirectory like 'project/submodule/'), the pre-commit hooks generated by ktlint-gradle fail to properly format files because of path mismatches. This change fixes the issue by: - Using `git diff --relative=$gradleRootDirPrefix` to output paths relative to the Gradle project root - Adding proper file path prefix handling in the git add command when checking if files exist and staging them This ensures that when git outputs paths like "src/main/Foo.kt" (relative to project/submodule/), the hook correctly references them as "project/submodule/src/main/Foo.kt" when checking file existence and staging. Fixes #374
1 parent e79fccb commit ecbfb0e

File tree

1 file changed

+7
-5
lines changed
  • plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint

1 file changed

+7
-5
lines changed

plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/GitHook.kt

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -44,16 +44,18 @@ private fun generateGitCommand(
4444
): String = if (gradleRootDirPrefix.isEmpty()) {
4545
"git --no-pager diff --name-status --no-color --cached"
4646
} else {
47-
"git --no-pager diff --name-status --no-color --cached -- $gradleRootDirPrefix/"
47+
"git --no-pager diff --name-status --no-color --cached --relative=$gradleRootDirPrefix -- $gradleRootDirPrefix/"
4848
}
4949

5050
private fun postCheck(
51-
shouldUpdateCommit: Boolean
51+
shouldUpdateCommit: Boolean,
52+
gradleRootDirPrefix: String
5253
): String = if (shouldUpdateCommit) {
54+
val filePrefix = if (gradleRootDirPrefix.isNotEmpty()) "$gradleRootDirPrefix/" else ""
5355
"""
5456
echo "${'$'}CHANGED_FILES" | while read -r file; do
55-
if [ -f ${'$'}file ]; then
56-
git add ${'$'}file
57+
if [ -f $filePrefix${'$'}file ]; then
58+
git add $filePrefix${'$'}file
5759
fi
5860
done
5961
"""
@@ -91,7 +93,7 @@ internal fun generateGitHook(
9193
gradle_command_exit_code=${'$'}?
9294
9395
echo "Completed ktlint run."
94-
${postCheck(shouldUpdateCommit)}
96+
${postCheck(shouldUpdateCommit, gradleRootDirPrefix)}
9597
9698
if [ -s ${'$'}diff ]; then
9799
git apply --ignore-whitespace ${'$'}diff

0 commit comments

Comments
 (0)