gradle-pre-commit-git-hooks icon indicating copy to clipboard operation
gradle-pre-commit-git-hooks copied to clipboard

Format files in a pre-commit and add them to the commit.

Open ezamelczyk opened this issue 1 year ago • 1 comments

What would you like to be able to do?

I am using ktfmt to keep consistent formatting in my kotlin project. I'd like to be able to create a hook that will automatically run the ktfmtFormat task and commit the formatted files. As of right now calling the ktfmtFormat properly formats the files but doing it in a pre-commit hook does not change anything. Basically I'm asking is it possible to have this configuration work:

gitHooks {
    preCommit {
        tasks("ktfmtFormat")
    }
    createHooks(true)
}

If you have any ideas on how this should be implemented, please tell us here.

I'm not sure how

Is this a feature you are interested in implementing yourself?

Maybe

ezamelczyk avatar Dec 18 '24 12:12 ezamelczyk

I think this is more a git question than a question related to the plugin. According to the docs, the pre-commit hook is the first that is executed when a commit is requested, but it can't alter the content of the stage.

What you probably want to do is something like:

    preCommit {
        from { // Creates a fresh script with a bash shebang line
            """
            ./gradlew ktfmtFormat
            modified_files=$(git diff --name-only)
            if [ -n "$modified_files" ]; then
              git add $modified_files
            fi
            """
        }
    }
    createHooks(true)
}

I'm not sure it works, and I am pretty sure this would ruin the game with commit --patch. A safer approach could be:

    preCommit {
        from { // Creates a fresh script with a bash shebang line
            """
            ./gradlew ktfmtFormat
            modified_files=$(git diff --name-only)
            if [ -n "$modified_files" ]; then
              echo "Some files have been edited by ktfmtFormat. Please retry your commit now. Modified: $modified_files
              exit 1
            fi
            """
        }
    }
    createHooks(true)
}

Please, try and let me know if this works

DanySK avatar Jan 23 '25 22:01 DanySK