Rumah  >  Artikel  >  hujung hadapan web  >  Eslint Code Insights daripada saluran paip Bitbucket

Eslint Code Insights daripada saluran paip Bitbucket

Patricia Arquette
Patricia Arquetteasal
2024-09-22 08:15:03556semak imbas

Eslint Code Insights from Bitbucket pipelines

Panduan ini menerangkan cara menyepadukan hasil ESLint ke dalam Permintaan Tarik Bitbucket anda menggunakan Talian Paip Bitbucket. Anda akan belajar cara menjana laporan ESLint dalam format JSON, menyiarkannya sebagai anotasi sebaris menggunakan API Laporan dan Anotasi Bitbucket dan mengkonfigurasi saluran paip Bitbucket untuk menjalankan ESLint secara automatik.

Hasilkan Laporan ESLint sebagai JSON

Pertama, anda perlu menjalankan ESLint dan mengeluarkan hasil dalam format JSON. Fail ini kemudiannya akan digunakan untuk membuat laporan dan anotasi.

Tambah -f dan -o args pada perintah eslint anda. Cth:

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

Siarkan Laporan dan Anotasi ESLint ke Bitbucket

Untuk memaparkan penemuan ESLint terus dalam Permintaan Tarik anda, anda akan menggunakan API Laporan dan API Anotasi Bitbucket.

  1. Baca laporan ESLint JSON.
  2. Jana laporan dengan jumlah ralat dan amaran.
  3. Siarkan anotasi sebaris berdasarkan mesej 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)
}

Konfigurasi Saluran Paip Bitbucket

Untuk mengautomasikan proses ini sebagai sebahagian daripada aliran kerja CI/CD anda, anda boleh menyediakan saluran paip Bitbucket untuk menjalankan ESLint, menjana laporan JSON dan menyiarkan hasilnya. Di bawah ialah contoh fail bitbucket-pipelines.yml untuk membantu anda bermula:

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

Nota

Laporan disiarkan ke Bitbucket dalam skrip selepas kerana skrip berikutnya tidak akan dipanggil jika eslint mengembalikan kod keluar bukan 0 (jika ESLint mempunyai ralat).

Atas ialah kandungan terperinci Eslint Code Insights daripada saluran paip Bitbucket. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn