Skip to content

Commit

Permalink
git hook: format renamed files, only format files that end with '.kt[s]'
Browse files Browse the repository at this point in the history
  • Loading branch information
KotlinIsland committed Apr 21, 2021
1 parent 44f14db commit a5a3576
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/).
- Updated default KtLint version to `0.41.0`
### Fixed
- Plugin fails to apply on non-Kotlin projects ([#443](https://github.com/JLLeitschuh/ktlint-gradle/issues/443))
- Git hook: format files that have been renamed
### Removed
- ?

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,8 @@ private fun postCheck(
""
}

internal const val NF = "\$NF"

@Language("Sh")
internal fun generateGitHook(
taskName: String,
Expand All @@ -65,7 +67,7 @@ internal fun generateGitHook(
) =
"""
CHANGED_FILES="${'$'}(${generateGitCommand(gradleRootDirPrefix)} | awk '$1 != "D" && $2 ~ /\.kts|\.kt/ { print $2}')"
CHANGED_FILES="${'$'}(${generateGitCommand(gradleRootDirPrefix)} | awk '$1 != "D" && $NF ~ /\.kts?$/ { print $NF }')"
if [ -z "${'$'}CHANGED_FILES" ]; then
echo "No Kotlin staged files."
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,28 @@ class GitHookTasksTest : AbstractPluginTest() {
}
}

@Test
internal fun `Format hook should format files when they are renamed`() {
projectRoot.setupGradleProject()
val gitDir = projectRoot.initGit()

build(":$INSTALL_GIT_HOOK_FORMAT_TASK").run {
assertThat(task(":$INSTALL_GIT_HOOK_FORMAT_TASK")?.outcome).isEqualTo(TaskOutcome.SUCCESS)
assertThat(gitDir.preCommitGitHook().readText()).matches(""".*awk '.* \$NF ~ \/.*\/ \{ print \$NF \}'.*""")
}
}

@Test
internal fun `Format hook should only format files that end with kt or kts`() {
projectRoot.setupGradleProject()
val gitDir = projectRoot.initGit()

build(":$INSTALL_GIT_HOOK_FORMAT_TASK").run {
assertThat(task(":$INSTALL_GIT_HOOK_FORMAT_TASK")?.outcome).isEqualTo(TaskOutcome.SUCCESS)
assertThat(gitDir.preCommitGitHook().readText()).contains("""/\.kts?$/""")
}
}

private fun File.initGit(): File {
val repo = RepositoryBuilder().setWorkTree(this).setMustExist(false).build()
repo.create()
Expand Down

0 comments on commit a5a3576

Please sign in to comment.