Spotless:面向 Gradle、Maven 与 SBT 的通用多语言代码格式化插件(Keep your code spotless)

原创2026-10-11 21:03:542,220 阅读
文章标签:开发工具代码质量格式化

Spotless:面向 Gradle、Maven 与 SBT 的通用多语言代码格式化插件(Keep your code spotless)

Spotless 是一个"通用格式化插件":它把格式化能力从"特定语言 × 特定构建工具"的绑定中解放出来,用同一套机制覆盖 antlr、c、c#、c++、css、flow、graphql、groovy、html、java、javascript、json、jsx、kotlin、less、markdown、objective-c、protobuf、python、scala、scss、shell、sql、typeScript、vue、yaml 以及任意自定义格式,并同时支持 gradle、maven、sbt 三大主流构建系统。读完本文,你将掌握 Spotless 的 Quickstart 配置、spotlessCheck / spotlessApply 工作流、Function<String, String> 的核心抽象,以及幂等性(PaddedCell)、ratchet、编码换行等生产级特性,并能结合仓库源码理解其内部实现。

一、Spotless 是什么:一张"语言 × 构建系统"的格式化矩阵

Spotless 的项目定位非常直白:你可以用 <gradle | maven | sbt | anything> 来格式化 <antlr | c | c# | ... | yaml | anything>。也就是说,语言支持与构建系统支持是两条独立轴,用户可以按需组合。官方维护的入口文档(本仓库 README.md)为每个构建系统单独维护了详细使用手册:

  • Spotless for Gradle:插件 id 为 com.diffplug.spotless,集成 VS Code 与 IntelliJ;
  • Spotless for Maven:artifact 为 com.diffplug.spotless:spotless-maven-plugin;
  • Spotless for SBT:目前由社区以外部插件形式维护(sbt-spotless 0.1.3);
  • 其他构建系统:若希望为 Bazel 等新构建系统增加支持,可参考 CONTRIBUTING.md 中的接入说明。

二、Gradle 三分钟上手:从构建失败到 BUILD SUCCESSFUL

在 Gradle 中使用 Spotless 时,对使用你构建的人而言,整个体验是这样一条命令链(来自根 README 的官方示例):

