tasks.register("ensureChecksPreCommitHook") { group = "verification" description = "Ensures that the Git pre-commit hook for ktlint is properly set up" doLast { val gitHooksDir = rootProject.file(".git/hooks") val preCommitHookFile = gitHooksDir.resolve("pre-commit") val requiredHookContent = """ #!/bin/sh # https://github.com/pinterest/ktlint pre-commit hook ktlint """.trimIndent() if (!gitHooksDir.exists()) { logger.warn("Git hooks directory not found. Is this a Git repository?") return@doLast } if (!preCommitHookFile.exists()) { logger.lifecycle("Creating ktlint pre-commit hook") preCommitHookFile.writeText(requiredHookContent) preCommitHookFile.setExecutable(true) } else { val currentContent = preCommitHookFile.readText() if (!currentContent.contains(requiredHookContent)) { logger.lifecycle("Updating pre-commit hook with ktlint check") preCommitHookFile.writeText(requiredHookContent) preCommitHookFile.setExecutable(true) } else { logger.lifecycle("ktlint pre-commit hook is already properly configured") } } } } gradle.projectsEvaluated { tasks.matching { it.name != "ensureChecksPreCommitHook" }.configureEach { dependsOn("ensureChecksPreCommitHook") } }