Implementing Code Quality Checks
1. Integrating SonarQube Analysis
Example: Jenkins Pipeline with SonarQube
pipeline {
agent any
stages {
stage('Checkout') {
steps {
git 'https://github.com/example/project.git'
}
}
stage('Build') {
steps {
sh 'mvn clean compile'
}
}
stage('SonarQube Analysis') {
steps {
withSonarQubeEnv('sonar-server') {
sh 'mvn sonar:sonar'
}
}
}
}
}
| Parameter | Description | Default Value |
|---|---|---|
| sonar.projectKey | Unique project identifier in SonarQube | Generated from SCM |
| sonar.sources | Source code directories to analyze | . |
| sonar.tests | Test source directories | src/test |
| sonar.java.binaries | Compiled Java classes directory | target/classes |
| sonar.java.libraries | Libraries used in project | target/lib |
Note: Ensure SonarQube Scanner is installed on Jenkins node or in Docker container.
Warning: SonarQube server must be accessible from Jenkins agent.
Integration Steps
- Install SonarQube Scanner plugin in Jenkins
- Configure SonarQube server in Jenkins global configuration
- Add
withSonarQubeEnvblock to pipeline stages - Run
mvn sonar:sonaror equivalent command
2. Using Static Code Analysis Tools
| Tool | Language Support | Key Features | Integration |
|---|---|---|---|
| SonarQube | Java, JavaScript, Python, C/C++, PHP, Go, Ruby, Swift |
Code smells, bugs, security vulnerabilities, code coverage | Plugin for Jenkins; supports SonarScanner |
| ESLint | JavaScript, TypeScript |
Code style, linting rules, best practices | npm plugin; runs as part of build pipeline |
| Checkmarx KICS | Infrastructure as Code (IaC) |
Security scanning for Terraform, Kubernetes, ARM templates | Jenkins plugin; integrates with pipeline stages |
| SpotBugs | Java |
Static analysis for bugs and security issues in bytecode | Plugin available; can be run via Maven or Gradle |
Example: Configuring ESLint in Jenkins Pipeline
pipeline {
agent any
stages {
stage('Lint JavaScript') {
steps {
sh '''npm install -g eslint
eslint src/**/*.js'''
}
}
}
}
}
Note: ESLint can be configured with
.eslintrc.json to enforce project-specific rules.
Example: Integrating SonarQube with Jenkins
pipeline {
agent any
stages {
stage('Analyze with SonarQube') {
steps {
withSonarQubeEnv('SonarQube Server') {
sh 'sonar-scanner'
}
}
}
}
}
3. Using Linting Tools
| Tool | Language | Description | Integration |
|---|---|---|---|
| ESLint | JavaScript/TypeScript | Pluggable linting utility for JavaScript and JSX | Plugin available in Jenkins |
| Stylelint | CSS/SCSS | Linting for CSS and SCSS files | Plugin available in Jenkins |
| Checkmarx KICS | Infrastructure as Code (IaC) | Static analysis for IaC files like Terraform and Kubernetes | Plugin available in Jenkins |
| SonarQube | Multiple Languages | Continuous inspection of code quality with support for 25+ languages | Plugin available in Jenkins |
Example: ESLint Configuration in Jenkins Pipeline
pipeline {
agent any
stages {
stage('Lint JavaScript') {
steps {
sh '''npm install -g eslint
eslint src/**/*.js'''
}
}
}
}
}
Note: ESLint can be integrated with Jenkins using the
eslint command-line tool or by using the ESLint plugin.
Example: Stylelint Configuration in Jenkins Pipeline
pipeline {
agent any
stages {
stage('Lint CSS') {
steps {
sh '''npm install -g stylelint
stylelint src/**/*.css'''
}
}
}
}
}
Note: Stylelint can be integrated with Jenkins using the
stylelint command-line tool or by using the Stylelint plugin.
Example: SonarQube Analysis in Jenkins Pipeline
pipeline {
agent any
stages {
stage('Analyze with SonarQube') {
steps {
withSonarQubeEnv('sonar-server') {
sh '''npm install
npm run build'''
}
}
}
}
}
}
Note: SonarQube integration requires the SonarQube plugin and a configured SonarQube server.
4. Configuring Quality Gates
| Property | Values | Description |
|---|---|---|
| quality.gate.enabled | true | false |
Enables or disables the quality gate check. |
| quality.gate.fail.build | true | false |
If set to true, the build will fail if quality gate criteria are not met. |
| quality.gate.threshold | 0.0 to 1.0 |
Minimum quality score required for build success (e.g., 0.8 = 80%). |
Example: Jenkinsfile Configuration
pipeline {
agent any
stages {
stage('Build') {
steps {
sh 'mvn clean compile'
}
}
stage('Quality Gate') {
steps {
script {
def qualityGate = waitForQualityGate()
if (qualityGate.status != 'OK') {
currentBuild.result = 'FAILURE'
}
}
}
}
}
}
Note: The
waitForQualityGate() step requires the SonarQube plugin to be installed and configured.
Warning: If
quality.gate.fail.build is set to false, the build will proceed even if quality criteria are not met.
| Quality Gate Criteria | Threshold | Impact |
|---|---|---|
| Code Coverage | >= 80% |
Build fails if coverage is below threshold |
| Bugs | < 1 |
Build fails if any bugs are detected |
| Vulnerabilities | < 1 |
Build fails if any vulnerabilities are found |
| Code Smells | < 10 |
Build fails if code smells exceed threshold |
5. Publishing Code Coverage Reports
| Property | Values | Description |
|---|---|---|
| coverageReport | jacoco.xml |
Path to the JaCoCo XML report file |
| coverageThreshold | 80% |
Minimum coverage percentage required for build success |
| failBuildOnCoverage | true |
Fail the build if coverage is below threshold |
Example: Configure JaCoCo Coverage in Jenkins Pipeline
pipeline {
agent any
stages {
stage('Build') {
steps {
sh 'mvn clean compile'
}
}
stage('Test') {
steps {
sh 'mvn test'
publishCoverage(
sourceFile: 'target/jacoco.xml',
threshold: 80,
failBuildOnCoverage: true
)
}
}
}
}
Note: JaCoCo is a popular Java code coverage library that generates XML reports for Jenkins to parse and display.
Warning: Ensure that the coverage report file path is correct and accessible in the Jenkins workspace.
| Tool | Report Format | Plugin Required | Notes |
|---|---|---|---|
Cobertura |
xml |
Cobertura Plugin |
Legacy but still supported |
JaCoCo |
xml |
JaCoCo Plugin |
Recommended for Java projects |
Codecov |
json |
Codecov Plugin |
External service integration |
6. Using Code Complexity Analysis
| Tool | Description | Integration | Configuration |
|---|---|---|---|
| PMD | Static code analysis tool for detecting code smells and complexity issues | Plugin: pmd |
|
| SonarQube | Platform for continuous inspection of code quality and complexity | Plugin: sonarqube |
|
| Checkmarx KICS | Infrastructure as Code (IaC) security and compliance scanner | Plugin: kics |
|
Example: PMD Configuration in Jenkins Pipeline
pipeline {
agent any
stages {
stage('Analyze') {
steps {
pmd(
ruleSets: ['basic', 'codesize'],
rules: [
[
name: 'CyclomaticComplexity',
max: 10
]
]
)
}
}
}
}
Note: PMD can be configured to fail the build if complexity exceeds thresholds.
Warning: SonarQube requires a running Sonar server instance to analyze code quality.
| Complexity Metric | Description | Threshold | Impact |
|---|---|---|---|
| Cyclomatic Complexity | Measures the number of linearly independent paths through a program's source code | <= 10 |
High complexity increases maintenance cost and risk of bugs |
| Halstead Metrics | Measures software complexity based on operators and operands | <= 50 |
Used to estimate effort and potential errors in code |
| NPath Complexity | Measures the number of possible execution paths through a function | <= 200 |
High NPath complexity indicates complex logic that is hard to test |
7. Implementing Security Scanning
| Tool | Description | Integration | Notes |
|---|---|---|---|
| OWASP ZAP | Open-source web application security scanner | Plugin for Jenkins | Can be run in automated mode or as a proxy |
| SonarQube | Continuous inspection of code quality and security | Jenkins plugin or standalone integration | Supports multiple languages; includes security hotspots |
| Bandit | Security linter for Python code | Jenkins Pipeline or CLI integration | Can be integrated into Jenkins pipeline stages |
| Checkmarx KICS | Infrastructure as Code (IaC) security scanner | Jenkins plugin or CLI tool | Supports Terraform, Kubernetes, Dockerfile, etc. |
Example: Integrating OWASP ZAP in Jenkins Pipeline
pipeline {
agent any
stages {
stage('Security Scan') {
steps {
sh '''# Install OWASP ZAP
curl -sL https://github.com/zaproxy/zaproxy/releases/download/v2.13.0/ZAP_2.13.0_Linux.tar.gz | tar -xzf -
# Run ZAP scan
./zap.sh -cmd -url http://localhost:8080 -addoninstall org.zaproxy.clientapi.core'''
}
}
}
}
}
Example: Using SonarQube in Jenkins Pipeline
pipeline {
agent any
stages {
stage('SonarQube Analysis') {
steps {
withSonarQubeEnv('sonar-server') {
sh 'sonar-scanner'
}
}
}
}
}
Note: Security scanning should be part of the CI/CD pipeline to ensure that code changes do not introduce vulnerabilities.
Warning: Ensure that security scans do not block the pipeline unless critical issues are found.
8. Using Dependency Scanning
| Tool | Description | Integration | Notes |
|---|---|---|---|
| OWASP Dependency-Check | Scans project dependencies for known vulnerabilities | Jenkins plugin available | Can be integrated into build pipeline with dependencyCheck step |
| Snyk | Scans dependencies for security issues and provides remediation | Jenkins plugin or CLI integration | Supports multiple languages including Node.js, Python, Java |
| SonarQube | Static analysis for code quality and security vulnerabilities | Jenkins plugin or standalone integration | Can analyze dependencies and code together in one pipeline |
Example: OWASP Dependency-Check in Jenkins Pipeline
pipeline {
agent any
stages {
stage('Scan Dependencies') {
steps {
dependencyCheck additionalArguments: '--scan .',
tool: 'OWASP-Dependency-Check'
}
}
}
}
Note: OWASP Dependency-Check requires a local database of vulnerabilities to be updated regularly for best results.
Warning: Some dependency scanners may report false positives. Always verify findings before taking action.
9. Configuring Quality Thresholds
| Threshold Type | Configuration Parameter | Description | Default Value |
|---|---|---|---|
| Code Coverage | coverage.threshold |
Minimum code coverage percentage required | 80% |
| Build Stability | build.stability.threshold |
Maximum allowed build failures before failing the build | 0 |
| Test Failures | test.failure.threshold |
Maximum number of test failures before build fails | 0 |
| Violations | violations.threshold |
Maximum number of code violations before build fails | 0 |
Example: Jenkinsfile Configuration
pipeline {
agent any
stages {
stage('Build') {
steps {
sh 'mvn clean compile'
}
}
stage('Quality Check') {
steps {
checkstyle tool: 'Checkstyle', pattern: '**/checkstyle-result.xml'
pmd tool: 'PMD', pattern: '**/pmd.xml'
cobertura coberturaReportFile: 'coverage.xml'
}
post {
always {
checkQualityThresholds(
coverageThreshold: 85,
buildStabilityThreshold: 1,
testFailureThreshold: 5,
violationsThreshold: 10
)
}
}
}
}
}
Note: Thresholds can be configured via Jenkins UI or through pipeline scripts. Adjust thresholds based on project requirements and team standards.
10. Using Quality Trend Reports
| Report Type | Description | Configuration | Notes |
|---|---|---|---|
| Quality Trend Report | Summarizes code quality metrics over time | quality.trend.report.enabled=true |
Available in Jenkins 2.307+ |
| Code Coverage Trend | Tracks coverage percentage changes | coverage.trend.enabled=true |
Requires JaCoCo plugin |
| Technical Debt | Measures accumulated technical debt | technical.debt.report.enabled=true |
Requires SonarQube plugin |
Example: Configuring Quality Trend Report
pipeline {
agent any
stages {
stage('Build') {
steps {
sh 'mvn clean compile'
}
}
stage('Quality Checks') {
steps {
sh 'mvn checkstyle:check'
sh 'mvn pmd:check'
}
}
stage('Report Generation') {
steps {
publishQualityTrendReport(
reportType: 'quality',
enabled: true
)
}
}
}
}
Note: Quality Trend Reports are generated by plugins like Checkstyle, PMD, and SonarQube. Ensure these plugins are installed and configured correctly.
Warning: If the Quality Trend Report is not enabled in Jenkins, it will not collect or display historical data for code quality metrics.