ThomasBurleson
6/4/2016 - 12:21 AM

pr_clean.js

var GithubAPI = require('github');
var child_process = require('child_process');

var github = new GithubAPI({
  version: '3.0.0',
});

github.authenticate({
  type: "oauth",
  username: 'DevVersion-Bot',
  token: '/* TOKEN */'
});


var branch_checks = getAllBranches().map(branch => {
  return isBranchStale(branch).then(success => {
    return {
      name: branch,
      stale: success
    };
  });
});

/**
 * After all the async branch checks finish, log & generate git command 
 * to delete each stale branch.
 */
Promise.all(branch_checks).then(summary => {
  let staleNames = summary
          .filter(entry => entry.stale)
          .map(entry => entry.name);

  console.log('Stale Brances:');
  staleName.forEach(entry => {
     console.log(`  - ${entry.name}`);
  });

  console.log('\n\nSafe Delete Command:');
  console.log(`  git branch -D ${staleNames.join(' ')}`);
});

/**
 * 
 */
function isBranchStale(branchName) {
  // Change the branch
  child_process.execSync('git stash');
  child_process.execSync(`git checkout ${branchName}`);

  // Load the last commit message
  var commit_message = child_process.execSync('git log -n 1').toString();
  var statements_regex = /(Fixes|Closes|Solves)\s#([0-9]+)/g;
  var issues = [];
  var states = [];

  var match;
  while (match = statements_regex.exec(commit_message)) {
    issues.push(match[2]);
  }

  issues = issues.map(issue => {
    return new Promise(resolve => {
      github.issues.get({
        user: 'angular',
        repo: 'material',
        number: issue
      }, function (err, data) {
        states.push(data.state);
        resolve();
      })
    });
  });

  return Promise.all(issues).then(() => {
    return !!states.every(state => state !== 'open');
  });
}

/**
 * 
 */
function getAllBranches() {
  var branches = child_process.execSync('git branch').toString();
  var branches_regex = /[A-Za-z].*/g;

  return branches.match(branches_regex);
}