如何通过极狐GitLab 平滑落地 Java 增量代码规范?

news2025/6/8 13:47:46

本文来自:

杨周 极狐GitLab 高级解决方案架构师

代码越写越规范是优秀开发者的成长之路,但很多人对老项目感到有心无力,因为太不规范了,所有人停下来一起修复也要花费很长时间,而且一次改动太多难以确保可靠性,怎么办?

有的语言可以借助 Git diff 把本次修改的代码挑出来,实现增量扫描,但 Java 很难这么做。

有的人在持续集成里配置了规范扫描工具,但报错之后需要在成千上万行 log 里查找,降低了研发效率。

Checkstyle 是业界知名的开源扫描工具,可扫描 Sun、Google 等代码规范,提供Maven、Gradle 插件。本文以 Java 项目配置 Checkstyle 扫描工具为例,分享消灭这些问题的办法:

1. 将代码规范问题显示在「合并请求页面」,大幅度提高研发效率;

2. 增量代码规范报告。

下文分别介绍「Java Maven 项目」「Java Gradle 项目」的配置方法。

通过极狐GitLab CI 平滑落地 Java 增量代码规范Checkstyle Maven


在项目中引入 Checkstyle 插件,并下载代码规范:

$ vi pom.xml
<plugin> 
  <groupId>org.apache.maven.plugins</groupId> 
  <artifactId>maven-checkstyle-plugin</artifactId> 
  <version>3.2.0</version> 
  <configuration> 
    <encoding>UTF-8</encoding> 
    <consoleOutput>true</consoleOutput> 
    <failsOnError>true</failsOnError> 
    <violationSeverity>warning</violationSeverity> 
    <configLocation>config/checkstyle/checkstyle.xml</configLocation> 
  </configuration> 
</plugin>
$ mkdir -p config/checkstyle/
$ wget https://raw.githubusercontent.com/checkstyle/checkstyle/checkstyle-9.3/src/main/resources/google_checks.xml -O config/checkstyle/checkstyle.xml

执行全量扫描命令,查看效果:

$ ./mvnw checkstyle:check

[WARN] Demo.java:6:1: 缺少 Javadoc 。 [MissingJavadocType]
[WARN] Demo.java:9:1: 行内含有制表符 tab 。 [FileTabCharacter]
[WARN] Demo.java:9:9: 'method def modifier' 缩进了8个缩进符,应为2个。 [Indentation]

在极狐GitLab 持续集成中执行强制扫描:

$ vi .gitlab-ci.yml

checkstyle:
  script:
    - ./mvnw checkstyle:check

当扫描工具报错,持续集成退出,想看代码规范问题,需要到 log 中查找。很多持续集成产品只做到了这一步,但这降低了开发效率,因此极狐GitLab 更进一步——采集「代码质量报告」。

在项目中引入 violations-maven-plugin,它会将 Checkstyle 报告转换成极狐GitLab 标准格式。

$ vi pom.xml
<plugin>
    <groupId>se.bjurr.violations</groupId>
    <artifactId>violations-maven-plugin</artifactId>
    <version>1.50.4</version>
    <executions>
        <execution>
            <phase>validate</phase>
            <goals>
                <goal>violations</goal>
            </goals>
            <configuration>
                <!-- Optional config -->
                <!-- 0 is disabled -->
                <maxReporterColumnWidth>0</maxReporterColumnWidth>
                <maxRuleColumnWidth>0</maxRuleColumnWidth>
                <maxSeverityColumnWidth>0</maxSeverityColumnWidth>
                <maxLineColumnWidth>0</maxLineColumnWidth>
                <maxMessageColumnWidth>30</maxMessageColumnWidth>
                <!-- Will create a CodeClimate JSON report. -->
                <codeClimateFile>gl-code-quality-report.json</codeClimateFile>

                <!-- Global configuration, remove if you dont want to report violations
                    for the entire repo. -->
                <!-- INFO, WARN or ERROR -->
                <minSeverity>INFO</minSeverity>
                <!-- PER_FILE_COMPACT, COMPACT or VERBOSE -->
                <detailLevel>VERBOSE</detailLevel>
                <!-- Will fail the build if total number of found violations is higher -->
                <maxViolations>99999999</maxViolations>
                <!-- Will print violations found in diff -->
                <printViolations>true</printViolations>


                <!-- Diff configuration, remove if you dont want to report violations
                    for files changed between specific revisions. -->
                <!-- Can be empty (ignored), Git-commit or any Git-reference -->
                <diffFrom></diffFrom>
                <!-- Same as above -->
                <diffTo></diffTo>
                <!-- INFO, WARN or ERROR -->
                <diffMinSeverity>INFO</diffMinSeverity>
                <!-- PER_FILE_COMPACT, COMPACT or VERBOSE -->
                <diffDetailLevel>VERBOSE</diffDetailLevel>
                <!-- Will fail the build if number of violations, in the diff within
                    from/to, is higher -->
                <diffMaxViolations>99</diffMaxViolations>
                <!-- Will print violations found in diff -->
                <diffPrintViolations>true</diffPrintViolations>
                <!-- Where to look for Git -->
                <gitRepo>.</gitRepo>

                <!-- This is mandatory regardless of if you want to report violations
                    between revisions or the entire repo. -->
                <violations>
                    <violation>
                        <parser>CHECKSTYLE</parser>
                        <reporter>Checkstyle</reporter>
                        <folder>.</folder>
                        <pattern>.*/target/checkstyle-result\.xml$</pattern>
                    </violation>
                </violations>
            </configuration>
        </execution>
    </executions>
</plugin>

在极狐GitLab CI 中采集代码规范报告:

image: eclipse-temurin:8

cache:
  paths:
    - /root/.m2

stages:
  - lint
  - build

checkstyle:
  allow_failure: true
  stage: lint
  script:
    - ./mvnw checkstyle:check
  artifacts:
    when: always
    untracked: true

report:
  stage: lint
  script:
    - ./mvnw validate
  needs:
    - job: checkstyle
      artifacts: true
  artifacts:
    reports:
      codequality: gl-code-quality-report.json

compile:
  stage: build
  script:
    - ./mvnw package -Dmaven.test.skip=true
  artifacts:
    untracked: true

可以看到在开发人员频繁使用的「合并请求」页面,直接显示了「代码规范问题」,供开发人员自助修复以及提醒评审的同事注意,这样可以有效提高研发效率。

老项目第一次配置代码规范可能会出现很多错误(比如上图有 7746 个),没关系,先将规范合并进入主干,下次修改代码发起合并请求时,极狐GitLab 将展示「增量代码质量报告」,而无需任何复杂设置。比如下图就只有 5 个新问题了:

通过极狐GitLab CI 平滑落地 Java 增量代码规范 Checkstyle Gradle


「Java Gradle 项目」和「Java Maven 项目」的配置方法一致:

在项目中引入 Checkstyle 插件,并下载代码规范:

$ vi build.gradle
plugins {
  id 'checkstyle'
}
checkstyle {
  toolVersion = '9.3'
  maxWarnings = 0
  maxErrors = 0
}
$ mkdir -p config/checkstyle/
$ wget https://raw.githubusercontent.com/checkstyle/checkstyle/checkstyle-9.3/src/main/resources/google_checks.xml -O config/checkstyle/checkstyle.xml

执行全量扫描命令,查看效果:

$ ./gradlew check

[WARN] Demo.java:6:1: 缺少 Javadoc 。 [MissingJavadocType]
[WARN] Demo.java:9:1: 行内含有制表符 tab 。 [FileTabCharacter]
[WARN] Demo.java:9:9: 'method def modifier' 缩进了8个缩进符,应为2个。 [Indentation]

在极狐GitLab 持续集成中执行强制扫描:

$ vi .gitlab-ci.yml

checkstyle:
  script:
    - ./gradlew check

同样,在项目中引入 violations-maven-plugin,它会将 Checkstyle 报告转换成极狐 GitLab 标准格式。

