Setting up a code formatter in an iOS project
People come and go, but projects stay. Having a uniform and idiomatic codebase is nicer, eases the onboarding of new developers and lets them to entirely focus on what matters the most while writing code or reviewing others.
There are really good Swift code formatters out there, like SwiftFormat and swift-format. We are using SwiftFormat at The Agile Monkeys. This is how we configure it for an iOS project as a pre-commit hook.
Wait! But why adding it as a pre-commit hook?
Because we don’t want this to run entirely on every local build (if the formatter was added as a build phase), but once we are going to commit new code. Besides, we want the formatter to interfere with our editor undo history the less as possible. The downside of the pre-commit approach is that every developer on the project would need to add the pre-commit hook file manually (once).
The ideal thing is to have this integrated into the CI process with Danger and let it commit the formatted changes for you in each Pull Request. This is how you can do it, for example, with Bitrise + Danger: https://blog.bitrise.io/danger-danger-uh-that-is-using-danger-with-bitrise
But if you don’t want to pay for any extra seats in your Github account or you don’t want anything else in the pipeline to be changing files on behalf of the developers, the pre-commit hook is nice too.
Let’s see how to do it!
First, you need to install the command-line tool:
brew install swiftformat
brew upgrade swiftformat
Next, add the pre-commit hook:
- Edit or create a .git/hooks/pre-commit file in your project folder. The .git folder is hidden but should already exist if you are using Git in your project. Open it with the terminal or the Finder’s Go > Go to Folder… menu.
- Add the following code in the pre-commit file:
git diff --diff-filter=d --staged --name-only | grep -e '\(.*\).swift$' | while read line; do swiftformat "${line}"; git add "$line"; donechmod +x .git/hooks/pre-commit
The pre-commit hook will now run whenever you run git commit. Running git commit — no-verify will skip it.
Note: GUI git clients do not know your environment/shell. I’m using Tower as my GUI git client so I needed to add this line at the top of the pre-commit file:
PATH="$PATH:/usr/local/bin"
To get default set of formatting rules (which are pretty good and idiomatic) you don’t need to do anything else. In case you want to adapt it to your needs, you can create and add rules to a .swiftformat file in your project path. You can find the rules reference in: https://github.com/nicklockwood/SwiftFormat/blob/master/Rules.md
Finally, perform the first full project formatting:
swiftformat .
Enjoy the homogeneity!
Originally published at https://dev.to on March 10, 2020.