Skip to content

Commit

Permalink
feat: use "git config core.hooksPath" instead of symlinking
Browse files Browse the repository at this point in the history
BREAKING CHANGE: this note is more to signify that this change can
have unexpected consequences on repositories that used any previous
version where GHooks used to use symbolic links. While I can't
think of anything that can go wrong with simply re-setting what the
local config for hooksPath is, this note is meant to be a trigger
for a major version change and to give a potential migration path:

- Remove the symlinked directory (and potentially re-create an
  empty directory: `rm -rf .git/hooks && mkdir .git/hooks`;
- Run GHooks' install task: `./gradlew installGitHooks`;
  • Loading branch information
gtramontina committed Apr 17, 2023
1 parent 128a719 commit 396f0c0
Showing 1 changed file with 2 additions and 23 deletions.
25 changes: 2 additions & 23 deletions src/main/kotlin/com/gtramontina/ghooks/GHooks.kt
Original file line number Diff line number Diff line change
@@ -1,23 +1,16 @@
package com.gtramontina.ghooks

import org.apache.commons.io.FileUtils.forceDelete
import org.gradle.api.Plugin
import org.gradle.api.Project
import java.nio.file.Files.createSymbolicLink
import java.nio.file.Files.exists
import java.nio.file.Files.isDirectory
import java.nio.file.Files.isSymbolicLink
import java.nio.file.Files.readSymbolicLink
import java.nio.file.Path

class GHooks : Plugin<Project> {
companion object {
private const val GIT_HOOKS_TARGET = ".githooks"
private const val GIT_HOOKS_SOURCE = ".git/hooks"
private const val DESCRIPTION = "Installs the configured Git hooks."
private const val GROUP = "git hooks"
private const val TASK_NAME = "installGitHooks"
private const val GIT_CDUP = "git rev-parse --show-cdup"
private const val GIT_CONFIG_HOOKS = "git config core.hooksPath $GIT_HOOKS_TARGET"
private const val GIT_HOOKS_TARGET_WARNING = """
Something went wrong while installing your Git hooks.
Expand Down Expand Up @@ -46,22 +39,8 @@ class GHooks : Plugin<Project> {
task.logger.warn(GIT_HOOKS_TARGET_WARNING.trimIndent()).also { return@task }
}

GIT_CDUP.exec(root)
.thenApply { root.resolve(it.trim()) }
.thenApply { it.resolve(GIT_HOOKS_SOURCE).toPath() }
.thenAccept { it.symLinkTo(it.parent.relativize(target)) }
GIT_CONFIG_HOOKS.exec(root)
.exceptionally { task.logger.warn(GIT_WARNING.trimIndent(), it).run { throw it } }
}
}

private fun Path.symLinkTo(target: Path) {
if (isSymLinkTo(target)) return
deleteIfExists().also { createSymbolicLink(this, target) }
}

private fun Path.isSymLinkTo(target: Path) = exists(this) &&
isSymbolicLink(this) &&
readSymbolicLink(this) == target

private fun Path.deleteIfExists() = forceDelete(toFile())
}

0 comments on commit 396f0c0

Please # to comment.