Apache ShardingSphere 代码格式化实战 —— Spotless

龙台,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

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值