Skip to content

Instantly share code, notes, and snippets.

@androiddevnotes
Created September 16, 2024 21:17
Show Gist options
  • Save androiddevnotes/d380f68ef062d8c361d6de614c24c902 to your computer and use it in GitHub Desktop.
Save androiddevnotes/d380f68ef062d8c361d6de614c24c902 to your computer and use it in GitHub Desktop.
Automatically format Kotlin source files using ktlint before committing changes in a Git repository.

to use it:

  1. install ktlint first: brew install ktlint - if not on mac, use different installation: https://github.com/pinterest/ktlint

  2. modify your pre-commit file in .git folder

  3. create .editorconfig file in root of your project

example config of .editorconfig:

[*.{kt,kts}]
indent_size = 2
indent_style = space

now commit ... ktlint will automatically format Kotlin source files using ktlint before committing changes in a Git repository.

#!/bin/sh
# Format Kotlin files with ktlint before committing
git diff --name-only -z --cached -- '*.kt' '*.kts' | \
xargs -0 sh -c 'ktlint -F "$@" || exit $?' ktlint
# If ktlint -F fails (returns non-zero), the commit will be aborted
# Re-add the files to stage the changes made by ktlint
git diff --name-only -z --cached -- '*.kt' '*.kts' | \
xargs -0 git add
# If you want to see what changes ktlint made before committing:
# git diff --cached
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment