Maison > interface Web > js tutoriel > le corps du texte

Informations sur le code Eslint des pipelines Bitbucket

Patricia Arquette
Libérer: 2024-09-22 08:15:03
original
552 Les gens l'ont consulté

Eslint Code Insights from Bitbucket pipelines

Ce guide explique comment intégrer les résultats ESLint dans vos requêtes d'extraction Bitbucket à l'aide de Bitbucket Pipelines. Vous apprendrez à générer des rapports ESLint au format JSON, à les publier sous forme d'annotations en ligne à l'aide de l'API Bitbucket Reports and Annotations et à configurer un pipeline Bitbucket pour exécuter automatiquement ESLint.

Générer un rapport ESLint au format JSON

Tout d'abord, vous devrez exécuter ESLint et afficher les résultats au format JSON. Ce fichier sera ensuite utilisé pour créer un rapport et des annotations.

Ajoutez les arguments -f et -o à votre commande eslint. Par exemple :

eslint . --ext .ts -f json -o eslint-report.json
Copier après la connexion

Publier le rapport ESLint et les annotations sur Bitbucket

Pour afficher les résultats d'ESLint directement dans vos demandes d'extraction, vous utiliserez l'API de rapport et l'API d'annotations de Bitbucket.

  1. Lisez le rapport ESLint JSON.
  2. Générez un rapport avec le nombre total d'erreurs et d'avertissements.
  3. Publiez des annotations en ligne basées sur les messages 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)
}
Copier après la connexion

Configurer le pipeline Bitbucket

Pour automatiser ce processus dans le cadre de votre flux de travail CI/CD, vous pouvez configurer un pipeline Bitbucket pour exécuter ESLint, générer le rapport JSON et publier les résultats. Vous trouverez ci-dessous un exemple de fichier bitbucket-pipelines.yml pour vous aider à démarrer :

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
Copier après la connexion

Note

Le rapport est publié sur Bitbucket après le script car les scripts suivants ne seront pas appelés si eslint renvoie un code de sortie différent de 0 (si ESLint contient des erreurs).

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

source:dev.to
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Derniers articles par auteur
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!