$ vi build.gradle
buildscript {
  repositories {
    maven { url 'https://plugins.gradle.org/m2/' }
  }
  dependencies {
    classpath "se.bjurr.violations:violations-gradle-plugin:1.52.2"
  }
}

task violations(type: se.bjurr.violations.gradle.plugin.ViolationsTask) {
  //
  // Optional config
  //
  maxReporterColumnWidth = 0 // 0 means "no limit"
  maxRuleColumnWidth = 60
  maxSeverityColumnWidth = 0
  maxLineColumnWidth = 0
  maxMessageColumnWidth = 50
  codeClimateFile = file('gl-code-quality-report.json') // Will create a CodeClimate JSON report.
  violationsFile = file('violations-file.json') // Will create a normalized JSON report.


  //
  // Global configuration, remove if you dont want to report violations for
  // the entire repo.
  //
  minSeverity = 'INFO' // INFO, WARN or ERROR
  detailLevel = 'VERBOSE' // PER_FILE_COMPACT, COMPACT or VERBOSE
  maxViolations = 99999999 // Will fail the build if total number of found violations is higher
  printViolations = true // Will print violations found in diff


  //
  // Diff configuration, remove if you dont want to report violations for
  // files changed between specific revisions.
  //
  // diff-properties can be supplied with something like:
  //
  // ./gradlew violations -PdiffFrom=e4de20e -PdiffTo=HEAD
  //
  // And in Travis, you could add:
  //
  //  script:
  //   - 'if [ "$TRAVIS_PULL_REQUEST" != "false" ]; then bash ./gradlew check -PdiffFrom=$TRAVIS_PULL_REQUEST_BRANCH -PdiffTo=$TRAVIS_BRANCH ; fi'
  //
  diffFrom = project.properties.diffFrom // Can be empty (ignored), Git-commit or any Git-reference
  diffTo = project.properties.diffTo // Same as above
  diffMinSeverity = 'INFO' // INFO, WARN or ERROR
  diffDetailLevel = 'VERBOSE' // PER_FILE_COMPACT, COMPACT or VERBOSE
  diffMaxViolations = 99 // Will fail the build if number of violations, in the diff within from/to, is higher
  diffPrintViolations = true // Will print violations found in diff
  gitRepo = file('.') // Where to look for Git


  //
  // This is mandatory regardless of if you want to report violations between
  // revisions or the entire repo.
  //
  // Many more formats available, see: https://github.com/tomasbjerre/violations-lib
  violations = [
   ["CHECKSTYLE", buildDir.path, ".*/checkstyle/.*\\.xml\$", "Checkstyle"]
  ]
}

在极狐GitLab CI 中采集代码规范报告:

image: eclipse-temurin:8

cache:
  paths:
    - /root/.m2

stages:
  - lint
  - build

checkstyle:
  allow_failure: true
  stage: lint
  script:
    - ./gradlew check
  artifacts:
    when: always
    untracked: true

report:
  stage: lint
  script:
    - ./gradlew violations
  needs:
    - job: checkstyle
      artifacts: true
  artifacts:
    reports:
      codequality: gl-code-quality-report.json

compile:
  stage: build
  script:
    - ./gradlew build -x check -x test
  artifacts:
    untracked: true

剩余步骤与「Java Gradle 项目」一致:开发人员频繁使用的「合并请求」页面,直接显示了「代码规范问题」,供开发人员自助修复以及提醒评审的同事注意,有效提高研发效率。

老项目第一次配置代码规范可能会出现很多错误(比如上图有 7746 个),没关系,先将规范合并进入主干,下次修改代码发起合并请求时,极狐GitLab 将展示「增量代码质量报告」,而无需任何复杂设置,比如下图只有 5 个新问题:

 这样,我们就通过极狐GitLab 平滑落地了 Java 增量代码规范,让项目代码越来越优雅。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/334461.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

达梦8的dblink

简介&#xff1a;外部链接对象&#xff08;LINK&#xff09;是 DM 中的一种特殊的数据库实体对象&#xff0c;它记录了远程数据库的连接和路径信息&#xff0c;用于建立与远程数据的联系。通过多台数据库主库间的相互通讯&#xff0c;用户可以透明地操作远程数据库的数据&#…

