|
| 1 | +#!/usr/bin/env node |
| 2 | +/** |
| 3 | + * Lint .github/workflows/*.yml — every `uses:` line MUST pin to a |
| 4 | + * 40-char commit SHA, with an optional trailing comment. |
| 5 | + * |
| 6 | + * Exit codes: |
| 7 | + * 0 all uses: lines pinned (or no non-local uses: lines found) |
| 8 | + * 1 one or more lines fail the pin regex (prints file:line:offender to stderr) |
| 9 | + * 2 unexpected error (e.g. workflows dir missing) |
| 10 | + * |
| 11 | + * Environment: |
| 12 | + * LINT_WORKFLOWS_DIR override the directory to lint (default: .github/workflows) |
| 13 | + * useful for unit tests pointing at fixture dirs |
| 14 | + */ |
| 15 | + |
| 16 | +import { readFileSync, readdirSync } from 'node:fs'; |
| 17 | +import { join, resolve } from 'node:path'; |
| 18 | + |
| 19 | +const WORKFLOWS_DIR = process.env.LINT_WORKFLOWS_DIR ?? '.github/workflows'; |
| 20 | + |
| 21 | +// Matches a ref ending with @<40-hex-chars> — tested against the extracted |
| 22 | +// ref value after stripping quotes, not the raw line. |
| 23 | +const PIN_RE = /@[a-f0-9]{40}$/; |
| 24 | + |
| 25 | +// Matches a uses: line (list-item form or map-value form, quoted or unquoted). |
| 26 | +// Group 1: optional open quote, Group 2: the reference value, Group 3: trailing comment |
| 27 | +const USES_RE = /^\s*-?\s*uses:\s*(['"]?)([^'";\s#]+)\1(\s*#.*)?$/; |
| 28 | + |
| 29 | +let failed = 0; |
| 30 | + |
| 31 | +try { |
| 32 | + const dir = resolve(WORKFLOWS_DIR); |
| 33 | + const files = readdirSync(dir).filter( |
| 34 | + (f) => f.endsWith('.yml') || f.endsWith('.yaml'), |
| 35 | + ); |
| 36 | + |
| 37 | + for (const f of files) { |
| 38 | + const filePath = join(dir, f); |
| 39 | + const lines = readFileSync(filePath, 'utf8').split(/\r?\n/); |
| 40 | + |
| 41 | + lines.forEach((line, idx) => { |
| 42 | + const m = line.match(USES_RE); |
| 43 | + if (!m) return; |
| 44 | + |
| 45 | + const ref = m[2]; |
| 46 | + // Local actions (./.github/actions/...) and docker images are not |
| 47 | + // pinnable by commit SHA — skip them. |
| 48 | + if (ref.startsWith('./') || ref.startsWith('docker://')) return; |
| 49 | + |
| 50 | + // Test the extracted ref value (not the raw line) to handle quoted forms |
| 51 | + // like uses: 'org/repo@<sha>' where a closing quote follows the SHA. |
| 52 | + if (!PIN_RE.test(ref)) { |
| 53 | + process.stderr.write( |
| 54 | + `${filePath}:${idx + 1}: not pinned to 40-char SHA: ${line.trim()}\n`, |
| 55 | + ); |
| 56 | + failed++; |
| 57 | + } |
| 58 | + }); |
| 59 | + } |
| 60 | +} catch (err) { |
| 61 | + process.stderr.write(`lint-workflows: ${err.message}\n`); |
| 62 | + process.exit(2); |
| 63 | +} |
| 64 | + |
| 65 | +process.exit(failed > 0 ? 1 : 0); |
0 commit comments