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

标签 java git maven intellij-idea code-formatting

当前状态:

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

我的调查/解决方案:

在调查过程中我发现solution ,这听起来很容易。只需更新 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>

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

问题:

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

最佳答案

您可以让预提交 Hook 触发暂存提交的文件的格式化程序。

git-code-format-maven-plugin使用google-java-format格式化程序,并且可以在编译阶段安装客户端预提交 git hook。它requires 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>

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

mvncompile 来安装钩子(Hook)。对于IDEA来说,就是这样。

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

Eclipse 的解决方法

由于 EGit 中的一个错误(有时会完全忽略 Git Hook ),在 Windows 上使用 Eclipse 的开发人员应该在 PATH 中包含 Cygwin。一个空的 cygpath.exe 就可以了。以管理员身份运行“命令提示符”并执行 C:\>echo "">/"Program Files"/Git/bin/cygpath.exe (感谢 hook is not working eclipse egit client )。

重新启动。

关于 java import 语句排序的说明

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

关于java - 如何根据google java格式格式化代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50857698/

相关文章:

Java Swing JTextField setInputVerifier 保持关注 TextField

java - 如何使用一个依赖于另一个 jar 的 jar

Git:如何恢复强制推送

git - 有人真的在使用 git super/subprojects 吗?

maven - JSF 找不到 h :inputFile tag

java - 添加到指定索引时数组列表的行为

javascript - 如何在javascript中从ArrayBuffer获取Short值?

git - 如何在 git 树的顶部应用补丁以防止重复?

java - 无法在 jenkins 中编译 maven 项目,而它在 eclipse "Source option 6 is no longer supported. Use 7 or later"中运行良好

java - 嵌入式Jetty 8热部署类(使用Maven)