message: ci: properly validate commit messages locally
  PR Close
diff: // tslint:disable:no-console
  module.exports = (gulp) => async() => {
  try {
  - if (process.env['CI'] === 'true' && process.env['CI_PULL_REQUEST'] === 'false') {
  + const validateCommitMessage = require('../validate-commit-message');
  + const shelljs = require('shelljs');
  + const getRefsAndShasForTarget = require('../utils/get-refs-and-shas-for-target');
  +
  + // Break on error.
  + shelljs.set('-e');
  +
  +
  + let target = {};
  + if (process.env['CI'] === 'true') {
  + // Validation of commit messages on CI
  + if (process.env['CI_PULL_REQUEST'] === 'false') {
  + // Skip commit message validation on CI for non-PR branches as we are not testing new
  + // unreviewed commits. By enforcing correctness on the incoming changes in the PR
  + // branches, we are able to render this check unnecessary on non-PR branches.
  console.info(
  `Since valid commit messages are enforced by PR linting on CI,\n` +
  `we do not need to validate commit messages on CI runs on upstream branches.\n\n` +
  `Skipping validate-commit-message check`);
  process.exit();
  }
  - const validateCommitMessage = require('../validate-commit-message');
  - const shelljs = require('shelljs');
  - const getRefsAndShasForTarget = require('../utils/get-refs-and-shas-for-target');
  -
  - shelljs.set('-e'); // Break on error.
  -
  - const target = await getRefsAndShasForTarget(process.env['CIRCLE_PR_NUMBER']);
  + target = await getRefsAndShasForTarget(process.env['CI_PULL_REQUEST']);
  + } else {
  + // Validation of commit messages locally
  + const baseRef = 'master';
  + const headRef = shelljs.exec('git symbolic-ref --short HEAD', {silent: true}).trim();
  + const baseSha = shelljs.exec(`git rev-parse origin/master`, {silent: true}).trim();
  + const headSha = shelljs.exec(`git rev-parse HEAD`, {silent: true}).trim();
  + const commonAncestorSha =
  + shelljs.exec(`git merge-base origin/master ${headSha}`, {silent: true}).trim();
  + target = {
  + base: {
  + ref: baseRef,
  + sha: baseSha,
  + },
  + head: {
  + ref: headRef,
  + sha: headSha,
  + },
  + commonAncestorSha: commonAncestorSha,
  + latestShaOfTargetBranch: baseSha,
  + latestShaOfPrBranch: headSha,
  + };
  + }
  - // We need to fetch origin explicitly because it might be stale.
  - // I couldn't find a reliable way to do this without fetch.
  const result = shelljs.exec(
  - `git log --reverse --format=%s ${target.commonAncestorSha}..${target.latestShaOfPrBranch}`);
  + `git log --reverse --format=%s ${target.commonAncestorSha}..${target.latestShaOfPrBranch}`,
  + {silent: true});
  if (result.code) {
  throw new Error(`Failed to fetch commits: ${result.stderr}`);
  