diff --git a/src/Commands/Env/CodeRebuildCommand.php b/src/Commands/Env/CodeRebuildCommand.php index 2f29b8798..89509a915 100644 --- a/src/Commands/Env/CodeRebuildCommand.php +++ b/src/Commands/Env/CodeRebuildCommand.php @@ -7,16 +7,19 @@ use Pantheon\Terminus\Exceptions\TerminusException; use Pantheon\Terminus\Site\SiteAwareInterface; use Pantheon\Terminus\Site\SiteAwareTrait; +use Pantheon\Terminus\Request\RequestAwareInterface; +use Pantheon\Terminus\Request\RequestAwareTrait; /** * Class CodeRebuildCommand. * * @package Pantheon\Terminus\Commands\Env */ -class CodeRebuildCommand extends TerminusCommand implements SiteAwareInterface +class CodeRebuildCommand extends TerminusCommand implements SiteAwareInterface, RequestAwareInterface { use SiteAwareTrait; use WorkflowProcessingTrait; + use RequestAwareTrait; /** * Moves code to the specified environment's runtime from the associated git branch, retriggering Composer builds for sites using Integrated Composer. (Not applicable for Test and Live environments which run on git tags made from the Dev environment's git history.) @@ -40,6 +43,14 @@ public function rebuild( $site = $this->getSiteById($site_env); $env = $this->getEnv($site_env); + if ($site->isEvcs()) { + if (($env->getName() === 'test' || $env->getName() === 'live') && !$site->isNodejs()) { + // Rebuilding for test/live is only supported for Node.js sites. + throw new TerminusException('Rebuilding for test/live is only supported for Node.js sites.'); + } + return $this->rebuildFromVcs($site->get('id'), $env->getName()); + } + if ($env->getName() === 'test' || $env->getName() === 'live') { throw new TerminusException('Test and live are not valid environments for this command.'); } @@ -56,4 +67,51 @@ public function rebuild( $this->processWorkflow($workflow); $this->log()->notice($workflow->getMessage()); } + + /** + * Rebuild from latest vcs event. + */ + protected function rebuildFromVcs(string $site_id, string $env) + { + $path = sprintf("%s/vcs/v1/site-details/%s/environments/%s/rebuild", $this->getBaseURI(), $site_id, $env); + $response = $this->request()->request($path, [ + 'method' => 'POST', + 'json' => [], + 'headers' => [ + 'Authorization' => sprintf( + 'Bearer %s', + $this->session()->get('session') + ), + ], + ]); + if ($response->getStatusCode() !== 201) { + throw new TerminusException( + 'Failed to rebuild from VCS for site {site} environment {env}. Status Code: {status_code}', + ['site' => $site_id, 'env' => $env, 'status_code' => $response->getStatusCode()] + ); + } + $this->log()->info( + "Rebuild is now happening for site {site} environment {env}.", + ['site' => $site_id, 'env' => $env] + ); + } + + /** + * Get API Base Uri. + */ + /** + * Parses the base URI for requests. + * + * @return string + */ + private function getBaseURI() + { + $config = $this->getConfig(); + return sprintf( + '%s://%s:%s', + $config->get('protocol'), + $config->get('host'), + $config->get('port') + ); + } }