|
| 1 | +#!/usr/bin/env node |
| 2 | +const sander = require('@marionebl/sander'); |
| 3 | +const execa = require('execa'); |
| 4 | +const findUp = require('find-up'); |
| 5 | + |
| 6 | +// Allow to override used bins for testing purposes |
| 7 | +const GIT = process.env.TRAVIS_COMMITLINT_GIT_BIN || 'git'; |
| 8 | +const COMMITLINT = |
| 9 | + process.env.TRAVIS_COMMITLINT_BIN || require('@commitlint/cli'); // eslint-disable-line import/newline-after-import |
| 10 | +const REQUIRED = ['TRAVIS_COMMIT', 'TRAVIS_BRANCH']; |
| 11 | + |
| 12 | +const TRAVIS_BRANCH = process.env.TRAVIS_BRANCH; |
| 13 | +const TRAVIS_COMMIT = process.env.TRAVIS_COMMIT; |
| 14 | + |
| 15 | +main().catch(err => { |
| 16 | + console.log(err); |
| 17 | + process.exit(1); |
| 18 | +}); |
| 19 | + |
| 20 | +async function main() { |
| 21 | + if (process.env.CI !== 'true' || process.env.TRAVIS !== 'true') { |
| 22 | + throw new Error( |
| 23 | + `@commitlint/travis-cli is inteded to be used on Travis CI` |
| 24 | + ); |
| 25 | + } |
| 26 | + |
| 27 | + const gitRoot = await findUp('.git'); |
| 28 | + const missing = REQUIRED.filter(envVar => !(envVar in process.env)); |
| 29 | + |
| 30 | + if (missing.length > 0) { |
| 31 | + const stanza = missing.length > 1 ? 'they were not' : 'it was not'; |
| 32 | + throw new Error( |
| 33 | + `Expected ${missing.join(', ')} to be defined globally, ${stanza}.` |
| 34 | + ); |
| 35 | + } |
| 36 | + |
| 37 | + const pop = await stash(); |
| 38 | + |
| 39 | + await git(['remote', 'set-branches', 'origin', TRAVIS_BRANCH]); |
| 40 | + |
| 41 | + if (await sander.exists(gitRoot, 'shallow')) { |
| 42 | + await git(['fetch', '--unshallow', '--quiet']); |
| 43 | + } |
| 44 | + |
| 45 | + await git(['checkout', TRAVIS_BRANCH, '--quiet']); |
| 46 | + await git(['checkout', '-', '--quiet']); |
| 47 | + |
| 48 | + await pop(); |
| 49 | + |
| 50 | + await lint(['--from', TRAVIS_BRANCH, '--to', TRAVIS_COMMIT]); |
| 51 | +} |
| 52 | + |
| 53 | +async function git(args, options) { |
| 54 | + return execa(GIT, args, Object.assign({}, {stdio: 'inherit'}, options)); |
| 55 | +} |
| 56 | + |
| 57 | +async function isClean() { |
| 58 | + const result = await git(['status', '--porcelain'], { |
| 59 | + stdio: ['pipe', 'pipe', 'pipe'] |
| 60 | + }); |
| 61 | + return !(result.stdout && result.stdout.trim()); |
| 62 | +} |
| 63 | + |
| 64 | +async function lint(args, options) { |
| 65 | + return execa( |
| 66 | + COMMITLINT, |
| 67 | + args, |
| 68 | + Object.assign({}, {stdio: 'inherit'}, options) |
| 69 | + ); |
| 70 | +} |
| 71 | + |
| 72 | +async function stash() { |
| 73 | + if (await isClean()) { |
| 74 | + return async () => {}; |
| 75 | + } |
| 76 | + await git(['stash']); |
| 77 | + return () => git(['stash', 'pop']); |
| 78 | +} |
0 commit comments