4 // This is the minimalist denialist implementation that doesn't check it's
5 // pre-conditions and will screw up if you don't know what you're doing.
8 * Manage the current working directory as a stack.
13 function __construct($dirs = array()) {
18 $this->dirs
[] = getcwd();
20 throw new Exception("Failed to chdir($dir)");
25 $oldDir = array_pop($this->dirs
);
31 * FIXME: Why am I doing this? Can't we get a proper build-system for little
32 * CLI tools -- and then use prepackaged libraries?
37 * Given a link to a pull-request, determine which local repo
38 * it applies to and fetch any metadata.
41 * @param array $repos list of locally known repos
42 * @return PullRequest|NULL
44 public static function get($url, $repos) {
45 foreach ($repos as $repo => $relPath) {
46 if (preg_match("/^https:\/\/github.com\/(.*)\/(civicrm-{$repo})\/pull\/([0-9]+)(|\/commits|\/files)$/", $url, $matches)) {
47 list ($full, $githubUser, $githubRepo, $githubPr) = $matches;
49 $pr = new PullRequest();
51 $pr->data
= HttpClient
::getJson("https://api.github.com/repos/$githubUser/$githubRepo/pulls/$githubPr");
52 if (empty($pr->data
)) {
63 * @var string local repo name e.g. "core", "drupal"
69 public function getNumber() {
70 return $this->data
->number
;
74 * @return string name of the branch on the requestor's repo
76 public function getRequestorBranch() {
77 return $this->data
->head
->ref
;
81 * @return string URL of the requestor's repo
83 public function getRequestorRepoUrl() {
84 return $this->data
->head
->repo
->git_url
;
91 * @var string 'checkout', 'begin', 'help', etc
98 protected $baseBranch;
101 * @var array ($repoName => $gitRef)
108 protected $civiRoot = '.';
113 protected $drupalVersion = 7;
118 protected $dryRun = FALSE;
123 protected $fetch = FALSE;
128 protected $force = FALSE;
133 protected $rebase = FALSE;
136 * @var string, the word 'all' or comma-delimited list of repo names
138 protected $repoFilter = 'all';
141 * @var array ($repoName => $relPath)
148 protected $useGencode = FALSE;
153 protected $useSetup = FALSE;
156 * @var array, non-hyphenated arguments after the basedir
158 protected $arguments;
161 * @var string, the name of this program
170 function __construct() {
171 $this->dirStack
= new DirStack();
172 $this->repos
= array(
174 'drupal' => 'drupal',
175 'joomla' => 'joomla',
176 'packages' => 'packages',
177 'wordpress' => 'WordPress',
181 function main($args) {
182 if (!$this->parseOptions($args)) {
183 printf("Error parsing arguments\n");
188 // All operations relative to civiRoot
189 $this->dirStack
->push($this->civiRoot
);
191 // Filter branch list based on what repos actually exist
192 foreach (array_keys($this->repos
) as $repo) {
193 if (!is_dir($this->repos
[$repo])) {
194 unset($this->repos
[$repo]);
197 if (!isset($this->repos
['core']) ||
!isset($this->repos
['packages'])) {
198 return $this->returnError("Root appears to be invalid -- missing too many repos. Try --root=<dir>\n");
201 $this->repos
= $this->filterRepos($this->repoFilter
, $this->repos
);
204 switch ($this->action
) {
206 call_user_func_array(array($this, 'doCheckoutAll'), $this->arguments
);
209 call_user_func_array(array($this, 'doFetchAll'), $this->arguments
);
212 call_user_func_array(array($this, 'doStatusAll'), $this->arguments
);
215 call_user_func_array(array($this, 'doBegin'), $this->arguments
);
218 call_user_func_array(array($this, 'doResume'), $this->arguments
);
221 call_user_func_array(array($this, 'doReview'), $this->arguments
);
223 //case 'merge-forward':
224 // call_user_func_array(array($this, 'doMergeForward'), $this->arguments);
227 call_user_func_array(array($this, 'doPush'), $this->arguments
);
234 return $this->returnError("unrecognized action: {$this->action}\n");
237 if ($this->useSetup
) {
238 $this->run('core', $this->civiRoot
. '/bin', 'bash', 'setup.sh');
240 elseif ($this->useGencode
) {
241 $this->run('core', $this->civiRoot
. '/xml', 'php', 'GenCode.php');
244 $this->dirStack
->pop();
251 function parseOptions($args) {
252 $this->branches
= array();
253 $this->arguments
= array();
255 foreach ($args as $arg) {
256 if ($arg == '--fetch') {
259 elseif ($arg == '--rebase') {
260 $this->rebase
= TRUE;
262 elseif ($arg == '--dry-run' ||
$arg == '-n') {
263 $this->dryRun
= TRUE;
265 elseif ($arg == '--force' ||
$arg == '-f') {
268 elseif ($arg == '--gencode') {
269 $this->useGencode
= TRUE;
271 elseif ($arg == '--setup') {
272 $this->useSetup
= TRUE;
274 elseif (preg_match('/^--d([678])/', $arg, $matches)) {
275 $this->drupalVersion
= $matches[1];
277 elseif (preg_match('/^--root=(.*)/', $arg, $matches)) {
278 $this->civiRoot
= $matches[1];
280 elseif (preg_match('/^--repos=(.*)/', $arg, $matches)) {
281 $this->repoFilter
= $matches[1];
283 elseif (preg_match('/^--(core|packages|joomla|drupal|wordpress)=(.*)/', $arg, $matches)) {
284 $this->branches
[$matches[1]] = $matches[2];
286 elseif (preg_match('/^-/', $arg)) {
287 printf("unrecognized argument: %s\n", $arg);
291 $this->arguments
[] = $arg;
295 $this->program
= @array_shift
($this->arguments
);
296 $this->action
= @array_shift
($this->arguments
);
302 $program = basename($this->program
);
303 echo "Givi - Coordinate git checkouts across CiviCRM repositories\n";
305 echo " You have cloned and forked the CiviCRM repos. Each of the repos has two\n";
306 echo " remotes (origin + upstream). When working on a new PR, you generally want\n";
307 echo " to checkout official code (eg upstream/master) in all repos, but 1-2 repos\n";
308 echo " should use a custom branch (which tracks upstream/master).\n";
310 echo " $program [options] checkout <branch>\n";
311 echo " $program [options] fetch\n";
312 echo " $program [options] status\n";
313 echo " $program [options] begin <base-branch> [--core=<new-branch>|--drupal=<new-branch>|...] \n";
314 echo " $program [options] resume [--rebase] <base-branch> [--core=<custom-branch>|--drupal=<custom-branch>|...] \n";
315 echo " $program [options] review <base-branch> <pr-url-1> <pr-url-2>...\n";
316 #echo " $program [options] merge-forward <maintenace-branch> <development-branch>\n";
317 #echo " $program [options] push <remote> <branch>[:<branch>]\n";
319 echo " checkout: Checkout same branch name on all repos\n";
320 echo " fetch: Fetch remote changes on all repos\n";
321 echo " status: Display status on all repos\n";
322 echo " begin: Begin work on a new branch on some repo (and use base-branch for all others)\n";
323 echo " resume: Resume work on an existing branch on some repo (and use base-branch for all others)\n";
324 echo " review: Test work provided by someone else's pull-request. (If each repo has related PRs, then you can link to each of them.)\n";
325 #echo " merge-forward: On each repo, merge changes from maintenance branch to development branch\n";
326 #echo " push: On each repo, push a branch to a remote (Note: only intended for use with merge-forward)\n";
327 echo "Common options:\n";
328 echo " --dry-run: Don't do anything; only print commands that would be run\n";
329 echo " --d6: Specify that Drupal branches should use 6.x-* prefixes\n";
330 echo " --d7: Specify that Drupal branches should use 7.x-* prefixes (default)\n";
331 echo " -f: When switching branches, proceed even if the index or the working tree differs from HEAD. This is used to throw away local changes.\n";
332 echo " --fetch: Fetch the latest code before creating, updating, or checking-out anything\n";
333 echo " --repos=X: Restrict operations to the listed repos (comma-delimited list) (default: all)";
334 echo " --root=X: Specify CiviCRM root directory (default: .)\n";
335 echo " --gencode: Run xml/GenCode after checking out code\n";
336 echo " --setup: Run bin/setup.sh (incl xml/GenCode) after checking out code\n";
337 echo "Special options:\n";
338 echo " --core=X: Specify the branch to use on the core repository\n";
339 echo " --packages=X: Specify the branch to use on the packages repository\n";
340 echo " --drupal=X: Specify the branch to use on the drupal repository\n";
341 echo " --joomla=X: Specify the branch to use on the joomla repository\n";
342 echo " --wordpress=X: Specify the branch to use on the wordpress repository\n";
343 echo " --rebase: Perform a rebase before starting work\n";
344 echo "Known repositories:\n";
345 foreach ($this->repos
as $repo => $relPath) {
346 printf(" %-12s: %s\n", $repo, realpath($this->civiRoot
. DIRECTORY_SEPARATOR
. $relPath));
348 echo "When using 'begin' or 'resume' with a remote base-branch, most repositories\n";
349 echo "will have a detached HEAD. Only repos with an explicit branch will be real,\n";
350 echo "local branches.\n";
353 function doCheckoutAll($baseBranch = NULL) {
355 return $this->returnError("Missing <branch>\n");
357 $branches = $this->resolveBranches($baseBranch, $this->branches
);
362 foreach ($this->repos
as $repo => $relPath) {
363 $filteredBranch = $this->filterBranchName($repo, $branches[$repo]);
364 $this->run($repo, $relPath, 'git', 'checkout', $filteredBranch, $this->force ?
'-f' : NULL);
369 function doStatusAll() {
370 foreach ($this->repos
as $repo => $relPath) {
371 $this->run($repo, $relPath, 'git', 'status');
376 function doBegin($baseBranch = NULL) {
378 return $this->returnError("Missing <base-branch>\n");
380 if (empty($this->branches
)) {
381 return $this->returnError("Must specify a custom branch for at least one repository.\n");
383 $branches = $this->resolveBranches($baseBranch, $this->branches
);
388 foreach ($this->repos
as $repo => $relPath) {
389 $filteredBranch = $this->filterBranchName($repo, $branches[$repo]);
390 $filteredBaseBranch = $this->filterBranchName($repo, $baseBranch);
392 if ($filteredBranch == $filteredBaseBranch) {
393 $this->run($repo, $relPath, 'git', 'checkout', $filteredBranch, $this->force ?
'-f' : NULL);
396 $this->run($repo, $relPath, 'git', 'checkout', '-b', $filteredBranch, $filteredBaseBranch, $this->force ?
'-f' : NULL);
403 function doResume($baseBranch = NULL) {
405 return $this->returnError("Missing <base-branch>\n");
407 if (empty($this->branches
)) {
408 return $this->returnError("Must specify a custom branch for at least one repository.\n");
410 $branches = $this->resolveBranches($baseBranch, $this->branches
);
415 foreach ($this->repos
as $repo => $relPath) {
416 $filteredBranch = $this->filterBranchName($repo, $branches[$repo]);
417 $filteredBaseBranch = $this->filterBranchName($repo, $baseBranch);
419 $this->run($repo, $relPath, 'git', 'checkout', $filteredBranch, $this->force ?
'-f' : NULL);
420 if ($filteredBranch != $filteredBaseBranch && $this->rebase
) {
421 list ($baseRemoteRepo, $baseRemoteBranch) = $this->parseBranchRepo($filteredBaseBranch);
422 $this->run($repo, $relPath, 'git', 'pull', '--rebase', $baseRemoteRepo, $baseRemoteBranch);
429 function doReview($baseBranch = NULL) {
430 if (! $this->doCheckoutAll($baseBranch)) {
434 $args = func_get_args();
435 array_shift($args); // $baseBranch
437 $pullRequests = array();
438 foreach ($args as $prUrl) {
439 $pullRequest = PullRequest
::get($prUrl, $this->repos
);
441 $pullRequests[] = $pullRequest;
443 return $this->returnError("Invalid pull-request URL: $prUrl");
447 foreach ($pullRequests as $pullRequest) {
448 $repo = $pullRequest->repo
;
449 $branchName = 'pull-request-' . $pullRequest->getNumber();
450 if ($this->hasLocalBranch($repo, $branchName)) {
451 $this->run($repo, $this->repos
[$repo], 'git', 'branch', '-D', $branchName);
453 $this->run($repo, $this->repos
[$repo], 'git', 'checkout', '-b', $branchName); ## based on whatever was chosen by doCheckoutAll()
454 $this->run($repo, $this->repos
[$repo], 'git', 'pull', $pullRequest->getRequestorRepoUrl(), $pullRequest->getRequestorBranch());
462 If we want merge-forward changes to be subject to PR process, then this
463 should useful. Currently using a simpler process based on
464 toosl/scripts/merge-forward
466 function doMergeForward($maintBranch, $devBranch) {
468 return $this->returnError("Missing <maintenace-base-branch>\n");
471 return $this->returnError("Missing <development-base-branch>\n");
473 list ($maintBranchRepo, $maintBranchName) = $this->parseBranchRepo($maintBranch);
474 list ($devBranchRepo, $devBranchName) = $this->parseBranchRepo($devBranch);
476 $newBranchRepo = $devBranchRepo;
477 $newBranchName = $maintBranchName . '-' . $devBranchName . '-' . date('Y-m-d-H-i-s');
483 foreach ($this->repos as $repo => $relPath) {
484 $filteredMaintBranch = $this->filterBranchName($repo, $maintBranch);
485 $filteredDevBranch = $this->filterBranchName($repo, $devBranch);
486 $filteredNewBranchName = $this->filterBranchName($repo, $newBranchName);
488 $this->run($repo, $relPath, 'git', 'checkout', '-b', $filteredNewBranchName, $filteredDevBranch);
489 $this->run($repo, $relPath, 'git', 'merge', $filteredMaintBranch);
494 function doPush($newBranchRepo, $newBranchNames) {
495 if (!$newBranchRepo) {
496 return $this->returnError("Missing <remote>\n");
498 if (!$newBranchNames) {
499 return $this->returnError("Missing <branch>[:<branch>]\n");
501 if (FALSE !== strpos($newBranchNames, ':')) {
502 list ($newBranchFromName,$newBranchToName) = explode(':', $newBranchNames);
503 foreach ($this->repos
as $repo => $relPath) {
504 $filteredFromName = $this->filterBranchName($repo, $newBranchFromName);
505 $filteredToName = $this->filterBranchName($repo, $newBranchToName);
507 $this->run($repo, $relPath, 'git', 'push', $newBranchRepo, $filteredFromName . ':' . $filteredToName);
510 foreach ($this->repos
as $repo => $relPath) {
511 $filteredName = $this->filterBranchName($repo, $newBranchNames);
512 $this->run($repo, $relPath, 'git', 'push', $newBranchRepo, $filteredName);
520 * Determine if a branch exists locally
522 * @param string $repo
523 * @param string $name branch name
526 function hasLocalBranch($repo, $name) {
527 $path = $this->repos
[$repo] . '/.git/refs/heads/' . $name;
528 return file_exists($path);
532 * Given a ref name, determine the repo and branch
534 * FIXME: only supports $refs like "foo" (implicit origin) or "myremote/foo"
539 function parseBranchRepo($ref, $defaultRemote = 'origin') {
540 $parts = explode('/', $ref);
541 if (count($parts) == 1) {
542 return array($defaultRemote, $parts[1]);
544 elseif (count($parts) == 2) {
548 throw new Exception("Failed to parse branch name ($ref)");
555 * Any items after $command will be escaped and added to $command
557 * @param string $runDir
558 * @param string $command
561 function run($repoName, $runDir, $command) {
562 $this->dirStack
->push($runDir);
564 $args = func_get_args();
568 foreach ($args as $arg) {
570 $command .= ' ' . escapeshellarg($arg);
573 printf("\n\n\nRUN [%s]: %s\n", $repoName, $command);
577 $r = system($command);
580 $this->dirStack
->pop();
584 function doFetchAll() {
585 foreach ($this->repos
as $repo => $relPath) {
586 $this->run($repo, $relPath, 'git', 'fetch', '--all');
591 * @param string $default branch to use by default
592 * @return array ($repoName => $gitRef)
594 function resolveBranches($default, $overrides) {
595 $branches = $overrides;
596 foreach ($this->repos
as $repo => $relPath) {
597 if (!isset($branches[$repo])) {
598 $branches[$repo] = $default;
604 function filterBranchName($repoName, $branchName) {
605 if ($branchName == '') {
608 if ($repoName == 'drupal') {
609 $parts = explode('/', $branchName);
610 $last = $this->drupalVersion
. '.x-' . array_pop($parts);
611 array_push($parts, $last);
612 return implode('/', $parts);
618 * @param string $filter e.g. "all" or "repo1,repo2"
619 * @param array $repos ($repoName => $repoDir)
620 * @return array ($repoName => $repoDir)
622 function filterRepos($filter, $repos) {
623 if ($filter == 'all') {
627 $inclRepos = explode(',', $filter);
628 $unknowns = array_diff($inclRepos, array_keys($repos));
629 if (!empty($unknowns)) {
630 throw new Exception("Unknown Repos: " . implode(',', $unknowns));
632 $unwanted = array_diff(array_keys($repos), $inclRepos);
633 foreach ($unwanted as $repo) {
634 unset($repos[$repo]);
639 function returnError($message) {
640 echo "\nERROR: ", $message, "\n\n";
647 static function download($url, $file) {
648 // PHP native client is unreliable PITA for HTTPS
649 if (exec("which wget")) {
650 self
::run('wget', '-q', '-O', $file, $url);
651 } elseif (exec("which curl")) {
652 self
::run('curl', '-o', $file, $url);
655 // FIXME: really detect errors
659 static function getJson($url) {
660 $file = tempnam(sys_get_temp_dir(), 'givi-json-');
661 HttpClient
::download($url, $file);
662 $data = json_decode(file_get_contents($file));
670 * Any items after $command will be escaped and added to $command
672 * @param string $runDir
673 * @param string $command
676 static function run($command) {
677 $args = func_get_args();
679 foreach ($args as $arg) {
680 $command .= ' ' . escapeshellarg($arg);
682 printf("\n\n\nRUN: %s\n", $command);
683 $r = system($command);