コンテンツにスキップ

SonarCloudチートシート

## 概要

SonarCloudは、バグ、脆弱性、コードスメルを自動的にレビューするクラウドベースのコード品質およびセキュリティ分析プラットフォームです。CI/CDパイプラインとシームレスに統合され、高いコード品質基準を維持するための詳細な洞察を提供します。

⚠️ 注意: パブリックリポジトリは無料。プライベートリポジトリは月額10ドルから始まる有料プランが必要です。

はじめに

アカウント設定

組織設定

プロジェクトのインポート

CLIのインストール

SonarScanner CLI

Dockerスキャナー

プロジェクト設定

sonar-project.properties

言語固有の設定

CI/CD統合

GitHub Actions

GitLab CI

Azure DevOps

Jenkinsパイプライン

分析コマンド

基本分析

言語固有の分析

品質ゲート

デフォルトの品質ゲート

カスタム品質ゲート

品質ゲートのステータス

セキュリティ分析

セキュリティホットスポット

脆弱性検出

セキュリティルールの設定

Would you like me to fill in more specific details for each section? I can provide more context and specific translations if needed.```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


### Organization 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

Project Import

# 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

# 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

# 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

Project Configuration

sonar-project.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

Language-Specific Configuration

# 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 Actions

# .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

# .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 DevOps

# 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

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
                }
            }
        }
    }
}

Analysis Commands

Basic Analysis

# 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

Language-Specific Analysis

# 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

Quality Gates

Default Quality Gate

# 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%

Custom Quality Gate

# 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

Quality Gate Status

# 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"
      }
    ]
  }
}

Security Analysis

Security Hotspots

# Security hotspot categories:
# - SQL Injection
# - Cross-Site Scripting (XSS)
# - Command Injection
# - Path Traversal
# - LDAP Injection
# - Weak Cryptography
# - Authentication Issues

Vulnerability Detection

// 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]);
}

Security Rules Configuration

# 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
```## コード・カバレッジ
```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"]
  }
}
```### JaCoCo による Java カバレッジ
```xml
<!-- pom.xml -->
<plugin>
    <groupId>org.jacoco</groupId>
    <artifactId>jacoco-maven-plugin</artifactId>
    <version>0.8.8</version>
    <executions>
        <execution>
            <goals>
                <goal>prepare-agent</goal>
            </goals>
        </execution>
        <execution>
            <id>report</id>
            <phase>test</phase>
            <goals>
                <goal>report</goal>
            </goals>
        </execution>
    </executions>
</plugin>
```### Python カバレッジ
```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 使用法
```bash
# Generate user token:
# Account > Security > Generate Tokens

# API authentication
curl -u your-token: \
  "https://sonarcloud.io/api/projects/search?organization=my-org"
```### REST API 認証
```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"
```### プロジェクト指標
```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"
  }
}
```### Webhook 設定
```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%)
```## プルリクエスト分析
```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
```### GitHub 連携
```xml
<!-- Custom rule template -->
<rule>
    <key>custom-rule-key</key>
    <name>Custom Rule Name</name>
    <description>Rule description</description>
    <severity>MAJOR</severity>
    <type>CODE_SMELL</type>
    <tag>custom</tag>
</rule>
```### ブランチ分析
```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
```## 詳細設定
```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
```### カスタムルール
```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
```### 品質プロファイル
```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
```### プロジェクト設定
```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"
```## トラブルシューティング
```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
```### 一般的な問題
```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
```### デバッグ分析
```bash
# Quality improvement process:
# 1. Monitor quality trends
# 2. Identify recurring issues
# 3. Update coding standards
# 4. Refine quality gates
# 5. Share best practices
```### パフォーマンス最適化
https://docs.sonarcloud.io/#

# ベストプラクティス
https://docs.sonarqube.org/latest/analysis/analysis-parameters/##

# コード品質基準
https://docs.sonarcloud.io/improving/quality-gates/##

# コミュニティhttps://community.sonarsource.com/- [SonarSourceコミュニティ](https://github.com/SonarSource/sonarcloud-github-action/issues- [GitHubイシュー](https://stackoverflow.com/questions/tagged/sonarcloud- [Stack Overflow](
https://academy.sonarsource.com/##

# トレーニングhttps://docs.sonarqube.org/latest/user-guide/clean-code/- [SonarCloud アカデミー](https://rules.sonarsource.com/- [クリーンコードガイドライン](