我的网站上线了!

最近有段时间没有写原创文章了&#xff0c;恰好这两天正在翻阅历史文章的时候&#xff0c;发现文章中的图片竟然裂了&#xff1f;顿时冒了一身冷汗&#xff0c;因为每逢遇到这种情况&#xff0c;动辄需要花费一周的时间迁移图片。。。。。。 当我直接访问图片 url 的时候&#…

直播预告 | 数据库自治平台 KAP 监控告警架构及实例演示

线上沙龙-技术流第 25 期营业啦02月15日&#xff08;周三&#xff09;19:30KaiwuDB - B站直播间企业级数据集群往往有成百上千的各类型运算或应用同时运行&#xff0c;为保障系统的稳定可靠性&#xff0c;势必需要克服庞大数据量、复杂运算逻辑、相互关联大数据组件等重难点&am…

4年测试经验去面试10分钟就被pass,测试现在要求这么高了?

年过完了&#xff0c;大家都开始上班了&#xff0c;各位小伙伴多多注意身体&#xff0c;但是学习也别落下等 做为一名优秀的程序员&#xff0c;技术面试都是不可避免的一个环节&#xff0c;通常技术面试官都会经过本身的方式去考察程序员的技术功底与基础理论知识。 若是你参…

python基础之PyCharm介绍

课程&#xff1a;PyCharm 课程目标 PyCharm的作用下载安装PyCharmPyCharm的基本使用PyCharm的基本设置 一. PyCharm的作用 PyCharm是一种Python IDE&#xff08;集成开发环境&#xff09;&#xff0c;带有一整套可以帮助用户在使用Python语言开发时提高其效率的工具&#x…

《Spring揭秘》记录

IOC部分 IOC不等于IOC容器&#xff0c;即使不使用spring&#xff0c;我们也可以使用IOC&#xff0c;只不过spring提供了IOC容器实现。Spring的IoC容器的功能就包含一个提供依赖注入服务的IoC Service Provider。它提供两方面的支持&#xff0c;业务对象的构建管理和业务对象间的…

GAMES202 PCSS软阴影算法细节解析

在LearnOpenGL框架的基础上实现了一遍GAMES202的PCFPCSS软阴影&#xff0c;之前学习GAMES202时一些没弄清楚的问题顺便搞清楚了。 注&#xff1a;本文中代码和shader均在笔者自学LearnOpenGL的框架中实现&#xff0c;因此有一些细节可能和GAMES202作业框架不一致&#xff0c;且…

【前端CSS面试题】2023前端最新版css模块,高频15问

&#x1f973;博 主&#xff1a;初映CY的前说(前端领域) &#x1f31e;个人信条&#xff1a;想要变成得到&#xff0c;中间还有做到&#xff01; &#x1f918;本文核心&#xff1a;博主收集的CSS面试题 目录 一、CSS必备面试题 1.CSS3新特性 2.CSS实现元素两个盒子垂…

开发技术-Java switch case 的简单用法

文章目录1. integral-selector2. case3. break4. default5. 总结最近开发写 switch 发现有的技术点还没有掌握&#xff0c;在此做个记录。ON JAVA 中文版中&#xff0c;关于 switch 的描述为&#xff1a; switch 有时也被划归为一种选择语句。根据整数表达式的值&#xff0c;s…

Vue路由 —— vue-router

在上一篇内容讲到关于单页面组件的内容&#xff0c;同时也附上补充讲了关于单页面&#xff08;SPA&#xff09;和多页面&#xff08;MPA&#xff09;之间的优缺点&#xff0c;在本篇目当中就要来讲这个路由&#xff08;vue-router&#xff09;&#xff0c;通过路由来实现页面的…

LCR测试仪测量电子元件的4种方法

