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.
16 public function __construct($dirs = array()) {
25 public function push($dir) {
26 $this->dirs
[] = getcwd();
28 throw new Exception("Failed to chdir($dir)");
32 public function pop() {
33 $oldDir = array_pop($this->dirs
);
40 * FIXME: Why am I doing this? Can't we get a proper build-system for little
41 * CLI tools -- and then use prepackaged libraries?
46 * Given a link to a pull-request, determine which local repo
47 * it applies to and fetch any metadata.
50 * @param array $repos list of locally known repos
51 * @return PullRequest|NULL
53 public static function get($url, $repos) {
54 foreach ($repos as $repo => $relPath) {
55 if (preg_match("/^https:\/\/github.com\/(.*)\/(civicrm-{$repo})\/pull\/([0-9]+)(|\/commits|\/files)$/", $url, $matches)) {
56 list ($full, $githubUser, $githubRepo, $githubPr) = $matches;
58 $pr = new PullRequest();
60 $pr->data
= HttpClient
::getJson("https://api.github.com/repos/$githubUser/$githubRepo/pulls/$githubPr");
61 if (empty($pr->data
)) {
72 * @var string local repo name e.g. "core", "drupal"
81 public function getNumber() {
82 return $this->data
->number
;
86 * @return string name of the branch on the requestor's repo
88 public function getRequestorBranch() {
89 return $this->data
->head
->ref
;
93 * @return string URL of the requestor's repo
95 public function getRequestorRepoUrl() {
96 return $this->data
->head
->repo
->git_url
;
107 * @var string 'checkout', 'begin', 'help', etc
114 protected $baseBranch;
117 * @var array ($repoName => $gitRef)
124 protected $civiRoot = '.';
129 protected $drupalVersion = 7;
134 protected $dryRun = FALSE;
139 protected $fetch = FALSE;
144 protected $force = FALSE;
149 protected $rebase = FALSE;
152 * @var string, the word 'all' or comma-delimited list of repo names
154 protected $repoFilter = 'all';
157 * @var array ($repoName => $relPath)
164 protected $useGencode = FALSE;
169 protected $useSetup = FALSE;
172 * @var array, non-hyphenated arguments after the basedir
174 protected $arguments;
177 * @var string, the name of this program
189 public function __construct() {
190 $this->dirStack
= new DirStack();
191 $this->repos
= array(
193 'backdrop' => 'backdrop',
194 'drupal' => 'drupal',
195 'joomla' => 'joomla',
196 'packages' => 'packages',
197 'wordpress' => 'WordPress',
206 public function main($args) {
207 if (!$this->parseOptions($args)) {
208 printf("Error parsing arguments\n");
213 // All operations relative to civiRoot
214 $this->dirStack
->push($this->civiRoot
);
216 // Filter branch list based on what repos actually exist
217 foreach (array_keys($this->repos
) as $repo) {
218 if (!is_dir($this->repos
[$repo])) {
219 unset($this->repos
[$repo]);
222 if (!isset($this->repos
['core']) ||
!isset($this->repos
['packages'])) {
223 return $this->returnError("Root appears to be invalid -- missing too many repos. Try --root=<dir>\n");
226 $this->repos
= $this->filterRepos($this->repoFilter
, $this->repos
);
229 switch ($this->action
) {
231 call_user_func_array(array($this, 'doCheckoutAll'), $this->arguments
);
235 call_user_func_array(array($this, 'doFetchAll'), $this->arguments
);
239 call_user_func_array(array($this, 'doStatusAll'), $this->arguments
);
243 call_user_func_array(array($this, 'doBegin'), $this->arguments
);
247 call_user_func_array(array($this, 'doResume'), $this->arguments
);
251 call_user_func_array(array($this, 'doReview'), $this->arguments
);
254 //case 'merge-forward':
255 // call_user_func_array(array($this, 'doMergeForward'), $this->arguments);
259 call_user_func_array(array($this, 'doPush'), $this->arguments
);
268 return $this->returnError("unrecognized action: {$this->action}\n");
271 if ($this->useSetup
) {
272 $this->run('core', $this->civiRoot
. '/bin', 'bash', 'setup.sh');
274 elseif ($this->useGencode
) {
275 $this->run('core', $this->civiRoot
. '/xml', 'php', 'GenCode.php');
278 $this->dirStack
->pop();
285 public function parseOptions($args) {
286 $this->branches
= array();
287 $this->arguments
= array();
289 foreach ($args as $arg) {
290 if ($arg == '--fetch') {
293 elseif ($arg == '--rebase') {
294 $this->rebase
= TRUE;
296 elseif ($arg == '--dry-run' ||
$arg == '-n') {
297 $this->dryRun
= TRUE;
299 elseif ($arg == '--force' ||
$arg == '-f') {
302 elseif ($arg == '--gencode') {
303 $this->useGencode
= TRUE;
305 elseif ($arg == '--setup') {
306 $this->useSetup
= TRUE;
308 elseif (preg_match('/^--d([678])/', $arg, $matches)) {
309 $this->drupalVersion
= $matches[1];
311 elseif (preg_match('/^--root=(.*)/', $arg, $matches)) {
312 $this->civiRoot
= $matches[1];
314 elseif (preg_match('/^--repos=(.*)/', $arg, $matches)) {
315 $this->repoFilter
= $matches[1];
317 elseif (preg_match('/^--(core|packages|joomla|drupal|wordpress|backdrop)=(.*)/', $arg, $matches)) {
318 $this->branches
[$matches[1]] = $matches[2];
320 elseif (preg_match('/^-/', $arg)) {
321 printf("unrecognized argument: %s\n", $arg);
325 $this->arguments
[] = $arg;
329 $this->program
= @array_shift
($this->arguments
);
330 $this->action
= @array_shift
($this->arguments
);
335 public function doHelp() {
336 $program = basename($this->program
);
337 echo "Givi - Coordinate git checkouts across CiviCRM repositories\n";
339 echo " You have cloned and forked the CiviCRM repos. Each of the repos has two\n";
340 echo " remotes (origin + upstream). When working on a new PR, you generally want\n";
341 echo " to checkout official code (eg upstream/master) in all repos, but 1-2 repos\n";
342 echo " should use a custom branch (which tracks upstream/master).\n";
344 echo " $program [options] checkout <branch>\n";
345 echo " $program [options] fetch\n";
346 echo " $program [options] status\n";
347 echo " $program [options] begin <base-branch> [--core=<new-branch>|--drupal=<new-branch>|...] \n";
348 echo " $program [options] resume [--rebase] <base-branch> [--core=<custom-branch>|--drupal=<custom-branch>|...] \n";
349 echo " $program [options] review <base-branch> <pr-url-1> <pr-url-2>...\n";
350 #echo " $program [options] merge-forward <maintenace-branch> <development-branch>\n";
351 #echo " $program [options] push <remote> <branch>[:<branch>]\n";
353 echo " checkout: Checkout same branch name on all repos\n";
354 echo " fetch: Fetch remote changes on all repos\n";
355 echo " status: Display status on all repos\n";
356 echo " begin: Begin work on a new branch on some repo (and use base-branch for all others)\n";
357 echo " resume: Resume work on an existing branch on some repo (and use base-branch for all others)\n";
358 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";
359 #echo " merge-forward: On each repo, merge changes from maintenance branch to development branch\n";
360 #echo " push: On each repo, push a branch to a remote (Note: only intended for use with merge-forward)\n";
361 echo "Common options:\n";
362 echo " --dry-run: Don't do anything; only print commands that would be run\n";
363 echo " --d6: Specify that Drupal branches should use 6.x-* prefixes\n";
364 echo " --d7: Specify that Drupal branches should use 7.x-* prefixes (default)\n";
365 echo " --d8: Specify that Drupal branches should use 8.x-* prefixes\n";
366 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";
367 echo " --fetch: Fetch the latest code before creating, updating, or checking-out anything\n";
368 echo " --repos=X: Restrict operations to the listed repos (comma-delimited list) (default: all)";
369 echo " --root=X: Specify CiviCRM root directory (default: .)\n";
370 echo " --gencode: Run xml/GenCode after checking out code\n";
371 echo " --setup: Run bin/setup.sh (incl xml/GenCode) after checking out code\n";
372 echo "Special options:\n";
373 echo " --core=X: Specify the branch to use on the core repository\n";
374 echo " --packages=X: Specify the branch to use on the packages repository\n";
375 echo " --backdrop=X: Specify the branch to use on the backdrop repository\n";
376 echo " --drupal=X: Specify the branch to use on the drupal repository\n";
377 echo " --joomla=X: Specify the branch to use on the joomla repository\n";
378 echo " --wordpress=X: Specify the branch to use on the wordpress repository\n";
379 echo " --rebase: Perform a rebase before starting work\n";
380 echo "Known repositories:\n";
381 foreach ($this->repos
as $repo => $relPath) {
382 printf(" %-12s: %s\n", $repo, realpath($this->civiRoot
. DIRECTORY_SEPARATOR
. $relPath));
384 echo "When using 'begin' or 'resume' with a remote base-branch, most repositories\n";
385 echo "will have a detached HEAD. Only repos with an explicit branch will be real,\n";
386 echo "local branches.\n";
390 * @param null $baseBranch
394 public function doCheckoutAll($baseBranch = NULL) {
396 return $this->returnError("Missing <branch>\n");
398 $branches = $this->resolveBranches($baseBranch, $this->branches
);
403 foreach ($this->repos
as $repo => $relPath) {
404 $filteredBranch = $this->filterBranchName($repo, $branches[$repo]);
405 $this->run($repo, $relPath, 'git', 'checkout', $filteredBranch, $this->force ?
'-f' : NULL);
413 public function doStatusAll() {
414 foreach ($this->repos
as $repo => $relPath) {
415 $this->run($repo, $relPath, 'git', 'status');
421 * @param null $baseBranch
425 public function doBegin($baseBranch = NULL) {
427 return $this->returnError("Missing <base-branch>\n");
429 if (empty($this->branches
)) {
430 return $this->returnError("Must specify a custom branch for at least one repository.\n");
432 $branches = $this->resolveBranches($baseBranch, $this->branches
);
437 foreach ($this->repos
as $repo => $relPath) {
438 $filteredBranch = $this->filterBranchName($repo, $branches[$repo]);
439 $filteredBaseBranch = $this->filterBranchName($repo, $baseBranch);
441 if ($filteredBranch == $filteredBaseBranch) {
442 $this->run($repo, $relPath, 'git', 'checkout', $filteredBranch, $this->force ?
'-f' : NULL);
445 $this->run($repo, $relPath, 'git', 'checkout', '-b', $filteredBranch, $filteredBaseBranch, $this->force ?
'-f' : NULL);
453 * @param null $baseBranch
458 public function doResume($baseBranch = NULL) {
460 return $this->returnError("Missing <base-branch>\n");
462 if (empty($this->branches
)) {
463 return $this->returnError("Must specify a custom branch for at least one repository.\n");
465 $branches = $this->resolveBranches($baseBranch, $this->branches
);
470 foreach ($this->repos
as $repo => $relPath) {
471 $filteredBranch = $this->filterBranchName($repo, $branches[$repo]);
472 $filteredBaseBranch = $this->filterBranchName($repo, $baseBranch);
474 $this->run($repo, $relPath, 'git', 'checkout', $filteredBranch, $this->force ?
'-f' : NULL);
475 if ($filteredBranch != $filteredBaseBranch && $this->rebase
) {
476 list ($baseRemoteRepo, $baseRemoteBranch) = $this->parseBranchRepo($filteredBaseBranch);
477 $this->run($repo, $relPath, 'git', 'pull', '--rebase', $baseRemoteRepo, $baseRemoteBranch);
485 * @param null $baseBranch
489 public function doReview($baseBranch = NULL) {
490 if (!$this->doCheckoutAll($baseBranch)) {
494 $args = func_get_args();
495 array_shift($args); // $baseBranch
497 $pullRequests = array();
498 foreach ($args as $prUrl) {
499 $pullRequest = PullRequest
::get($prUrl, $this->repos
);
501 $pullRequests[] = $pullRequest;
504 return $this->returnError("Invalid pull-request URL: $prUrl");
508 foreach ($pullRequests as $pullRequest) {
509 $repo = $pullRequest->repo
;
510 $branchName = 'pull-request-' . $pullRequest->getNumber();
511 if ($this->hasLocalBranch($repo, $branchName)) {
512 $this->run($repo, $this->repos
[$repo], 'git', 'branch', '-D', $branchName);
514 $this->run($repo, $this->repos
[$repo], 'git', 'checkout', '-b', $branchName); ## based on whatever was chosen by doCheckoutAll()
515 $this->run($repo, $this->repos
[$repo], 'git', 'pull', $pullRequest->getRequestorRepoUrl(), $pullRequest->getRequestorBranch());
522 * @param $newBranchRepo
523 * @param $newBranchNames
527 public function doPush($newBranchRepo, $newBranchNames) {
528 if (!$newBranchRepo) {
529 return $this->returnError("Missing <remote>\n");
531 if (!$newBranchNames) {
532 return $this->returnError("Missing <branch>[:<branch>]\n");
534 if (FALSE !== strpos($newBranchNames, ':')) {
535 list ($newBranchFromName, $newBranchToName) = explode(':', $newBranchNames);
536 foreach ($this->repos
as $repo => $relPath) {
537 $filteredFromName = $this->filterBranchName($repo, $newBranchFromName);
538 $filteredToName = $this->filterBranchName($repo, $newBranchToName);
540 $this->run($repo, $relPath, 'git', 'push', $newBranchRepo, $filteredFromName . ':' . $filteredToName);
544 foreach ($this->repos
as $repo => $relPath) {
545 $filteredName = $this->filterBranchName($repo, $newBranchNames);
546 $this->run($repo, $relPath, 'git', 'push', $newBranchRepo, $filteredName);
554 * Determine if a branch exists locally
556 * @param string $repo
557 * @param string $name branch name
560 public function hasLocalBranch($repo, $name) {
561 $path = $this->repos
[$repo] . '/.git/refs/heads/' . $name;
562 return file_exists($path);
566 * Given a ref name, determine the repo and branch
568 * FIXME: only supports $refs like "foo" (implicit origin) or "myremote/foo"
571 * @param string $defaultRemote
576 public function parseBranchRepo($ref, $defaultRemote = 'origin') {
577 $parts = explode('/', $ref);
578 if (count($parts) == 1) {
579 return array($defaultRemote, $parts[1]);
581 elseif (count($parts) == 2) {
585 throw new Exception("Failed to parse branch name ($ref)");
592 * Any items after $command will be escaped and added to $command
595 * @param string $runDir
596 * @param string $command
600 public function run($repoName, $runDir, $command) {
601 $this->dirStack
->push($runDir);
603 $args = func_get_args();
607 foreach ($args as $arg) {
609 $command .= ' ' . escapeshellarg($arg);
612 printf("\n\n\nRUN [%s]: %s\n", $repoName, $command);
617 $r = system($command);
620 $this->dirStack
->pop();
624 public function doFetchAll() {
625 foreach ($this->repos
as $repo => $relPath) {
626 $this->run($repo, $relPath, 'git', 'fetch', '--all');
631 * @param string $default branch to use by default
634 * @return array ($repoName => $gitRef)
636 public function resolveBranches($default, $overrides) {
637 $branches = $overrides;
638 foreach ($this->repos
as $repo => $relPath) {
639 if (!isset($branches[$repo])) {
640 $branches[$repo] = $default;
652 public function filterBranchName($repoName, $branchName) {
653 if ($branchName == '') {
656 if ($repoName == 'drupal') {
657 $parts = explode('/', $branchName);
658 $last = $this->drupalVersion
. '.x-' . array_pop($parts);
659 array_push($parts, $last);
660 return implode('/', $parts);
662 if ($repoName == 'backdrop') {
663 $parts = explode('/', $branchName);
664 $last = '1.x-' . array_pop($parts);
665 array_push($parts, $last);
666 return implode('/', $parts);
672 * @param string $filter e.g. "all" or "repo1,repo2"
673 * @param array $repos ($repoName => $repoDir)
676 * @return array ($repoName => $repoDir)
678 public function filterRepos($filter, $repos) {
679 if ($filter == 'all') {
683 $inclRepos = explode(',', $filter);
684 $unknowns = array_diff($inclRepos, array_keys($repos));
685 if (!empty($unknowns)) {
686 throw new Exception("Unknown Repos: " . implode(',', $unknowns));
688 $unwanted = array_diff(array_keys($repos), $inclRepos);
689 foreach ($unwanted as $repo) {
690 unset($repos[$repo]);
700 public function returnError($message) {
701 echo "\nERROR: ", $message, "\n\n";
718 public static function download($url, $file) {
719 // PHP native client is unreliable PITA for HTTPS
720 if (exec("which wget")) {
721 self
::run('wget', '-q', '-O', $file, $url);
723 elseif (exec("which curl")) {
724 self
::run('curl', '-o', $file, $url);
727 // FIXME: really detect errors
736 public static function getJson($url) {
737 $file = tempnam(sys_get_temp_dir(), 'givi-json-');
738 HttpClient
::download($url, $file);
739 $data = json_decode(file_get_contents($file));
747 * Any items after $command will be escaped and added to $command
749 * @param string $command
751 * @internal param string $runDir
754 public static function run($command) {
755 $args = func_get_args();
757 foreach ($args as $arg) {
758 $command .= ' ' . escapeshellarg($arg);
760 printf("\n\n\nRUN: %s\n", $command);
761 $r = system($command);