Toggle formatting inline with spotless:off and spotless:on by nedtwigg · Pull Request #691 · diffplug/spotless
Summary
Sometimes there is a chunk of code which you have carefully handcrafted, and you would like to exclude just this one little part from getting clobbered by the autoformat. Some formatters have a way to do this, some don't, but who cares. It would be nice if you could scatter spotless:off and spotless:on inline in your code, and have it just work, no matter which formatter you're using. This PR makes that possible.
Changing the defaults
The one hiccup is that, because it works for all languages / formatters, it isn't context-aware. Meaning that it doesn't care if spotless:off is in a comment, a string constant, or wherever. It just does a dumb search for pairs of spotless:off / spotless:on, and saves whatever is between them from being formatted. You can change the terms to be whatever you want, e.g. fmt:off, fmt:on, or whatever, but using something longer and uncommon like "spotless" is safer than something short like "fmt". You can also set a full regex if you want to try to make it comment-specific, but that's probably harder than it seems at first.
How it is implemented
It implements this under the hood with PipeStepPair, which has an In step and an Out step. The In step is the very first step which gets applied, Out is the last step, and all the other formatting steps go in between them. The In step finds matching off/on pairs, and stores the text between them. The intermediate steps like google-java-format or whatever do their work, and at the end the Out step finds the off/on pairs again, which may have moved. Then it replaces those pairs with whatever was stored by the In step.
Limitations
The intermediate steps can't remove an in/out pair. If they do, there's no way for spotless to put them back together. For example, if you have a step that converts your whole file to uppercase, that will turn spotless:off to SPOTLESS:OFF, which breaks the pair. This isn't a problem for the vast majority of steps. One notable exception, though, is the license header step. Because it replaces the whole header, any off/on pairs within the header will get clobbered, which will cause spotless to fail with an error.