当今电子元件的设计追求高性能&#xff0c; 而同时又致力于减少尺寸、 功耗和成本。 有效而准确的元件性能描述、设计、评估和制造过程中的测试&#xff0c;对于元件用户和生产厂家是至关重要的。电感、电容、电阻是电子线路中使用广泛的电子器件&#xff0c;在进行电子设计的基…

【图像处理OpenCV(C++版)】——4.5 全局直方图均衡化

前言&#xff1a; &#x1f60a;&#x1f60a;&#x1f60a;欢迎来到本博客&#x1f60a;&#x1f60a;&#x1f60a; &#x1f31f;&#x1f31f;&#x1f31f; 本专栏主要结合OpenCV和C来实现一些基本的图像处理算法并详细解释各参数含义&#xff0c;适用于平时学习、工作快…

Vue中路由缓存及activated与deactivated的详解

目录前言一&#xff0c;路由缓存1.1 引子1.2 路由缓存的方法1.2.1 keep-alive1.2.2 keep-alive标签中的include属性1.2.3 include中多组件的配置二&#xff0c;activated与deactivated2.1 引子2.2 介绍activated与deactivated2.3 解决需求三&#xff0c;整体代码总结前言 在Vu…

【C++】C++11语法 ~ lambda 表达式

&#x1f308;欢迎来到C专栏~~ lambda 表达式 (꒪ꇴ꒪(꒪ꇴ꒪ )&#x1f423;,我是Scort目前状态&#xff1a;大三非科班啃C中&#x1f30d;博客主页&#xff1a;张小姐的猫~江湖背景快上车&#x1f698;&#xff0c;握好方向盘跟我有一起打天下嘞&#xff01;送给自己的一句鸡…

WPF常用UI库和图标库(MahApps、HandyControl、LiveCharts)

WPF常用UI库和图表库&#xff08;MahApps、HandyControl、LiveCharts&#xff09; WPF有很多开源免费的UI库&#xff0c;本文主要介绍常见的MahApps、HandyControl两个UI库&#xff1b;在开发过程中经常会涉及到图表的开发&#xff0c;本文主要介绍LiveCharts开源图表库。 UI…

Dell Precision T7910 工作站做RAID

1&#xff1a;开机根据提示按Ctrl-C 2&#xff1a;进入下面界面直接按回车。Adapter是LSISAS3008IR的卡。 3&#xff1a;回车来到下面的界面&#xff0c;我们选择RAID Propertie回车。 4&#xff1a;回车来到选择RAID级别的界面。根据自己的硬盘数量和需求进行选择。 5&#xf…

云原生丨Prometheus+Grafana监控 OpenGauss 数据库

文章目录前言一、Prometheus的介绍及安装1、Prometheus 介绍2、Prometheus 安装二、Grafana的介绍及安装1.Grafana 介绍2、Grafana 安装三、安装探针1、安装Node Exporter探针2.安装opengauss_exporter探针四、 访问Prometheus与Grafana1、 访问Prometheus2、 访问 Grafana五、…

React 组件性能优化

React 组件性能优化1. 组件卸载前进行清理操作2. PureComponent3. shouldComponentUpdate4. React.memo5. 使用组件懒加载6. 使用 Fragment 避免额外标记7. 不要使用内联函数定义8. 在构造函数中进行函数this绑定9. 类组件中的箭头函数10. 避免使用内联样式属性11. 优化条件渲染…

记录复现一下第一次awd

前言 之前没打过awd&#xff0c;这次学长组织了一场awd娱乐赛&#xff0c;两个web一个pwn&#xff0c;还有一个黑盒&#xff0c;只会web&#xff0c;第一次啥也不会瞎打&#xff0c;被打烂了&#xff0c;不会写脚本&#xff0c;手交flag的感觉真“不错”&#xff0c;感觉awd还…

NetIQ 高级认证框架

NetIQ 高级认证框架 NetIQ Advanced Authentication 提供无密码身份验证并提升安全访问&#xff0c;以满足这个可扩展的基于标准的身份验证框架的合规要求。 优点 1、灵活性不仅仅在于方法。平台和应用程序支持至关重要。将安全范围扩展到您的所有系统。 2、通过一套适合…