|
| 1 | +import Octokit from '@octokit/rest' |
| 2 | +import execa from 'execa' |
| 3 | + |
| 4 | +const NotFound = new Error() |
| 5 | + |
| 6 | +const git = (...args: string[]) => execa.stdout('git', args) |
| 7 | + |
| 8 | +const checkCommit = async (...refs: string[]) => |
| 9 | + Promise.all( |
| 10 | + refs.map(ref => |
| 11 | + git('cat-file', '-e', ref) |
| 12 | + ) |
| 13 | + ) |
| 14 | + |
| 15 | +const matchGithub = <T>(url: string | undefined, prop: string) => { |
| 16 | + if(!url) { |
| 17 | + throw NotFound |
| 18 | + } |
| 19 | + |
| 20 | + const match = url.match(new RegExp(`github\\.com/(.+)/(.+)/${prop}/(.+)`)) |
| 21 | + |
| 22 | + if(!match) { |
| 23 | + throw NotFound |
| 24 | + } |
| 25 | + |
| 26 | + const [_, owner, repo, data] = match |
| 27 | + |
| 28 | + return {owner, repo, data} |
| 29 | +} |
| 30 | + |
| 31 | +const getRangeFromPr = async () => { |
| 32 | + const {owner, repo, data: pull} = matchGithub(process.env['CIRCLE_PULL_REQUEST'], 'pull') |
| 33 | + const github = new Octokit() |
| 34 | + |
| 35 | + console.log('📡 Looking up PR #%s...', pull) |
| 36 | + const {data: {base, head}} = await github.pullRequests.get( |
| 37 | + {owner, repo, number: +pull} |
| 38 | + ) |
| 39 | + |
| 40 | + await checkCommit(base.sha, head.sha) |
| 41 | + |
| 42 | + console.log('🔀 Linting PR #%s', pull) |
| 43 | + |
| 44 | + return [base.sha, head.sha] |
| 45 | +} |
| 46 | + |
| 47 | +const getRangeFromCompare = async () => { |
| 48 | + const [from, to] = matchGithub(process.env['CIRCLE_COMPARE_URL'], 'compare').data.split('...') |
| 49 | + |
| 50 | + await checkCommit(from, to) |
| 51 | + console.log('🎏 Linting using comparison URL %s...%s', from, to) |
| 52 | + |
| 53 | + return [from, to] |
| 54 | +} |
| 55 | + |
| 56 | +const getRangeFromSha = async () => { |
| 57 | + const sha = process.env['CIRCLE_SHA1'] |
| 58 | + |
| 59 | + if(!sha) { |
| 60 | + throw new Error('Cannot find CIRCLE_SHA1 environment variable') |
| 61 | + } |
| 62 | + |
| 63 | + await checkCommit(sha) |
| 64 | + console.log('⚙️ Linting using CIRCLE_SHA1 (%s)', sha) |
| 65 | + |
| 66 | + return ['origin/master', sha] |
| 67 | +} |
| 68 | + |
| 69 | +const getRangeFromGit = async () => { |
| 70 | + const head = await git('rev-parse', '--verify', 'HEAD') |
| 71 | + |
| 72 | + await checkCommit(head) |
| 73 | + console.log('⚙️ Linting using git HEAD (%s)', head) |
| 74 | + |
| 75 | + return ['origin/master', head] |
| 76 | +} |
| 77 | + |
| 78 | +const lint = ([from, to]: string[]) => |
| 79 | + execa( |
| 80 | + 'node', |
| 81 | + [require('@commitlint/cli'), '--from', from, '--to', to], |
| 82 | + {stdio: 'inherit'} |
| 83 | + ) |
| 84 | + |
| 85 | +export const run = () => |
| 86 | + getRangeFromPr() |
| 87 | + .catch(getRangeFromCompare) |
| 88 | + .catch(getRangeFromSha) |
| 89 | + .catch(getRangeFromGit) |
| 90 | + .then(lint) |
0 commit comments