|
| 1 | +name: Auto Label Pull Requests |
| 2 | + |
| 3 | +on: |
| 4 | + pull_request_target: |
| 5 | + branches: ["main"] |
| 6 | + types: [opened, synchronize, reopened, edited] |
| 7 | + |
| 8 | +jobs: |
| 9 | + autolabeler: |
| 10 | + runs-on: ubuntu-latest |
| 11 | + permissions: |
| 12 | + pull-requests: write |
| 13 | + env: |
| 14 | + CONFIG_PATH: .github/autolabeler-config.json |
| 15 | + steps: |
| 16 | + - name: Checkout repository |
| 17 | + uses: actions/checkout@v4 |
| 18 | + |
| 19 | + - name: Install minimatch |
| 20 | + run: npm install minimatch |
| 21 | + |
| 22 | + - name: Label PR based on config rules |
| 23 | + uses: actions/github-script@v7 |
| 24 | + with: |
| 25 | + script: | |
| 26 | + const fs = require('fs').promises; |
| 27 | + const path = require('path'); |
| 28 | + const { minimatch } = require('minimatch'); |
| 29 | +
|
| 30 | + const configPath = path.resolve(process.env.CONFIG_PATH); |
| 31 | + const fileContent = await fs.readFile(configPath, 'utf-8'); |
| 32 | + const autolabelerConfig = JSON.parse(fileContent); |
| 33 | + |
| 34 | + const prNumber = context.payload.pull_request.number; |
| 35 | + const prListFilesResponse = await github.rest.pulls.listFiles({ |
| 36 | + owner: context.repo.owner, |
| 37 | + repo: context.repo.repo, |
| 38 | + pull_number: prNumber, |
| 39 | + }); |
| 40 | + const prFiles = prListFilesResponse.data; |
| 41 | + |
| 42 | + for (const [label, rules] of Object.entries(autolabelerConfig)) { |
| 43 | + const shouldAddLabel = prFiles.some((prFile) => { |
| 44 | + return rules.some((rule) => { |
| 45 | + const isFileStatusMatch = rule.fileStatus ? rule.fileStatus === prFile.status : true; |
| 46 | + const isIncludeGlobMatch = rule.includeGlobs.some((glob) => minimatch(prFile.filename, glob)); |
| 47 | + const isExcludeGlobMatch = rule.excludeGlobs.some((glob) => minimatch(prFile.filename, glob)); |
| 48 | + |
| 49 | + return isFileStatusMatch && isIncludeGlobMatch && !isExcludeGlobMatch; |
| 50 | + }); |
| 51 | + }); |
| 52 | + |
| 53 | + if (shouldAddLabel) { |
| 54 | + console.log(`Adding label ${label} to PR ${prNumber}`); |
| 55 | + await github.rest.issues.addLabels({ |
| 56 | + owner: context.repo.owner, |
| 57 | + repo: context.repo.repo, |
| 58 | + issue_number: prNumber, |
| 59 | + labels: [label], |
| 60 | + }); |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + |
| 65 | + |
0 commit comments