I'm a huge fan of formatters and linters as they enforce style and conventions, making it hard if not impossible to tell who authored a file, function, etc.
For Swift projects I've been using the great SwiftFormat and Swiftlint (both of which can be installed via Homebrew), with my favorite linting and formatting rules.
When working on an Xcode project, I tend to add a Run Script to Xcode's Build Phases which runs Swiftlint and SwiftFormat to lint and format every time you build. While this does slow down your build by a second or two, its not been something I've noticed in my experience.
Recently I've been authoring more and more Swift packages, which do not have a build phase equivalent. I haven't had any luck with the Swift Package Manager plugin system, so I've resorted to using a Git hook, specifically pre-commit
.
This is a sample pre-commit that both formats and lints a package. Any errors that occur are redirected to stderr
, so if you're using a GUI app for Git (I couldn't live without Tower) any errors are shown in a dialog.
To add the precommit hook:
- save the script to a file called
precommit
- give the script execute permissions (e.g.
chmod u+x precommit
) - either manually move it into the
.git/hooks
folder, - or make a symlink (e.g.
ln -s pre-commit .git/hooks/pre-commit
)
The next time you commit some code, the script will run and potentially modify some of your files. At that point I tend to amend the original commit with those changes.