user@machine repo % ./gradlew build
:spotlessJavaCheck FAILED
  The following files had format violations:
  src\main\java\com\diffplug\gradle\spotless\FormatExtension.java
    -\t\t····if·(targets.length·==·0)·{
    +\t\tif·(targets.length·==·0)·{
  Run './gradlew spotlessApply' to fix these violations.
user@machine repo % ./gradlew spotlessApply
:spotlessApply
BUILD SUCCESSFUL
user@machine repo % ./gradlew build
BUILD SUCCESSFUL

即:spotlessCheck 发现格式违规并给出精确 diff → 运行 spotlessApply 自动修复 → 重新构建通过。对应的最小配置如下(完整 Quickstart 见 plugin-gradle/README.md):

spotless {
  // optional: limit format enforcement to just the files changed by this feature branch
  ratchetFrom 'origin/main'

  format 'misc', {
    // define the files to apply `misc` to
    target '*.gradle', '.gitattributes', '.gitignore'

    // define the steps to apply to those files
    trimTrailingWhitespace()
    leadingSpacesToTabs() // or leadingTabsToSpaces. Takes an integer argument if you don't like 4
    endWithNewline()
  }
  java {
    // don't need to set target, it is inferred from java

    // apply a specific flavor of google-java-format
    googleJavaFormat('1.8').aosp().reflowLongStrings().skipJavadocFormatting()
    // fix formatting of type annotations
    formatAnnotations()
    // make sure every file has the following copyright header.
    // optionally, Spotless can set copyright years by digging
    // through git history (see "license" section below)
    licenseHeader '/* (C)$YEAR */'
  }
}

这段配置揭示了 Spotless 的两个核心概念:

  1. format(格式块):spotless 由一组 format 组成(上例是 misc 和 java),每个 format 都有一个 target(要格式化的文件集合),用 target 和 targetExclude 设置;
  2. FormatterStep(格式化步骤):每个 format 内是一串步骤,本质都是 String -> String 的纯函数,例如 replace、replaceRegex、trimTrailingWhitespace、custom、prettier、eclipseWtp、licenseHeader 等。所有通用步骤定义在 FormatExtension.java 中,语言专属步骤则在其语言专属子类中。

运行前提(Requirements):Spotless 需要 JRE 17+ 与 Gradle 7.3 或更新版本。如果受限于旧环境,可以回退到旧版本插件:JRE 11 用 7.2.1 或更旧,JRE 8 用 6.13.0 或更旧,Gradle 2.x 用 4.5.1(详见 plugin-gradle/CHANGES.md)。

三、Maven 三分钟上手:mvn spotless:check 与 spotless:apply

Maven 侧的体验与 Gradle 完全对称(官方示例):

user@machine repo % mvn spotless:check
[ERROR]  > The following files had format violations:
[ERROR]  src\main\java\com\diffplug\gradle\spotless\FormatExtension.java
[ERROR]    -\t\t····if·(targets.length·==·0)·{
[ERROR]    +\t\tif·(targets.length·==·0)·{
[ERROR]  Run 'mvn spotless:apply' to fix these violations.
user@machine repo % mvn spotless:apply
[INFO] BUILD SUCCESS
user@machine repo % mvn spotless:check
[INFO] BUILD SUCCESS

对应的 pom 配置(完整版见 plugin-maven/README.md):

<plugin>
  <groupId>com.diffplug.spotless</groupId>
  <artifactId>spotless-maven-plugin</artifactId>
  <version>${spotless.version}</version>
  <configuration>
    <!-- optional: limit format enforcement to just the files changed by this feature branch -->
    <ratchetFrom>origin/main</ratchetFrom>
    <formats>
      <!-- you can define as many formats as you want, each is independent -->
      <format>
        <!-- define the files to apply to -->
        <includes>
          <include>.gitattributes</include>
          <include>.gitignore</include>
        </includes>
        <!-- define the steps to apply to those files -->
        <trimTrailingWhitespace/>
        <endWithNewline/>
        <indent>
          <tabs>true</tabs>
          <spacesPerTab>4</spacesPerTab>
        </indent>
      </format>
    </formats>
    <!-- define a language-specific format -->
    <java>
      <!-- no need to specify files, inferred automatically, but you can if you want -->

      <!-- apply a specific flavor of google-java-format and reflow long strings -->
      <googleJavaFormat>
        <version>1.8</version>
        <style>AOSP</style>
        <reflowLongStrings>true</reflowLongStrings>
        <formatJavadoc>false</formatJavadoc>
      </googleJavaFormat>

      <!-- make sure every file has the following copyright header. -->
      <licenseHeader>
        <content>/* (C)$YEAR */</content>  <!-- or <file>${project.basedir}/license-header</file> -->
      </licenseHeader>
    </java>
  </configuration>
</plugin>

Maven 插件要求 Maven 3.1.0 及以上、JRE 17+(JRE 11 用 2.46.1,JRE 8 用 2.30.0 或更旧)。同时有两个 Maven 特有要点:

  • 步骤顺序很重要,而且是好事:例如 googleJavaFormat 永远用空格缩进,若你希望制表符缩进,必须把 <indent> 放在它之后;放在之前会被覆盖:
    <googleJavaFormat/>   <!-- this works -->
    <indent><tabs>true</tabs><spacesPerTab>2</spacesPerTab></indent>
    
  • 绑定 Maven 阶段:默认 spotless:check 绑定到 verify 阶段,只要声明 check goal 即可随 mvn verify 执行;也可以在 <executions> 中用 <phase>compile</phase> 改绑到其他阶段。

四、SBT 与其他构建系统

SBT 用户目前通过外部社区插件 sbt-spotless(0.1.3)使用。若你的构建系统不在官方列表内,Spotless 的架构刻意让"新增一个构建系统插件"和"新增一个 FormatterStep"互相独立——你只需要把一个已有的 FormatterStep 接入你的构建系统即可,具体做法记录在 CONTRIBUTING.md。

五、核心原理:每个格式化步骤都是一个 Function<String, String>

根 README 的 "How it works" 一节把 Spotless 的设计哲学讲得很清楚:一个理想的格式化器不只是报告错误,它应该能修复错误。而一个能修复代码的格式化器,本质上就是一个 Function<String, String>——输入可能未格式化的文本,返回格式化后的文本。

构造这样一个函数很容易,但真正的工程量在于各种"坑"与集成:换行符、字符编码、幂等性、git ratchet,以及构建系统集成。Spotless 把这些脏活全部替你处理掉,让你可以专注于写一个简单的 Function<String, String>,并且它能够与 Spotless 军团中的任何其他格式化器和构建工具自由组合。

从源码看,这一抽象落在 FormatterStep.java 接口上:

public interface FormatterStep extends Serializable, AutoCloseable {
    /** The name of the step, for debugging purposes. */
    String getName();

    @Nullable
    String format(String rawUnix, File file) throws Exception;
    ...
}

关键约束写在该接口的 javadoc 里:输入保证是 unix 风格换行(\n),输出也禁止引入 windows 风格换行。这一约定让所有步骤可以安全地顺序组合。

真正的"组合执行器"是 Formatter.java,它持有 lineEndingsPolicy、encoding 与有序的 List<FormatterStep>,其 computeWithLint 方法逐步骤调用 step.format(...),每步输出先统一为 unix 换行(LineEnding.toUnix)再交给下一步;若某步抛异常则记录到 ValuePerStep 中继续执行,最后由 legacyErrorBehavior 统一决定抛错还是作为 lint 呈现。整个 Formatter 是 Serializable 的,这为 Gradle 的配置缓存、增量构建与 build cache 提供了序列化基础。

仓库 lib/src/main/java/com/diffplug/spotless/generic/ 目录下提供了大量即插即用的通用步骤实现:TrimTrailingWhitespaceStep、EndWithNewlineStep、IndentStep、ReplaceStep、ReplaceRegexStep、LicenseHeaderStep、NativeCmdStep、Jsr223Step 等;语言专属步骤则散落在 java/、kotlin/、json/、npm/ 等子包中(例如 GoogleJavaFormatStep、ImportOrderStep、RemoveUnusedImportsStep、PrettierFormatterStep、BiomeStep、ShfmtStep、BlackStep、ScalaFmtStep、KtLintStep 等)。这些步骤的完整清单与支持矩阵见下文第七节。

六、幂等性保障(PaddedCell):格式化器的"自我一致性"守护

一个正确(idempotent)的格式化器 F 必须满足:对所有输入,F(F(input)) == F(input)。如果某步骤不满足,spotlessCheck 将永远失败——因为格式化结果本身不稳定。复杂的代码格式化器常常在 corner case 中表现出"乒乓"行为:在两三个状态之间来回切换,甚至形成更长的循环。

Spotless 内置了自动的幂等性防护,其完整设计与示例记录在 PADDEDCELL.md 中。它的判定逻辑是把输入反复应用格式化器,然后按结果归类:

  • Two-state cycle:'CCCC' 'A' 'B' 'A' ...——检测到循环 'B' 'A' 后,取按长度优先、其次按字母序最小的元素作为规范格式(本例为 A);
  • Four-state cycle:'A' 'B' 'C' 'D' 'A' ...——同样取循环中最小元素 A;
  • Convergence:'ATT' 'AT' 'A' 'A'——无循环但逐步收敛,以收敛结果 A 为规范格式;
  • Divergence:'1' '12' '123' ...——既不循环也不收敛,PaddedCell 在 10 次尝试后放弃,保留初始值作为规范格式。

实现层面,PaddedCell.java 定义了 CONVERGE / CYCLE / DIVERGE 三种结果类型,PaddedCell.check(Formatter, File) 是入口:应用一次若与原文相同即 CONVERGE,应用两次仍不同则继续迭代直到 MAX_CYCLE = 10 上限。对应的测试见 PaddedCellTest.java。这意味着:哪怕某个第三方格式化器在极端输入下不自洽,Spotless 也能自动选定一个稳定的规范输出,而不是无限震荡。

七、Feature Matrix:语言步骤 × 构建系统的完整支持矩阵

根 README 用一张"feature matrix"总结当前能力(已去除 freshmark 生成标记,保留实际内容)。行是功能或 FormatterStep,列是 Gradle / Maven / SBT / 新构建系统:

Feature / FormatterStep gradle maven sbt 新构建系统
Automatic idempotency safeguard ✅ ✅ ✅ ⬜
Misconfigured encoding safeguard ✅ ✅ ✅ ⬜
Toggle with spotless:off and spotless:on ✅ ✅ ⬜ ⬜
Ratchet from origin/main or other git ref ✅ ✅ ⬜ ⬜
Define line endings using git ✅ ✅ ✅ ⬜
Fast incremental format and up-to-date check ✅ ✅ ⬜ ⬜
Fast format on fresh checkout using buildcache ✅ ⬜ ⬜ ⬜
generic.EndWithNewlineStep ✅ ✅ ⬜ ⬜
generic.IndentStep ✅ ✅ ⬜ ⬜
generic.Jsr223Step ⬜ ✅ ⬜ ⬜
generic.LicenseHeaderStep ✅ ✅ ✅ ⬜
generic.NativeCmdStep ✅ ✅ ⬜ ⬜
generic.ReplaceRegexStep ✅ ✅ ⬜ ⬜
generic.ReplaceStep ✅ ✅ ⬜ ⬜
generic.TrimTrailingWhitespaceStep ✅ ✅ ⬜ ⬜
antlr4.Antlr4FormatterStep ✅ ✅ ⬜ ⬜
biome.BiomeStep ✅ ✅ ⬜ ⬜
cpp.ClangFormatStep ✅ ⬜ ⬜ ⬜
cpp.EclipseFormatterStep ✅ ✅ ✅ ⬜
go.GofmtFormatStep ✅ ⬜ ⬜ ⬜
gherkin.GherkinUtilsStep ✅ ✅ ⬜ ⬜
groovy.GrEclipseFormatterStep ✅ ✅ ✅ ⬜
java.GoogleJavaFormatStep ✅ ✅ ✅ ⬜
java.ImportOrderStep ✅ ✅ ✅ ⬜
java.PalantirJavaFormatStep ✅ ✅ ⬜ ⬜
java.PrinceOfSpaceStep ✅ ✅ ⬜ ⬜
java.RemoveUnusedImportsStep ✅ ✅ ✅ ⬜
java.ExpandWildcardImportsStep ✅ ⬜ ⬜ ⬜
java.ForbidWildcardImportsStep ✅ ✅ ✅ ⬜
java.ForbidModuleImportsStep ✅ ✅ ⬜ ⬜
java.ShortenFullyQualifiedTypesStep ✅ ✅ ⬜ ⬜
java.EclipseJdtFormatterStep ✅ ✅ ✅ ⬜
java.FormatAnnotationsStep ✅ ✅ ⬜ ⬜
java.CleanthatJavaStep ✅ ✅ ⬜ ⬜
java.TableTestFormatterStep ✅ ✅ ⬜ ⬜
json.gson.GsonStep ✅ ✅ ⬜ ⬜
json.JacksonJsonStep ✅ ✅ ⬜ ⬜
json.JsonSimpleStep ✅ ✅ ⬜ ⬜
json.JsonPatchStep ✅ ✅ ⬜ ⬜
kotlin.KtLintStep ✅ ✅ ✅ ⬜
kotlin.KtfmtStep ✅ ✅ ⬜ ⬜
kotlin.DiktatStep ✅ ✅ ⬜ ⬜
markdown.FreshMarkStep ✅ ⬜ ⬜ ⬜
markdown.FlexmarkStep ✅ ✅ ⬜ ⬜
npm.EslintFormatterStep ✅ ✅ ⬜ ⬜
npm.PrettierFormatterStep ✅ ✅ ⬜ ⬜
npm.TsFmtFormatterStep ✅ ✅ ⬜ ⬜
pom.SortPomStep ✅ ✅ ⬜ ⬜
protobuf.BufStep ✅ ⬜ ⬜ ⬜
python.BlackStep ✅ ⬜ ⬜ ⬜
rdf.RdfFormatterStep ⬜ ✅ ⬜ ⬜
scala.ScalaFmtStep ✅ ✅ ✅ ⬜
shell.ShfmtStep ✅ ✅ ⬜ ⬜
sql.DBeaverSQLFormatterStep ✅ ✅ ✅ ⬜
wtp.EclipseWtpFormatterStep ✅ ✅ ⬜ ⬜
yaml.JacksonYamlStep ✅ ✅ ⬜ ⬜

以上所有 FormatterStep 的 Java 实现均可在 lib/src/main/java/com/diffplug/spotless/ 及其子包(lib-extra 中为基于 Eclipse 的 cpp.EclipseFormatterStep、groovy.GrEclipseFormatterStep、java.EclipseJdtFormatterStep、wtp.EclipseWtpFormatterStep)中找到。矩阵中标记"⬜"的空格子,正是社区贡献的入口。

为什么会有空格子?

根 README 明确解释了矩阵哲学:项目越大越难维护,而 Spotless 刻意不要求贡献者"填满矩阵"。你可以只为一个构建系统接入一个格式化器,只要它对你自己的工作有用,PR 就会被接受;而一旦某个格子被填上,其他人就有了完整的参考实现,填其他空格子会变得很容易。例如可以为 CONTRIBUTING.md 中描述的"新增一个 FormatterStep"提供任意单一构建系统支持。

八、编码与换行:那些"看不见的东西"

编码(encoding)与换行(line ending)是格式化工具最容易出错、也最影响 git 协作体验的细节,Spotless 对此有专门设计(对应测试见 EncodingErrorMsgTest.java):

  • 编码:默认使用 UTF-8,也支持 JVM 支持的任何编码,可全局设置,也可按 format 覆盖:

    spotless {
      encoding 'UTF-8' // all formats will be interpreted as UTF-8
      java {
        encoding 'Cp1252' // except java, which will be Cp1252
    
  • 换行(lineEndings):支持三类模式——

    • 常量模式:UNIX、WINDOWS、MAC_CLASSIC;
    • 简单模式:PLATFORM_NATIVE、PRESERVE;
    • git 感知模式:GIT_ATTRIBUTES、GIT_ATTRIBUTES_FAST_ALLSAME。

    默认值是 GIT_ATTRIBUTES_FAST_ALLSAME,官方强烈建议不要改动:git 对换行有自己的意见,如果 Spotless 与 git 意见不一致会引发灾难性的 diff。FAST_ALLSAME 意味着 Spotless 可以假定同一批文件使用相同的换行符,从而大幅提速。推荐用 .gitattributes 统一控制,例如 * text eol=lf 把所有文件设为 unix 换行。

从源码看,Formatter.computeLineEndings 根据 LineEnding.Policy 为每个文件计算最终换行,再对 unix 内容做替换,确保"步骤内一律 unix、写出时按策略还原"的约定闭环。

九、渐进式强制格式化(ratchet):避免"格式化一切"的巨型提交

如果项目此前完全没有强制格式化,直接启用会带来一个巨大的、难以阅读的"格式化一切"提交。ratchet 特性正是为此而生:

spotless {
  ratchetFrom 'origin/main' // only format files which have changed since origin/main
}

此模式下 Spotless 只处理自 origin/main 以来变更过的文件。ratchet 的基准可以是任意 git ref(甚至 HEAD),也可以按 format 单独设置(如 spotless { java { ratchetFrom ... } })。官方强烈建议使用非本地分支(tag 或 origin/main):如果使用 HEAD 或本地分支,一旦你把文件提交了,那个提交内容(哪怕格式是错的)就变成了新的规范基准;而使用 origin/main 或 tag,CI 会在"变更过的文件没有变得更好"时失败。

CI 注意事项:GitHub、GitLab、BitBucket、Travis 等 CI 默认使用 shallow clone,此时 ratchetFrom 'origin/main' 会报 No such reference。解决方法是先执行 git fetch origin main,或关闭 shallow clone。

十、许可证头(License Header)与 $YEAR 自动年份

通过 licenseHeader 或 licenseHeaderFile 指定许可证头时,若内容包含 $YEAR 或 $today.year,该 token 会被替换为当前 4 位年份。例如 2020 年运行时,/* Licensed under Apache-2.0 $YEAR. */ 会生成 /* Licensed under Apache-2.0 2020. */。已有合法年份(如 2020 或 2017-2020)的头部不会被改动;若想随年份更新,可配合 ratchetFrom,按如下规则自动更新(假设当前年为 2020):

  • 无许可证头 → 2020
  • 2017 → 2017-2020
  • 2017-2019 → 2017-2020

此外还有两个实用能力:

  • 从 git 历史回溯年份:对历史项目可用 -PspotlessSetLicenseHeaderYearsFromGitHistory=true 触发一次性的 git 历史搜索,按每个文件最早/最晚提交设置版权年份;
  • 固定头行跳过:XML 的 <?xml version="1.0" ...、bash 脚本的 #!/bin/bash 等固定头行不能置于注释之前,可用 skipLinesMatching 配置正则跳过,例如 .skipLinesMatching("^#!.+?\$") 跳过 shebang。

源码层面,LicenseHeaderStep.java 用 YearMode 枚举(PRESERVE / UPDATE_TO_TODAY / SET_FROM_GIT)驱动年份行为,并提供默认 Java 分隔符 (package|import|public|class|module) 用于定位文件头位置。

十一、spotless:off 与 spotless:on:局部豁免

有时候某段代码是你精心手写的,不希望被自动格式化覆盖。启用:

spotless {
  java { // or kotlin, or c, or python, or whatever
    toggleOffOn()

之后,凡是被一对 spotless:off / spotless:on 包裹的代码,无论其他规则如何,一律不参与格式化。也可以自定义标签,例如 toggleOffOn('fmt:off', 'fmt:on')(Gradle 与 Maven 均支持;SBT 暂不支持,见第七节矩阵)。

十二、生产落地进阶:lint、git hook 与自定义步骤

  • Linting:自 7.0.0 起 Spotless 在格式化之外还支持 linting。对 Spotless 而言所有 lint 都是必须修复或抑制的错误,失败时会列出 文件:行号 step(code) 描述;可用 suppressLintsFor { step = 'ktlint'; shortCode = 'standard:no-wildcard-imports' } 这类配置抑制。官方定位是:Spotless 首先是格式化器而不是 linter——"linter 只是一个坏掉的 formatter",但当 formatter 确实会失败时,用可抑制的 lint 表达比直接放弃更有用。
  • Git hook:运行 ./gradlew spotlessInstallGitPrePushHook(Gradle)或 mvn spotless:install-git-pre-push-hook(Maven)即可安装 pre-push 钩子:push 时先跑 spotlessCheck,发现问题会自动 spotlessApply 修复并中止 push,让你提交修复后重推。实现位于 GitPrePushHookInstallerGradle.java 与 GitPrePushHookInstallerMaven.java。
  • 自定义步骤:既可以直接在构建脚本里写 custom 'lowercase', { str -> str.toLowerCase() }(注意:自定义规则会禁用 up-to-date 检查与缓存,除非按 bumpThisNumberIfACustomStepChanges 的 javadoc 仔细处理);也可以在 buildSrc 里实现正规 FormatterStep 后通过 addStep(...) 接入。抛异常时:AssertionError 及其子类被报告为"文件本身的问题",其他异常被报告为"formatter 自身的 bug"。
  • 针对特定文件:可通过 -PspotlessFiles=my/file/pattern.java,more/generic/.*-pattern.java 用逗号分隔的模式列表把 spotlessApply 限定到特定文件(按绝对路径做 String#matches 匹配)。
  • 依赖解析模式:超大并行构建可用 spotlessPredeclare { java { eclipse() } ... } 将依赖解析集中到根项目,避免 per-project 解析问题;但此模式与 Isolated projects 不兼容。
  • 预览与回滚:先 git add -A && git commit 存档,再跑 spotlessApply,用 git diff 审阅;不满意 git reset --hard,满意则 git reset --soft head~1 让存档提交"消失"但保留改动。

十三、如何继续深入

总体而言,Spotless 的价值在于把"格式化"还原为一个可组合、可验证、可渐进引入的纯函数管道:你只需在 spotless { ... } 里声明"哪些文件 × 哪些步骤",剩下的幂等性、编码、换行、git ratchet、增量构建与缓存都由它兜底,让 "Keep your code spotless" 成为一条可持续执行的工程纪律。

登录后查看全文
spotless