From 9f8775671dd8cc84aface34abdef2d83bfde432a Mon Sep 17 00:00:00 2001 From: Petri Lehtinen Date: Tue, 5 Nov 2024 08:45:23 +0200 Subject: [PATCH] Add a CI workflow that validates PR labels --- .github/workflows/validate-labels.yml | 21 +++++++++++ bin/validate-labels.js | 54 +++++++++++++++++++++++++++ 2 files changed, 75 insertions(+) create mode 100644 .github/workflows/validate-labels.yml create mode 100755 bin/validate-labels.js diff --git a/.github/workflows/validate-labels.yml b/.github/workflows/validate-labels.yml new file mode 100644 index 00000000000..9a84310299a --- /dev/null +++ b/.github/workflows/validate-labels.yml @@ -0,0 +1,21 @@ +# SPDX-FileCopyrightText: 2017-2024 City of Espoo +# +# SPDX-License-Identifier: LGPL-2.1-or-later + +name: 'Validate PR labels' +on: + pull_request: + types: + - labeled + - unlabeled + - opened + - reopened + - ready_for_review + +jobs: + validate-labels: + if: ${{ github.event.pull_request.state == 'open' && !github.event.pull_request.draft }} + runs-on: ubuntu-latest + steps: + - run: | + echo '${{ toJSON(github.event.pull_request.labels[*].name) }}' | bin/validate-labels.js diff --git a/bin/validate-labels.js b/bin/validate-labels.js new file mode 100755 index 00000000000..70030559e4b --- /dev/null +++ b/bin/validate-labels.js @@ -0,0 +1,54 @@ +#!/usr/bin/env node + +// SPDX-FileCopyrightText: 2017-2024 City of Espoo +// +// SPDX-License-Identifier: LGPL-2.1-or-later + +// Usage: +// +// echo '["foo", "bar"]' | bin/check-labels.js +// + +function main() { + let inputData = '' + + const stdin = process.stdin; + stdin.setEncoding('utf-8') + stdin.on('data', (data) => { + inputData += data + }); + + stdin.on('end', () => { + let json + try { + json = JSON.parse(inputData); + } catch (error) { + console.error('An error occurred while parsing JSON:', error.message); + process.exit(1); + } + if (!validateLabels(json)) { + console.error('Each pull request must have exactly one of the following labels:', knownLabels.join(', ')); + process.exit(1); + } + }); +} + +const knownLabels = [ + 'no-changelog', + 'breaking', + 'enhancement', + 'bug', + 'unknown', + 'tech', + 'dependencies' +]; + +function validateLabels(labels) { + const numKnownLabels = labels.reduce( + (acc, label) => (knownLabels.includes(label)) ? acc + 1 : acc, + 0 + ); + return numKnownLabels === 1; +} + +main();