Skip to content

Commit cde76f3

Browse files
authoredApr 22, 2021
Merge pull request #470 from KotlinIsland/master
git hook: don't commit whole file
2 parents 44f14db + 7ca878f commit cde76f3

File tree

3 files changed

+31
-1
lines changed

3 files changed

+31
-1
lines changed
 

‎CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/).
1313
- Updated default KtLint version to `0.41.0`
1414
### Fixed
1515
- Plugin fails to apply on non-Kotlin projects ([#443](https://github.com/JLLeitschuh/ktlint-gradle/issues/443))
16+
- Pre-commit hook adds entire file to commit when only part of the file was indexed ([#470](https://github.com/JLLeitschuh/ktlint-gradle/pull/470))
1617
### Removed
1718
- ?
1819

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

+6-1
Original file line numberDiff line numberDiff line change
@@ -74,11 +74,16 @@ internal fun generateGitHook(
7474
7575
echo "Running ktlint over these files:"
7676
echo "${'$'}CHANGED_FILES"
77-
77+
78+
git stash push --keep-index
79+
7880
${generateGradleCommand(taskName, gradleRootDirPrefix)}
7981
8082
echo "Completed ktlint run."
8183
${postCheck(shouldUpdateCommit)}
84+
85+
git stash pop
86+
8287
echo "Completed ktlint hook."
8388
8489
""".trimIndent()

‎plugin/src/test/kotlin/org/jlleitschuh/gradle/ktlint/GitHookTasksTest.kt

+24
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,30 @@ class GitHookTasksTest : AbstractPluginTest() {
138138
}
139139
}
140140

141+
@Test
142+
internal fun `Format hook should not add non-indexed code to the commit`() {
143+
// TODO: This test doesn't run git or verify that only indexed code is committed,
144+
// only that the hook contains the correct commands.
145+
// Ideally an end to end test case would do something like:
146+
//
147+
// echo "val a = 1" > test.kt
148+
// git add test.kt
149+
// echo "val b = 2" >> test.kt
150+
// git commit -m test
151+
// assert that commit equals "val a = 1"
152+
// assert that test.kt equals "val a = 1\nval b = 2"
153+
154+
projectRoot.setupGradleProject()
155+
val gitDir = projectRoot.initGit()
156+
157+
build(":$INSTALL_GIT_HOOK_FORMAT_TASK").run {
158+
assertThat(task(":$INSTALL_GIT_HOOK_FORMAT_TASK")?.outcome).isEqualTo(TaskOutcome.SUCCESS)
159+
val hookText = gitDir.preCommitGitHook().readText()
160+
assertThat(hookText).contains("git stash push")
161+
assertThat(hookText).contains("git stash pop")
162+
}
163+
}
164+
141165
private fun File.initGit(): File {
142166
val repo = RepositoryBuilder().setWorkTree(this).setMustExist(false).build()
143167
repo.create()

0 commit comments

Comments
 (0)