it could be interesting to create another git pre-commit hook with auto-correct.
What do you think?
Hi Antonio.
I'm not sure this is possible.
ktlint has --install-git-pre-commit-hook but it runs linting only due to the following:
touch file
git add file
echo update >> file
git commit -m "commit message" file
# git commits file without "update" line (because last change wasn't staged)
# imagine we would somehow `git add` files changed by ktlint -F
# if we do - we risk including changes that were not meant to be included
# (not staged before ktlint -F was run)
If we disregard staging area things might get feasible but I don't feel that would be wise.
(I might be wrong)
If anybody knows a way - please let me know, otherwise this ticket is closed.
I have created another pre-commit based on the existing one https://gist.github.com/tonilopezmr/88f651827a924993a6692b3bde2ca755
My idea is to create another Ktlint option to create an auto-correct pre-commit.
I set this up for our team. I was also worried about changes that weren't staged, or files that had partially staged changes. I think I came up with a solution which should work. It looks at only staged files, and ignores files that are partially staged.
#!/usr/bin/env bash
# This gets the list of staged files that will be included in the commit (removed files are ignored).
# If a file is only partially staged (some changes in it are unstaged), then the file is not included
# in checks. That is because the checks re-add the file to ensure autocorrected fixes are included
# in the commit, and we don't want to add the whole file since that would mess with the intention
# of partial staging.
stagedFilename=.tmpStagedFiles
unstagedFilename=.tmpUnstagedFiles
git diff --cached --name-only --diff-filter=ACM | grep '\.kt[s"]\?$' | sort > $stagedFilename
git diff --name-only --diff-filter=ACM | grep '\.kt[s"]\?$' | sort > $unstagedFilename
# This returns a list of lines that are only in the staged list
filesToCheck=$(comm -23 $stagedFilename $unstagedFilename | tr '\n' ' ')
# Delete the files, which were created for temporary processing
rm -f $stagedFilename
rm -f $unstagedFilename
# If the list of files is not empty then run checks on them
if [ ! -z "$filesToCheck" ]
then
ktlint --format $filesToCheck
if [ $? -ne 0 ]; then exit 1; fi
# If we haven't exited because of an error it means we were able to
# fix issues with autocorrect. However, we need to add the changes in
# order for them to be included in the pending commit.
git add $filesToCheck
fi
Most helpful comment
I set this up for our team. I was also worried about changes that weren't staged, or files that had partially staged changes. I think I came up with a solution which should work. It looks at only staged files, and ignores files that are partially staged.