Skip to content

Instantly share code, notes, and snippets.

@alias-mac
Created May 19, 2014 17:55
Show Gist options
  • Save alias-mac/e8c788d33a49b5d0726c to your computer and use it in GitHub Desktop.
Save alias-mac/e8c788d33a49b5d0726c to your computer and use it in GitHub Desktop.
WIP repository cleaner
#!/usr/bin/env php
<?php
/*
* Copyright (c) 2008-2014 Filipe Guerra
* https://github.com/alias-mac/branch-cleaner
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* @file
* This script helps clean up some branches in SugarCRM repository
* Please read more about it here:
* https://github.com/alias-mac/branch-cleaner#readme
*/
// confirm we are running this using the cli
if (php_sapi_name() !== "cli") {
throw new \RuntimeException("This is only supported from the terminal");
}
if (version_compare(PHP_VERSION, '5.3.', '<')) {
throw new \RuntimeException("This script requires php 5.3.0 version or above.");
}
process($argv);
/**
* Process this command with the options passed on the CLI.
*/
function process($argv)
{
// f maps to file, d to dir, p to path, h to helper and v is verbose
$shortOpts = "v";
$longOpts = array(
"dry-run",
);
$opts = getopt($shortOpts, $longOpts);
// $converterOptions = array(
// 'dryRun' => isset($opts['dry-run']),
// 'verbose' => isset($opts['v']),
// );
}
require_once 'vendor/autoload.php';
use Guzzle\Http\Client;
use Guzzle\Http\Exception\ClientErrorResponseException;
// TODO make me configurable
$projectKeys = array(
'SC',
// 'MAR',
// 'SFA',
// 'BR',
);
$dryRun = true;
$ghOptions = array(
'owner' => 'sugarcrm',
'repo' => 'Mango',
);
// Create a client and provide a base URL
$gh = new Client('https://api.github.com');
// TODO change this to use configuration values
$gh->setDefaultOption('auth', array('alias-mac', 'md5'));
$jira = new Client('https://sugarcrm.atlassian.net/rest/api/latest/');
// TODO change this to use configuration values
$jira->setDefaultOption('auth', array('fguerra', 'password'));
$prs = $gh->get(sprintf("repos/%s/%s/issues?state=open&creator=tservo", $ghOptions['owner'], $ghOptions['repo']))
->send()->json();
echo sprintf("%d PR(s)\n", count($prs));
$findIn = implode('|', $projectKeys);
foreach ($prs as $pr) {
echo sprintf("PR number: %d\n", $pr['number']);
echo sprintf("Title: %s\n", $pr['title']);
echo sprintf("Body: %s\n", $pr['body']);
echo "Looking for JIRA issues\n";
$matches = array();
if (preg_match_all('/\b(' . $findIn . ')-\d+\b/i', $pr['title'], $matches) === false) {
throw new \RuntimeException("Error when applying regular expression against title.");
}
list($issuesT, $projectsT) = $matches;
$matches = array();
if (preg_match_all('/\b(' . $findIn . ')-\d+\b/i', $pr['body'], $matches) === false) {
throw new \RuntimeException("Error when applying regular expression against body.");
}
list($issuesB, $projectsB) = $matches;
$issues = array_merge($issuesT, $issuesB);
$projects = array_merge($projectsT, $projectsB);
if (empty($issues)) {
echo sprintf("No JIRA issues found for PR %d\n", $pr['number']);
continue;
}
$replacingPRs = array();
$allResolved = true;
// lets go to JIRA now with the found issues
foreach ($issues as $issueKey) {
try {
$issue = $jira->get("issue/$issueKey")->send()->json();
} catch (ClientErrorResponseException $e) {
if ($e->getResponse()->getStatusCode() !== 404) {
throw $e;
}
break;
}
if ($issue['fields']['status']['name'] !== 'Resolved') {
// TODO will be return after :)
$allResolved = false;
break;
}
// possible PRs that will replace it
$replacingPRs = array_unique(array_merge($replacingPRs, array_filter(array(
$issue['fields']['customfield_12000'],
$issue['fields']['customfield_13000'],
$issue['fields']['customfield_13001'],
))));
}
// all issues are resolved so lets close the PR
if (!$allResolved) {
continue;
}
$msg = array('Closing this since it is marked as resolved in JIRA.');
if (!empty($replacingPRs)) {
$msg[] = sprintf(
'PR%s replacing this (from JIRA): %s.',
count($replacingPRs) ? 's' : '',
implode(', ', $replacingPRs)
);
}
$comment = $gh->post(sprintf('repos/%s/%s/issues/%d/comments', $ghOptions['owner'], $ghOptions['repo'], $pr['number']))
->setBody(json_encode(array('body' => implode("\n", $msg))), 'application/json');
echo sprintf("Posting comment on PR '%d' with:\n %s\n", $pr['number'], $comment->getBody());
if (!$dryRun) {
$response = $comment->send();
if ($response->getStatusCode() !== 201) {
throw new \RuntimeException(
sprintf("Unable to post comment on PR %d\n", $pr['number'])
);
}
}
$close = $gh->patch(sprintf('repos/%s/%s/pulls/%d', $ghOptions['owner'], $ghOptions['repo'], $pr['number']))
->setBody(json_encode(array('state' => 'closed')), 'application/json');
echo sprintf("Closing PR '%d'.\n", $pr['number']);
if (!$dryRun) {
$response = $close->send();
if ($response->getStatusCode() !== 200) {
throw new \RuntimeException(
sprintf("Unable to post comment on PR %d\n", $pr['number'])
);
}
}
// $pr = $gh->get(sprintf("repos/%s/%s/pulls/%d", $ghOptions['owner'], $ghOptions['repo'], $issue['number']))
// ->send()->json();
//
// // cleanup the branch
// try {
// $branch = $gh->delete(sprintf("repos/%s/git/refs/heads/%s", $pr['head']['repo']['full_name'], $pr['head']['ref']));
//
// echo sprintf("Deleting branch '%s' on PR '%d'.\n", $branch->getUrl(), $pr['number']);
// if (!$dryRun) {
// $branch->send();
// }
// } catch (ClientErrorResponseException $e) {
// // if not already deleted
// if ($e->getResponse()->getStatusCode() !== 422) {
// throw $e;
// }
// continue;
// }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment