>  기사  >  웹 프론트엔드  >  Bitbucket 파이프라인의 Eslint Code Insights

Bitbucket 파이프라인의 Eslint Code Insights

Patricia Arquette
Patricia Arquette원래의
2024-09-22 08:15:03556검색

Eslint Code Insights from Bitbucket pipelines

이 가이드에서는 Bitbucket 파이프라인을 사용하여 ESLint 결과를 Bitbucket Pull Request에 통합하는 방법을 설명합니다. JSON 형식으로 ESLint 보고서를 생성하고, Bitbucket 보고서 및 주석 API를 사용하여 이를 인라인 주석으로 게시하고, ESLint를 자동으로 실행하도록 Bitbucket 파이프라인을 구성하는 방법을 알아봅니다.

ESLint 보고서를 JSON으로 생성

먼저 ESLint를 실행하고 결과를 JSON 형식으로 출력해야 합니다. 이 파일은 나중에 보고서와 주석을 만드는 데 사용됩니다.

eslint 명령에 -f 및 -o args를 추가하세요. 예:

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

Bitbucket에 ESLint 보고서 및 주석 게시

ESLint 결과를 끌어오기 요청에 직접 표시하려면 Bitbucket의 Report API 및 Annotations 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 Code Insights의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.