magallanes/src/Task/BuiltIn/Git/ChangeBranchTask.php

93 lines
2.5 KiB
PHP
Raw Normal View History

2016-12-31 07:52:25 +01:00
<?php
2022-04-10 06:20:03 +02:00
2016-12-31 07:52:25 +01:00
/*
* This file is part of the Magallanes package.
*
* (c) Andrés Montañez <andres@andresmontanez.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Mage\Task\BuiltIn\Git;
2017-01-07 05:53:57 +01:00
use Mage\Task\Exception\SkipException;
2016-12-31 07:52:25 +01:00
use Symfony\Component\Process\Process;
use Mage\Task\AbstractTask;
/**
* Git Task - Checkout Branch
*
* @author Andrés Montañez <andresmontanez@gmail.com>
*/
class ChangeBranchTask extends AbstractTask
{
2022-04-10 06:20:03 +02:00
public function getName(): string
2016-12-31 07:52:25 +01:00
{
return 'git/change-branch';
}
2022-04-10 06:20:03 +02:00
public function getDescription(): string
2016-12-31 07:52:25 +01:00
{
$options = $this->getOptions();
$tag = $options['tag'];
2016-12-31 07:52:25 +01:00
$branch = $options['branch'];
2022-04-10 06:20:03 +02:00
if ($this->runtime->getVar('git_revert_branch', null)) {
2016-12-31 07:52:25 +01:00
$branch = $this->runtime->getVar('git_revert_branch');
}
if ($tag) {
return sprintf('[Git] Checkout Tag (%s)', $tag);
}
2016-12-31 07:52:25 +01:00
return sprintf('[Git] Change Branch (%s)', $branch);
}
2022-04-10 06:20:03 +02:00
public function execute(): bool
2016-12-31 07:52:25 +01:00
{
$options = $this->getOptions();
2022-04-10 06:20:03 +02:00
/** @var string|bool */
$branch = $this->runtime->getVar('git_revert_branch', null);
2016-12-31 07:52:25 +01:00
2022-04-10 06:20:03 +02:00
if (!$branch) {
2016-12-31 07:52:25 +01:00
$cmdGetCurrent = sprintf('%s branch | grep "*"', $options['path']);
/** @var Process $process */
$process = $this->runtime->runLocalCommand($cmdGetCurrent);
if (!$process->isSuccessful()) {
2016-12-31 07:52:25 +01:00
return false;
}
$currentBranch = str_replace('* ', '', trim($process->getOutput()));
2022-04-10 23:06:48 +02:00
if ($currentBranch === $options['branch']) {
throw new SkipException();
}
$branch = $options['tag'] ? $options['tag'] : $options['branch'];
$this->runtime->setVar('git_revert_branch', $currentBranch);
2016-12-31 07:52:25 +01:00
}
$cmdChange = sprintf('%s checkout %s', $options['path'], $branch);
/** @var Process $process */
$process = $this->runtime->runLocalCommand($cmdChange);
return $process->isSuccessful();
}
2022-04-10 06:20:03 +02:00
/**
* @return array<string, string>
*/
protected function getOptions(): array
2016-12-31 07:52:25 +01:00
{
$tag = $this->runtime->getEnvOption('tag', false);
2017-01-12 02:22:21 +01:00
$branch = $this->runtime->getEnvOption('branch', 'master');
2016-12-31 07:52:25 +01:00
$options = array_merge(
['path' => 'git', 'branch' => $branch, 'tag' => $tag],
2016-12-31 07:52:25 +01:00
$this->options
);
return $options;
}
}