fun installHook()

in bunch-cli/src/main/kotlin/org/jetbrains/bunches/hooks/hooks.kt [127:189]


fun installHook(type: HookType, dotGitPath: File) {
    val hooksDirectory = File(dotGitPath, "hooks")
    val hookPath = File(hooksDirectory, type.hookName).absolutePath

    val oldHookNewName: String
    val hooksPath = File(dotGitPath, "hooks")

    if (File(hookPath).exists()) {
        if (checkHookMarker(File(hookPath).readText(), type)) {
            println("Bunch file ${type.hookName} hook found, it will be reinstalled")
            val oldHookName = File(hookCodeParams(File(hookPath).readText()).oldHookPath).name
            oldHookNewName = if (oldHookName == ":") "" else oldHookName
        } else {
            println(
                """
                Other ${type.hookName} hook was found
                Do you want the new name to be generated (1) or rename it by yourself? (2)
                Type 1 or 2
                To cancel installation press ctrl+c
                """.trimIndent()
            )

            when (readLine()) {
                "2" -> {
                    oldHookNewName = readLine() ?: exitWithLocalError("New name for ${type.hookName} was not provided")
                }
                else -> {
                    val tempFile = createTempFile(type.hookName, "", File("$dotGitPath/hooks"))
                    oldHookNewName = tempFile.relativeTo(hooksPath).path
                    tempFile.delete()
                }
            }

            if (File(hookPath).renameTo(File(hooksPath, oldHookNewName)))
                println("Old ${type.hookName} hook was renamed to $oldHookNewName and will still be called")
            else
                exitWithLocalError("Couldn't rename existing ${type.hookName} hook")
        }
    } else {
        oldHookNewName = ""
    }

    val hookFile = File(hookPath).absoluteFile
    if (!hookFile.exists() && !hookFile.createNewFile()) {
        exitWithLocalError("Failed to create ${type.hookName} hook file")
    }
    if (!hookFile.setExecutable(true)) {
        exitWithLocalError("Failed to make ${type.hookName} hook executable")
    }

    val bunchExecutableFile = findExecutableFileFromZip()
        ?: findExecutableFileFromProject()
        ?: exitWithError("Can't find executable file")

    val oldHookPath = if (oldHookNewName != "")
        "'${File(hooksPath, oldHookNewName).absolutePath}'"
    else
        ":"

    hookFile.writeText(type.getHookCodeTemplate(bunchExecutableFile, oldHookPath, dotGitPath.parentFile))

    println("Bunch ${type.hookName} hook has been successfully installed")
}