如何根据google java格式格式化代码

Beg*_*ner 7 java git code-formatting intellij-idea maven

当前状态:

我有一个使用以下工具构建的项目:Java 1.8.161、Maven 3.3.9、SpringBoot 2.0.1,工具:Jenkins 和 GitLab。我想使用google java 格式作为整个团队的标准。

我的调查/解决方案:

在调查过程中,我找到了解决方案,这听起来很简单。只需使用以下命令更新 pom 文件:

<build>
    <plugins>
        <plugin>
            <groupId>com.coveo</groupId>
            <artifactId>fmt-maven-plugin</artifactId>
            <version>2.5.0</version>
            <executions>
                <execution>
                    <goals>
                        <goal>format</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>
Run Code Online (Sandbox Code Playgroud)

它有效。如果我运行编译、打包、验证、安装或部署 Maven 生命周期,代码将被格式化。

题:

我如何在所有团队成员每次提交后运行它,而无需在他们的 IDEA 中执行任何额外步骤?因为现在,我需要在每次提交之前运行 Maven。但是在应用程序运行过程中没有必要,所以团队可以避免它..这当然会导致git中的历史问题。

小智 5

您可以让pre-commit 钩子触发为提交暂存的文件格式化程序。

git-code-format-maven-plugin使用google-java-format格式化程序,并且可以在编译阶段安装客户端预提交 git hook。它需要Maven 3.5.x,应该强制执行。

<build>
  <plugins>
    <plugin>
      <groupId>com.cosium.code</groupId>
      <artifactId>git-code-format-maven-plugin</artifactId>
      <version>VERSION</version>
      <executions>
        <execution>
          <goals>
            <goal>install-hooks</goal>
          </goals>
        </execution>
      </executions>
    </plugin>
    <plugin>
      <artifactId>maven-enforcer-plugin</artifactId>
      <version>VERSION</version>
      <executions>
        <execution>
          <goals>
            <goal>enforce</goal>
          </goals>
          <configuration>
            <rules>
              <requireMavenVersion>
                <version>[3.5.4,)</version>
              </requireMavenVersion>
            </rules>
          </configuration>
        </execution>
      </executions>
    </plugin>
  </plugins>
</build>
Run Code Online (Sandbox Code Playgroud)

指向IDE 中的独立Maven,因为git-code-format-maven-plugin不能很好地与嵌入式 Maven 配合使用。

mvn compile安装钩子。对于IDEA,就是这样。

由于git-code-format-maven-plugin仅格式化更改的文件(这很好),因此预先格式化整个项目可能很好(mvn git-code-format:format-code -Dgcf.globPattern=**/*)。

Eclipse 的解决方法

由于 EGit 中的一个错误,它有时会完全忽略 Git 钩子,因此在 Windows 上使用Eclipse 的开发人员应该在 PATH 中有 Cygwin。空的cygpath.exe就行。以管理员身份运行“命令提示符”并执行C:\>echo "" > /"Program Files"/Git/bin/cygpath.exe钩子无法正常工作 eclipse egit 客户端)。

重启。

关于 java import 语句排序的说明

在 IDE 中优化导入或重新格式化或使用插件重新格式化,可能会导致导入顺序发生变化。如果将旧版本的git-code-format-maven-pluginfmt-maven-plugin一起使用(例如,稍后在 CI 中格式化或验证代码),则会令人讨厌。