PUBLIC OBJECT

I Want a Fast Whitespace Fixer

A couple of us are grumpy that putting robots in charge of code formatting is too slow & too clumsy. Jake Wharton reminded us that ranting isn’t as useful as participating, and challenged us to work on fixes.

Lemme start with my ideal:

  1. IntelliJ, Android Studio, and a command-line thing all agree on the formatting rules.
  2. I can use .editorconfig to customize some rules that I’m persnickety about. The IDE and command-line both honor these customizations. The default style is thoughtful.
  3. I don’t need to install any IDE plugins.
  4. The command-line thing is absurdly fast. Fast enough that I can run it in a pre-commit hook and not feel like I’m doing a build.
  5. The command-line thing can validate the style: spotlessCheck.
  6. The command-line thing can fix the style automatically: spotlessApply.
  7. The command-line thing can run on a whole repo, or just a few commits: ratchetFrom.
  8. I can mash the Reformat Code shortcut in the IDE (⌘⌥L) and it’ll fix my code.

It turns out that almost everything I want is already here. IntelliJ and Android Studio are excellent and support .editorconfig. Ktlint has good enough defaults and supports .editorconfig. Spotless integrates Gradle with ktlint and Git.

But there’s a bug (KTIJ-16847) in IntelliJ where it doesn’t sort aliased imports properly. This one’s super annoying because it means I’ll probably need spotlessApply before each commit. Please vote up this issue!

And spotlessApply isn’t absurdly fast. It runs inside Gradle which needs to do a lot of project set up before it can launch ktlint to format my code. Here’s some unreasonable optimizations that qualify as absurdly fast:

  • Interrogate the host hardware and use careful parallelism to saturate the CPU, file reading, and file writing.
  • Use Kotlin/Native or a GraalVM native image to eliminate JIT startup latency.
  • Use a sqlite DB to remember which files have already been formatted.
  • Do something fancy with SIMD.

Fast is a feature. If my formatter runs in half a second, I’ll run it all the time.