龙台,Apache ShardingSphere Contributor,GitHub 2.2K star hippo4j 作者,Github ID:longtai-cn。
为什么要代码格式化?代码格式化的意义是让代码更加 易读易懂易修改。
ShardingSphere 作为 Apache 顶级开源项目,截止当前已有 380+ 贡献者。因为大部分开发人员的代码风格不一致,在 Github 多人协作的模式下,不易保障项目整体代码格式。
基于以上诉求,ShardingSphere 采用了 Spotless 充当代码格式统一的角色。
什么是 Spotless
Spotless 是支持多种语言的代码格式化工具,支持 Maven 和 Gradle 以 Plugin 的形式构建。
Spotless 对开发者来说,有 2 种使用方式:检查代码是否存在格式问题,以及格式化代码。
ShardingSphere 采用 Maven 构建项目,以下若无特殊声明,Spotless 使用 Maven 做演示。
如何使用
下述代码是 Spotless 官方示例。
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
通过 mvn spotless:check
检查项目代码时发现错误,接着使用 mvn spotless:apply
进行代码格式化;再次检查时,格式化错误消失。
1. 项目实战
ShardingSphere 使用 Spotless 实现了添加 Java 文件 licenseHeader 和 Java 代码格式化。
Spotless 有多种 Java 代码格式化方式,例如:googleJavaFormat、eclipse、prettier 等。基于定制化的考虑,最终采用 eclipse 进行 Java 代码格式化。
1)根据项目需求添加 licenseHeader
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
注意,licens