ホームページ  >  記事  >  ウェブフロントエンド  >  Bitbucket パイプラインからの Eslint コード インサイト

Bitbucket パイプラインからの Eslint コード インサイト

Patricia Arquette
Patricia Arquetteオリジナル
2024-09-22 08:15:03554ブラウズ

Eslint Code Insights from Bitbucket pipelines

このガイドでは、Bitbucket Pipelines を使用して ESLint の結果を Bitbucket プル リクエストに統合する方法について説明します。 ESLint レポートを JSON 形式で生成し、Bitbucket Reports and Annotations API を使用してインライン注釈として投稿し、ESLint を自動的に実行するように Bitbucket パイプラインを構成する方法を学びます。

ESLint レポートを JSON として生成

まず、ESLint を実行し、結果を JSON 形式で出力する必要があります。このファイルは、後でレポートと注釈を作成するために使用されます。

eslint コマンドに -f 引数と -o 引数を追加します。例:

eslint . --ext .ts -f json -o eslint-report.json

ESLint レポートと注釈を Bitbucket に投稿する

ESLint の結果をプル リクエストに直接表示するには、Bitbucket のレポート API と注釈 API を使用します。

  1. ESLint JSON レポートを読んでください。
  2. エラーと警告の合計数を含むレポートを生成します。
  3. ESLint メッセージに基づいてインライン注釈を投稿します。
const fs = require('fs')
const path = require('path')
const util = require('util')

// External ID must be unique per report on a commit
const EXTERNAL_ID = 'com.yorcompany.reports.eslint'
const BB_USER = 'YOUR_USER'
const BB_REPO = 'YOUR_REPO'
const BB_URL = 'https://api.bitbucket.org/2.0'
// This is available by default in the pipeline.
const COMMIT = process.env.BITBUCKET_COMMIT
// For this to be availble you need to create an access token with read access to the repo
//  and set it an environment variable in the pipeline.
const TOKEN = process.env.BITBUCKET_TOKEN

// Map ESLint severities to Bitbucket report severities
const severities = {
    0: 'LOW',
    1: 'MEDIUM',
    2: 'HIGH'
}

// Read the ESLint JSON report
const data = await util.promisify(fs.readFile)(path.join(process.cwd(), 'eslint-report.json'), 'utf8')
    .catch(err => {
        console.error('Error reading eslint-report.json:', err)
        throw err
    })

const eslintOutput = JSON.parse(data)
let totalErrorCount = 0
let totalWarningCount = 0
const annotations = []
let i = 1

eslintOutput.forEach(file => {
    totalErrorCount += file.errorCount
    totalWarningCount += file.warningCount

    const relativePath = path.relative(process.cwd(), file.filePath)

    file.messages.forEach(message => {
        annotations.push({
            external_id: `${EXTERNAL_ID}.${COMMIT}.${i++}`,
            path: relativePath,
            annotation_type: 'CODE_SMELL',
            summary: message.message,
            line: message.line,
            severity: severities[message.severity]
        })
    })
})

// Prepare the report
const report = {
    title: 'ESLint Report',
    details: 'Results from ESLint analysis',
    report_type: 'TEST',
    logoUrl: 'https://eslint.org/img/logo.svg',
    data: [
        {
            title: 'Error Count',
            type: 'NUMBER',
            value: totalErrorCount
        },
        {
            title: 'Warning Count',
            type: 'NUMBER',
            value: totalWarningCount
        }
    ]
}

try {
    // Post the report to Bitbucket
    const reportUrl = `${BB_URL}/repositories/${BB_USER}/${BB_REPO}/commit/${COMMIT}/reports/${EXTERNAL_ID}`
    let response = await fetch(reportUrl, {
        method: 'PUT',
        body: JSON.stringify(report),
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            'Authorization': `Bearer ${TOKEN}`
        }
    })

    if (!response.ok) {
        console.error(await response.text())
        throw new Error(`Error posting report: ${response.statusText}`)
    }

    console.log('Report posted successfully!')
    console.log(await response.json())

    // Post annotations if any
    if (annotations.length > 0) {
        const annotationsUrl = `${BB_URL}/repositories/${BB_USER}/${BB_REPO}/commit/${COMMIT}/reports/${EXTERNAL_ID}/annotations`
        response = await fetch(annotationsUrl, {
            method: 'POST',
            body: JSON.stringify(annotations),
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json',
                'Authorization': `Bearer ${TOKEN}`
            }
        })

        if (!response.ok) {
            console.error(await response.text())
            throw new Error(`Error posting annotations: ${response.statusText}`)
        }

        console.log('Annotations posted successfully!')
        console.log(await response.json())
    }

} catch (error) {
    console.error('Error posting insights:', error.response ? error.response.data : error.message)
}

Bitbucket パイプラインを構成する

CI/CD ワークフローの一部としてこのプロセスを自動化するには、ESLint を実行し、JSON レポートを生成し、結果を投稿するように Bitbucket パイプラインを設定します。以下は、開始するためのサンプル bitbucket-pipelines.yml ファイルです:

image: node:18.13.0

pipelines:
  default:
    - step:
        name: ESLint
        caches:
          - node
        script:
          - npm install
          - npx eslint . --ext .ts -f json -o eslint-report.json  # Run ESLint and save the report
        after-script:
          - node post-eslint-results.js  # Post results to Bitbucket
        artifacts:
          - eslint-report.json

注記

eslint が 0 以外の終了コードを返した場合 (ESLint にエラーがある場合)、後続のスクリプトは呼び出されないため、レポートはアフタースクリプトで Bitbucket に投稿されます。

以上がBitbucket パイプラインからの Eslint コード インサイトの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。