1. 授权认证
  2. 获取用户个人信息
  3. 项目协同
  4. 代码托管
  5. 持续集成
  6. 制品仓库
  7. 测试管理
  1. 项目协同
  2. 代码仓库
  3. DevOps 实践之旅
  4. 一分钟开始持续集成之旅
  5. 持续部署
  6. 制品库

Java 代码规范

文章内容
  1. Checkstyle

Java 常用代码规范检查工具如下:

工具 lint 命令 支持 IDE
Checkstyle ./gradlew check VSCodeIDEA
PMD pmd -d src -R rulesets.xml VSCode

Checkstyle

Checkstyle 内置 2 种规范——Google 与 Sun,其中常用的「Google Java Style」规范包括下列规则:

  • 每行代码最大长度 100 个字符;
  • 缩进使用 2 个空格;

安装:

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

全量检查:

$ ./gradlew check

[WARN] TaskTest.java:543: 本行字符数 101个,最多:100个。 [LineLength]
[WARN] ReportTest.java:206:9: 第 9 个字符 '}'应该与下一部分位于同一行。
[WARN] ProjectRoleTest.java:449:8: 注释应缩进8个缩进符,而不是7个。

增量检查:

修改 build.gradle,代码:

plugins {
    id 'checkstyle'
}
checkstyle {
    toolVersion = '8.34'
    maxWarnings = 0
    maxErrors = 0
}

task checkstyleChanged(type: Checkstyle) {
    source "${project.rootDir}"
    def changedFiles = getChangedFiles()
    if (changedFiles) {
        // include changed files only
        include changedFiles
    } else {
        // if no changed Java files detected, exclude all
        exclude "**/*"
    }
    classpath = files()
    showViolations = true

    // Define the output folder for the generated reports
    def reportsPath = "${buildDir}/reports/checkstyle"
    reports {
        html.enabled true
        html.destination rootProject.file("${reportsPath}/changed-files.html")

        xml.enabled true
        xml.destination rootProject.file("${reportsPath}/changed-files.xml")
    }
}

static def getChangedFiles() {
    ByteArrayOutputStream systemOutStream = new ByteArrayOutputStream()
    def diffFile = ''
    def files = []

    try {
        diffFile = new FileInputStream(".diff").getText();
    } catch (FileNotFoundException e) {
        ("git diff --name-only --diff-filter=d HEAD").execute().waitForProcessOutput(systemOutStream, System.err)
        diffFile = systemOutStream.toString()
        systemOutStream.close()
    }

    // Collect only *.java-files from all changed files
    for (file in diffFile.trim().split('\n')) {
        if (file.endsWith(".java")) {
            files.add(file)
        }
    }
    return files
}

本地增量检查:

./gradlew checkstyleChanged

持续集成合并请求增量检查:

pipeline {
  agent any
  stages {
    stage('检出') {
      steps {
        checkout([
          $class: 'GitSCM',
          branches: [[name: '*']],
          userRemoteConfigs: [[url: env.GIT_REPO_URL, credentialsId: env.CREDENTIALS_ID]]
        ])
        script {
          sh 'touch .diff'
          if (env.MR_SOURCE_BRANCH ==~ /.*/) {
            sh "git checkout ${env.MR_TARGET_BRANCH}"
            sh "git checkout ${env.MR_SOURCE_BRANCH}"
            sh "git diff --diff-filter=d --name-only ${env.MR_TARGET_BRANCH}... > .diff"
          } else {
            sh "git checkout ${env.GIT_COMMIT}"
          }
        }
      }
    }
    stage('增量检查代码规范') {
      when {
        expression { env.MR_SOURCE_BRANCH ==~ /.*/ }
      }
      agent {
        docker {
          image 'openjdk:14-jdk-alpine'
          args '-v /root/.gradle/:/root/.gradle/ -v /root/.m2/:/root/.m2/'
          reuseNode true
        }
      }
      steps {
        sh './gradlew checkstyleChanged'
      }
    }
  }
}

上一篇PHP 代码规范
最近更新
感谢反馈有用
感谢反馈没用