SonarCloud Cheat Sheet
Überblick
SonarCloud ist eine Cloud-basierte Code-Qualität und Sicherheitsanalyse-Plattform, die automatisch den Code für Bugs, Schwachstellen und Codegerüche überprüft. Es integriert sich nahtlos mit CI/CD-Pipelines und bietet detaillierte Einblicke, um hohe Codequalitätsstandards zu erhalten.
ZEIT Note: Kostenlos für öffentliche Repositories. Private Repositories benötigen bezahlte Pläne ab $10/Monat.
Erste Schritte
Kontoaufbau
```bash
Sign up options:
- GitHub account (recommended)
- Bitbucket account
- Azure DevOps account
- GitLab account
Visit: https://sonarcloud.io
Click "Log in" and choose your Git provider
```_
Organisation Setup
```bash
Create organization:
1. After login, click "Create Organization"
2. Choose Git provider
3. Select organization/account
4. Configure organization settings
5. Import repositories
```_
Projektimport
```bash
Import from GitHub:
1. Organizations > Your Org > Analyze new project
2. Select repositories to import
3. Configure project settings
4. Set up analysis method
Manual project creation:
1. Create project manually
2. Generate project token
3. Configure analysis locally
```_
CLI Installation
SonarScanner CLI
```bash
Download and install SonarScanner
Linux/macOS
wget https://binaries.sonarsource.com/Distribution/sonar-scanner-cli/sonar-scanner-cli-4.8.0.2856-linux.zip unzip sonar-scanner-cli-4.8.0.2856-linux.zip export PATH=$PATH:/path/to/sonar-scanner-4.8.0.2856-linux/bin
macOS with Homebrew
brew install sonar-scanner
Windows
Download from https://docs.sonarqube.org/latest/analysis/scan/sonarscanner/
Add to PATH environment variable
```_
Docker Scanner
```bash
Run analysis with Docker
docker run \ --rm \ -e SONAR_HOST_URL="https://sonarcloud.io" \ -e SONAR_LOGIN="your-token" \ -v "${PWD}:/usr/src" \ sonarsource/sonar-scanner-cli ```_
Projektkonfiguration
sonar-project.properties
```properties
Basic project configuration
sonar.projectKey=my-org_my-project sonar.organization=my-org sonar.projectName=My Project sonar.projectVersion=1.0
Source code settings
sonar.sources=src sonar.tests=tests sonar.sourceEncoding=UTF-8
Language-specific settings
sonar.java.source=11 sonar.java.target=11 sonar.java.binaries=target/classes
Exclusions
sonar.exclusions=/test/,/*.spec.ts,/node_modules/ sonar.test.exclusions=/test/**
Coverage reports
sonar.javascript.lcov.reportPaths=coverage/lcov.info sonar.java.coveragePlugin=jacoco sonar.jacoco.reportPaths=target/jacoco.exec ```_
Sprach-spezifische Konfiguration
```properties
JavaScript/TypeScript
sonar.typescript.lcov.reportPaths=coverage/lcov.info sonar.javascript.environments=node,browser,jest
Python
sonar.python.coverage.reportPaths=coverage.xml sonar.python.xunit.reportPath=test-reports/xunit.xml
C#/.NET
sonar.cs.opencover.reportsPaths=coverage.opencover.xml sonar.cs.nunit.reportsPaths=TestResults.xml
Go
sonar.go.coverage.reportPaths=coverage.out
PHP
sonar.php.coverage.reportPaths=coverage.xml sonar.php.tests.reportPath=test-reports/phpunit.xml ```_
CI/CD Integration
GitHub Aktionen
```yaml
.github/workflows/sonarcloud.yml
name: SonarCloud Analysis
on: push: branches: [ main, develop ] pull_request: branches: [ main ]
jobs: sonarcloud: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 with: fetch-depth: 0 # Shallow clones should be disabled
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: '18'
- name: Install dependencies
run: npm ci
- name: Run tests with coverage
run: npm run test:coverage
- name: SonarCloud Scan
uses: SonarSource/sonarcloud-github-action@master
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
```_
GitLab CI
```yaml
.gitlab-ci.yml
sonarcloud-check: image: name: sonarsource/sonar-scanner-cli:latest entrypoint: [""] variables: SONAR_USER_HOME: "${CI_PROJECT_DIR}/.sonar" GIT_DEPTH: "0" cache: key: "${CI_JOB_NAME}" paths: - .sonar/cache script: - sonar-scanner only: - merge_requests - master - develop ```_
Azure DevOs
```yaml
azure-pipelines.yml
trigger: - main
pool: vmImage: 'ubuntu-latest'
steps: - task: SonarCloudPrepare@1 inputs: SonarCloud: 'SonarCloud' organization: 'your-org' scannerMode: 'CLI' configMode: 'file'
-
task: NodeTool@0 inputs: versionSpec: '18.x'
-
script: | npm ci npm run test:coverage displayName: 'Install dependencies and run tests'
-
task: SonarCloudAnalyze@1
-
task: SonarCloudPublish@1 inputs: pollingTimeoutSec: '300' ```_
Jenkins Pipeline
```groovy pipeline { agent any
environment {
SONAR_TOKEN = credentials('sonar-token')
}
stages {
stage('Checkout') {
steps {
checkout scm
}
}
stage('Test') {
steps {
sh 'npm ci'
sh 'npm run test:coverage'
}
}
stage('SonarCloud Analysis') {
steps {
withSonarQubeEnv('SonarCloud') {
sh 'sonar-scanner'
}
}
}
stage('Quality Gate') {
steps {
timeout(time: 1, unit: 'HOURS') {
waitForQualityGate abortPipeline: true
}
}
}
}
} ```_
Analysekommandos
Basisanalyse
```bash
Run analysis with CLI
sonar-scanner \ -Dsonar.projectKey=my-project \ -Dsonar.organization=my-org \ -Dsonar.sources=. \ -Dsonar.host.url=https://sonarcloud.io \ -Dsonar.login=your-token
Analysis with coverage
sonar-scanner \ -Dsonar.projectKey=my-project \ -Dsonar.organization=my-org \ -Dsonar.sources=src \ -Dsonar.tests=tests \ -Dsonar.javascript.lcov.reportPaths=coverage/lcov.info \ -Dsonar.host.url=https://sonarcloud.io \ -Dsonar.login=your-token ```_
Sprachspezifische Analyse
```bash
Java with Maven
mvn clean verify sonar:sonar \ -Dsonar.projectKey=my-project \ -Dsonar.organization=my-org \ -Dsonar.host.url=https://sonarcloud.io \ -Dsonar.login=your-token
.NET with dotnet
dotnet sonarscanner begin \ /k:"my-project" \ /o:"my-org" \ /d:sonar.host.url="https://sonarcloud.io" \ /d:sonar.login="your-token" dotnet build dotnet test --collect:"XPlat Code Coverage" dotnet sonarscanner end /d:sonar.login="your-token"
Python with coverage
coverage run -m pytest coverage xml sonar-scanner \ -Dsonar.projectKey=my-project \ -Dsonar.python.coverage.reportPaths=coverage.xml ```_
Qualitätstore
Standardqualität Tor
```bash
Default conditions:
- Coverage on New Code >= 80%
- Duplicated Lines on New Code <= 3%
- Maintainability Rating on New Code = A
- Reliability Rating on New Code = A
- Security Rating on New Code = A
- Security Hotspots Reviewed on New Code >= 100%
```_
Zollqualität Tor
```bash
Create custom quality gate:
1. Administration > Quality Gates
2. Create new quality gate
3. Add conditions:
- Coverage > 85%
- Bugs = 0
- Vulnerabilities = 0
- Code Smells <= 10
- Duplicated Lines <= 5%
4. Set as default or assign to projects
```_
Status des Tores
```bash
Check quality gate status via API
curl -u your-token: \ "https://sonarcloud.io/api/qualitygates/project_status?projectKey=my-project"
Response example:
{ "projectStatus": { "status": "OK", "conditions": [ { "status": "OK", "metricKey": "new_coverage", "comparator": "LT", "errorThreshold": "80" } ] } } ```_
Sicherheitsanalyse
Sicherheit Hotspots
```bash
Security hotspot categories:
- SQL Injection
- Cross-Site Scripting (XSS)
- Command Injection
- Path Traversal
- LDAP Injection
- Weak Cryptography
- Authentication Issues
```_
Schwachstellenerkennung
```javascript // Example: Detected vulnerability function getUserData(userId) { // SonarCloud detects SQL injection risk const query = "SELECT * FROM users WHERE id = " + userId; return database.execute(query); }
// Recommended fix: function getUserData(userId) { const query = "SELECT * FROM users WHERE id = ?"; return database.execute(query, [userId]); } ```_
Sicherheitsregeln Konfiguration
```bash
Configure security rules:
1. Project > Administration > Quality Profiles
2. Select language profile
3. Enable/disable security rules
4. Set rule severity levels
5. Add custom rules if needed
```_
Code Coverage
JavaScript/TypScript Deckung
json
// package.json
{
"scripts": {
"test": "jest",
"test:coverage": "jest --coverage"
},
"jest": {
"collectCoverageFrom": [
"src/**/*.{js,jsx,ts,tsx}",
"!src/**/*.d.ts",
"!src/index.tsx"
],
"coverageReporters": ["lcov", "text"]
}
}
_
Java Coverage mit JaCoCo
```xml
Python Coverage
```bash
Install coverage
pip install coverage
Run tests with coverage
coverage run -m pytest coverage xml
Configuration in .coveragerc
[run] source = src omit = /tests/ /venv/ setup.py
[report] exclude_lines = pragma: no cover def repr raise AssertionError ```_
API Verwendung
REST API Authentication
```bash
Generate user token:
Account > Security > Generate Tokens
API authentication
curl -u your-token: \ "https://sonarcloud.io/api/projects/search?organization=my-org" ```_
Projekt Metriken
```bash
Get project metrics
curl -u your-token: \ "https://sonarcloud.io/api/measures/component?component=my-project&metricKeys;=bugs,vulnerabilities,code_smells,coverage,duplicated_lines_density"
Get quality gate status
curl -u your-token: \ "https://sonarcloud.io/api/qualitygates/project_status?projectKey=my-project"
Get issues
curl -u your-token: \ "https://sonarcloud.io/api/issues/search?componentKeys=my-project&types;=BUG,VULNERABILITY" ```_
Webhook Konfiguration
json
// Webhook payload example
{
"serverUrl": "https://sonarcloud.io",
"taskId": "task-id",
"status": "SUCCESS",
"analysedAt": "2024-01-15T10:30:00+0000",
"project": {
"key": "my-project",
"name": "My Project"
},
"qualityGate": {
"name": "Sonar way",
"status": "OK"
}
}
_
Analyse der Nachfrage
Integration von GitHub
```bash
Automatic PR analysis:
1. Install SonarCloud GitHub App
2. Configure repository permissions
3. Enable PR decoration
4. Analysis runs on every PR
PR comment example:
Quality Gate passed
0 Bugs
0 Vulnerabilities
0 Security Hotspots
2 Code Smells
Coverage: 85.2% (+2.1%)
```_
Messtechnik
```bash
Analyze specific branch
sonar-scanner \ -Dsonar.projectKey=my-project \ -Dsonar.branch.name=feature/new-feature \ -Dsonar.login=your-token
Compare branches
SonarCloud automatically compares:
- New code vs. overall code
- Feature branch vs. main branch
- Short-lived vs. long-lived branches
```_
Erweiterte Konfiguration
Zollvorschriften
```xml
Qualitätsprofile
```bash
Create custom quality profile:
1. Quality Profiles > Create
2. Select language and parent profile
3. Activate/deactivate rules
4. Set rule parameters
5. Assign to projects
```_
Projekteinstellungen
```properties
Advanced project settings
sonar.projectDescription=Project description sonar.links.homepage=https://example.com sonar.links.ci=https://ci.example.com sonar.links.scm=https://github.com/org/repo sonar.links.issue=https://github.com/org/repo/issues
Analysis scope
sonar.inclusions=/*.js,/.jsx,/.ts,/*.tsx sonar.exclusions=/node_modules/,/dist/,/.min.js sonar.test.inclusions=/.test.js,/*.spec.js sonar.coverage.exclusions=/.test.js,/.config.js ```_
Fehlerbehebung
Gemeinsame Themen
```bash
Analysis fails with "Project not found":
1. Check project key spelling
2. Verify organization name
3. Ensure project exists in SonarCloud
4. Check token permissions
Coverage not showing:
1. Verify coverage report path
2. Check report format compatibility
3. Ensure tests run before analysis
4. Validate coverage configuration
```_
Analyse der Schulden
```bash
Enable debug logging
sonar-scanner -Dsonar.verbose=true
Check analysis logs
SonarCloud > Project > Activity > View Details
Validate configuration
sonar-scanner -Dsonar.scanner.dumpToFile=sonar-scanner-dump.properties ```_
Leistungsoptimierung
```bash
Optimize analysis performance:
1. Exclude unnecessary files
2. Use incremental analysis
3. Optimize test coverage collection
4. Configure appropriate heap size
JVM options for large projects
export SONAR_SCANNER_OPTS="-Xmx2048m" ```_
Best Practices
Code Qualitätsstandards
```bash
Maintain quality standards:
- Zero tolerance for bugs and vulnerabilities
- Minimum 80% code coverage
- Maximum 5% code duplication
- Regular technical debt reduction
- Consistent coding standards
```_
Team Adoption
```bash
Successful team adoption:
1. Set clear quality gates
2. Integrate with development workflow
3. Provide training on fixing issues
4. Regular code quality reviews
5. Celebrate quality improvements
```_
kontinuierliche Verbesserung
```bash
Quality improvement process:
1. Monitor quality trends
2. Identify recurring issues
3. Update coding standards
4. Refine quality gates
5. Share best practices
```_
Ressourcen
Dokumentation
- SonarCloud Dokumentation
- Analyseparameter
- (LINK_9)
Gemeinschaft
- [SonarSource Community](_LINK_9__ -%20(LINK_9)
- Stack Overflow
Ausbildung
- SonarCloud Academy
- [Klean-Code-Leitlinien](__LINK_9 -%20(_LINK_9_)