name: Auto Label Pull Requests on: pull_request_target: branches: ["main"] types: [opened, synchronize, reopened, edited] jobs: autolabeler: runs-on: ubuntu-latest permissions: pull-requests: write env: CONFIG_PATH: .github/autolabeler-config.json steps: - name: Label PR based on config rules uses: actions/github-script@v7 with: script: | const fs = require('fs').promises; const { minimatch } = require('minimatch'); const configPath = process.env.CONFIG_PATH; let config; try { const fileContent = await fs.readFile(configPath, 'utf-8'); config = JSON.parse(fileContent); } catch (error) { console.error(`❌ Issue while load config file: ${error.message}`); return; } const prNumber = context.payload.pull_request.number; const prFiles = (await github.rest.pulls.listFiles({ owner: context.repo.owner, repo: context.repo.repo, pull_number: prNumber, })).data; let labelsToAdd = new Set(); for (const [label, rules] of Object.entries(config)) { if (prFiles.some(prFile => rules.some(rule => (!rule.fileStatus || rule.fileStatus === prFile.status) && rule.includeGlobs.some(glob => minimatch(prFile.filename, glob)) && !rule.excludeGlobs.some(glob => minimatch(prFile.filename, glob)) ) )) { labelsToAdd.add(label); } } const existingLabels = new Set((await github.rest.issues.listLabelsOnIssue({ owner: context.repo.owner, repo: context.repo.repo, issue_number: prNumber, })).data.map(l => l.name)); labelsToAdd = [...labelsToAdd].filter(label => !existingLabels.has(label)); if (labelsToAdd.length > 0) { await github.rest.issues.addLabels({ owner: context.repo.owner, repo: context.repo.repo, issue_number: prNumber, labels: labelsToAdd, }); }