This is pre-commit hook that runs scalafmt
on changed .scala and .sbt files each time you commit them.
You need to have pre-commit, Nailgun (for installation guidelines please see the respective sites) and Bash installed first.
Next, you should place the hook inside the .pre-commit-hooks.yaml. Minimal version can looks like this:
- repo: git@github.com:coyainsurance/pre-commit-scalafmt.git
sha: master # you probably do not want to use latest version, but rather pin it to specific commit and update manually
hooks:
- id: scalafmt
args: [ -p9090, -t ] # run in server mode on port 9090 and pass `--test` to scalafmt; alternatively you can place here other supported cmdline arguments
After that, you should run
pre-commit install -f --install-hooks
or equivalent to install and/or update your hooks file.
Then you should be ready to enjoy automatic checks if your Scala files are formatted accordingly.
Script has several options than can be passed using args array for the pre-commit hook configuration.
-
-c $scalafmtConfigsets the scalafmt config (default=.scalafmt.conf). -
-d $bootstrapDirectorysets the bootstrap directory (default=$HOME/.scalafmt).It is used to place
coursierandscalafmtbinaries for the first time this hook is run. -
-p $port- bindsnailgunto the specified port. Implies the-soption. -
-s- startsscalafmtin background usingnailgun.That should significantly speedup checking your files, as
scalafmtis then already running in background and JVM processes can take quite significant time to initialize. The tradeoff is that you may sometimes need to commit again, as hook may fail due to connection problems (apparently happens with long-enough runningnailgunservice).You should also make sure to have recent enough
nailgunversion (0.9.1should do). In case of older version you may simply get no response back.Default port is specified by
$NAILGUN_PORTenvironment variable if it exists. If not,2113is taken. Alternatively one can use-poption to override the port. -
-Sallows you to set the Scala version forscalafmt, e.g.-S2.12or-S2.13(the default). -
-t- passes--testtoscalafmt, that implies no mis-formatted file will be changed instead of returning1exit code on any. -
-v $version- forces to use specific (default=2.6.3)scalafmtversion. -
-o $organisation- forces to use specificscalafmtorganisation (default=org.scalameta). (The organisation before the release of 2.0 wascom.geirsson.)
It was successfully tested both on Linux distributions and MacOS.