protected function execute(InputInterface $input, OutputInterface $output)
{
$project = $this->getCurrentProject();
$projectRoot = $this->getProjectRoot();
if (!$project || !$projectRoot) {
throw new RootNotFoundException();
}
$branch = $input->getArgument('id');
if (empty($branch)) {
if ($input->isInteractive()) {
$branch = $this->offerBranchChoice($project, $projectRoot);
if (empty($branch)) {
return 1;
}
} else {
$this->stdErr->writeln('No branch specified.');
return 1;
}
}
/** @var \Platformsh\Cli\Helper\GitHelper $gitHelper */
$gitHelper = $this->getHelper('git');
$gitHelper->setDefaultRepositoryDir($projectRoot);
$existsLocally = $gitHelper->branchExists($branch);
if (!$existsLocally && !$this->api()->getEnvironment($branch, $project)) {
$this->stdErr->writeln('Branch not found: <error>' . $branch . '</error>');
return 1;
}
// If the branch exists locally, check it out directly.
if ($existsLocally) {
$this->stdErr->writeln('Checking out <info>' . $branch . '</info>');
return $gitHelper->checkOut($branch) ? 0 : 1;
}
// Make sure that remotes are set up correctly.
$this->localProject->ensureGitRemote($projectRoot, $project->getGitUrl());
// Determine the correct upstream for the new branch. If there is an
// 'origin' remote, then it has priority.
$upstreamRemote = self::$config->get('detection.git_remote_name');
$originRemoteUrl = $gitHelper->getConfig('remote.origin.url');
if ($originRemoteUrl !== $project->getGitUrl(false) && $gitHelper->remoteBranchExists('origin', $branch)) {
$upstreamRemote = 'origin';
}
// Fetch the branch from the upstream remote.
$gitHelper->fetch($upstreamRemote, $branch);
$upstream = $upstreamRemote . '/' . $branch;
$this->stdErr->writeln(sprintf('Creating branch %s based on upstream %s', $branch, $upstream));
// Create the new branch, and set the correct upstream.
$success = $gitHelper->checkOutNew($branch, null, $upstream);
return $success ? 0 : 1;
}