STAGE command triggering release to server using deployer

@param string $stage Environment to deploy to (by default: local/staging/production)
@param string $branchOrTag Branch or Tag to deploy
@param array $opts
518914
public function deployDeploy(
        $stage,
        $branchOrTag,
        $opts = [
            self::OPT_DEPLOYER_PARALLEL => false,
        ]
    ) {
        // use string parallel due as robo always submits this string for both triggers
        $parallelMode = $opts['parallel'];

        $this->startTimer();

        $this->printStageInfo('DEPLOYER DEPLOY');

        $task = $this->taskDeployerDeploy($stage, $branchOrTag);
        if ($parallelMode === true) {
            $task->parallel();
        }

        $task->run();

        $this->stopTimer();
        $this->printRuntime(__FUNCTION__);
    }
1306681
public function execute(Node $node, Application $application, Deployment $deployment, array $options = [])
    {
        $options = $this->configureOptions($options);

        $workspacePath = $deployment->getWorkspacePath($application);
        $webDirectory = $application->hasOption('webDirectory') ? $application->getOption('webDirectory') : 'Web';
        $scriptBasePath = $options['scriptBasePath'] ?: Files::concatenatePaths([$workspacePath, $webDirectory]);

        if ($options['scriptIdentifier'] === null) {
            // Store the script identifier as an application option
            $scriptIdentifier = bin2hex($this->randomBytesGenerator->generate(32));
            $application->setOption(WebOpcacheResetExecuteTask::class . '[scriptIdentifier]', $scriptIdentifier);
        } else {
            $scriptIdentifier = $options['scriptIdentifier'];
        }

        $localhost = new Node('localhost');
        $localhost->onLocalhost();

        $commands = [
            'cd ' . escapeshellarg($scriptBasePath),
            'rm -f surf-opcache-reset-*',
        ];

        $this->shell->executeOrSimulate($commands, $localhost, $deployment);

        if (! $deployment->isDryRun()) {
            $scriptFilename = sprintf('%s/surf-opcache-reset-%s.php', $scriptBasePath, $scriptIdentifier);

            $result = $this->filesystem->put($scriptFilename, '<?php
                if (function_exists("opcache_reset")) {
                    opcache_reset();
                }
                @unlink(__FILE__);
                echo "success";
            ');

            if ($result === false) {
                throw TaskExecutionException::webOpcacheResetCreateScriptTaskCouldNotWritFile($scriptFilename);
            }
        }
    }
745251
public function execute(Node $node, Application $application, Deployment $deployment, array $options = [])
    {
        $deployment->getLogger()->warning(DeprecationMessageFactory::createGenericDeprecationWarningForTask(__CLASS__));
        $options = $this->configureOptions($options);
        $projectName = $options['sourceforgeProjectName'];

        $sourceforgeLogin = $options['sourceforgeUserName'] . ',' . $options['sourceforgeProjectName'];

        $projectDirectory = str_replace(' ', '\ ', sprintf('/home/frs/project/%s/%s/%s/%s/%s', substr($projectName, 0, 1), substr($projectName, 0, 2), $projectName, $options['sourceforgePackageName'], $options['version']));
        $targetHostAndDirectory = escapeshellarg($sourceforgeLogin . '@frs.sourceforge.net:' . $projectDirectory);

        $this->shell->executeOrSimulate('rsync -e ssh ' . implode(' ', $options['files']) . ' ' . $targetHostAndDirectory, $node, $deployment);
    }
1340039
function gulp(opts) {
  opts = opts || {};

  var failOnError = opts['failOnError'] || false;
  var interimFiles = [];
  var failedValidations = [];

  return Through(
    function (file) {
      interimFiles.push(file.path);
      this.queue(file);
    },
    function () {
      var baseFile = opts.packageFile;

      interimFiles.forEach(function (file) {
        opts.packageFile = file;

        var results = validate(opts);

        if (hasErrors(results)) {
          failedValidations.push(file);
          log(results);
        }
      });

      opts.packageFile = baseFile;

      if (failOnError &&  failedValidations.length) {
        this.emit('error', new PluginError('dep-validate', 'Unable to validate dependencies'));
      } else {
        this.emit('end');
      }
    }
  );
}
138994
protected function setOpt(array &$opts, $mapperString, $val)
    {
        $args = explode( '.', $mapperString );
        array_push( $args, $val );
        $this->setNestedOptVal( $opts, $args ); 
    }
201760
public function execute(Node $node, Application $application, Deployment $deployment, array $options = [])
    {
        $this->validateOptions($options);
        $options = $this->processOptions($options, $deployment);

        $targetPath = $deployment->getApplicationReleasePath($application);
        $this->shell->executeOrSimulate(sprintf('cd ' . $targetPath . '; git tag -f -a -m %s %s', escapeshellarg($options['description']), escapeshellarg($options['tagName'])), $node, $deployment);
        if (isset($options['recurseIntoSubmodules']) && $options['recurseIntoSubmodules'] === true) {
            $submoduleCommand = escapeshellarg(sprintf('git tag -f -a -m %s %s', escapeshellarg($options['description']), escapeshellarg($options['submoduleTagNamePrefix'] . $options['tagName'])));
            $this->shell->executeOrSimulate(sprintf('cd ' . $targetPath . '; git submodule foreach %s', $submoduleCommand), $node, $deployment);
        }

        if (isset($options['pushTag']) && $options['pushTag'] === true) {
            $this->shell->executeOrSimulate(sprintf('cd ' . $targetPath . '; git push %s %s', escapeshellarg($options['remote']), escapeshellarg($options['tagName'])), $node, $deployment);
            if (isset($options['recurseIntoSubmodules']) && $options['recurseIntoSubmodules'] === true) {
                $submoduleCommand = escapeshellarg(sprintf('git push %s %s', escapeshellarg($options['remote']), escapeshellarg($options['submoduleTagNamePrefix'] . $options['tagName'])));
                $this->shell->executeOrSimulate(sprintf('cd ' . $targetPath . '; git submodule foreach %s', $submoduleCommand), $node, $deployment);
            }
        }
    }
502640
def switch(stage):
    
    stage = stage.lower()
    local("git pull")
    if stage in ['dev', 'devel', 'develop']:
        branch_name = 'develop'
    elif stage in ['qa', 'release']:
        branches = local('git branch -r', capture=True)
        possible_branches = []
        for b in branches.split("\n"):
            b_parts = b.split('/')
            if b_parts[1] == 'release':
                possible_branches.append(b_parts[2])
        if len(possible_branches) == 0:
            raise Exception('No release branches found. Please create a new release first.')
        possible_branches = sorted(possible_branches, reverse=True)
        branch_name = 'release/%s' % possible_branches[0]
    elif stage in ['production', 'master']:
        branch_name = 'master'
    else:
        raise NotImplemented
    local("git checkout %s" % branch_name)
    local("git pull")
1220858
protected function getBranchSpecificPlugins(&$config, $stage, $pluginsToExecute)
    {
        /** @var \PHPCI\Model\Build $build */
        $build = $this->pluginFactory->getResourceFor('PHPCI\Model\Build');
        $branch = $build->getBranch();

        // If we don't have any branch-specific plugins:
        if (!isset($config['branch-' . $branch][$stage]) || !is_array($config['branch-' . $branch][$stage])) {
            return $pluginsToExecute;
        }

        // If we have branch-specific plugins to execute, add them to the list to be executed:
        $branchConfig = $config['branch-' . $branch];
        $plugins = $branchConfig[$stage];

        $runOption = 'after';

        if (!empty($branchConfig['run-option'])) {
            $runOption = $branchConfig['run-option'];
        }

        switch ($runOption) {
            // Replace standard plugin set for this stage with just the branch-specific ones:
            case 'replace':
                $pluginsToExecute = array();
                $pluginsToExecute[] = $plugins;
                break;

            // Run branch-specific plugins before standard plugins:
            case 'before':
                array_unshift($pluginsToExecute, $plugins);
                break;

            // Run branch-specific plugins after standard plugins:
            case 'after':
                array_push($pluginsToExecute, $plugins);
                break;

            default:
                array_push($pluginsToExecute, $plugins);
                break;
        }

        return $pluginsToExecute;
    }
98226
public function install($version, $stage = null)
    {
        $deploymentStrategy = $this->getContainer()->get('deployment_strategy');

        $result = $deploymentStrategy->install($version, $stage);

        $this->dispatch(AccompliEvents::INSTALL_COMMAND_COMPLETE);

        return $result;
    }
268849
public function set_deploy($preview_server_name, $to_branch) {

		$current_dir = realpath('.');

		$output = "";
		$result = array('status' => true,
						'message' => '');

		$server_list = $this->main->options->preview_server;
		array_push($server_list, json_decode(json_encode(array(
			'name'=>'master',
			'path'=>$this->main->options->git->repository,
		))));

		set_time_limit(0);
		
		foreach ( $server_list as $preview_server ) {
			chdir($current_dir);

			try {

				if ( trim($preview_server->name) == trim($preview_server_name) ) {

					$to_branch_rep = trim(str_replace("origin/", "", $to_branch));

					// ディレクトリ移動
					if ( chdir( $preview_server->path ) ) {

						// 現在のブランチ取得
						exec( 'git branch', $output);

						$now_branch;
						$already_local_branch_exists = false;
						foreach ( $output as $value ) {

							// 「*」の付いてるブランチを現在のブランチと判定
							if ( strpos($value, '*') !== false ) {

								$value = trim(str_replace("* ", "", $value));
								$now_branch = $value;

							} else {

								$value = trim($value);

							}

							// 選択された(切り替える)ブランチがブランチの一覧に含まれているか判定
							if ( $value == $to_branch_rep ) {
								$already_local_branch_exists = true;
							}
						}

						// git fetch
						exec( 'git fetch origin', $output );

						// 現在のブランチと選択されたブランチが異なる場合は、ブランチを切り替える
						if ( $now_branch !== $to_branch_rep ) {

							if ($already_local_branch_exists) {
								// 選択された(切り替える)ブランチが既にチェックアウト済みの場合

								exec( 'git checkout ' . escapeshellarg($to_branch_rep), $output);

							} else {
								// 選択された(切り替える)ブランチがまだチェックアウトされてない場合

								exec( 'git checkout -b ' . escapeshellarg($to_branch_rep) . ' ' . escapeshellarg($to_branch), $output);
							}
						}

						// git pull
						exec( 'git pull origin ' . escapeshellarg($to_branch_rep), $output );

					} else {
						// プレビューサーバのディレクトリが存在しない場合

						// エラー処理
						throw new \Exception('Preview server directory not found.');
					}

				}

			} catch (\Exception $e) {
				set_time_limit(30);

				$result['status'] = false;
				$result['message'] = $e->getMessage();

				chdir($current_dir);
				return $result;
			}

		}
		set_time_limit(30);

		$result['status'] = true;

		chdir($current_dir);
		return $result;
		
	}
861349
public static function show(array $data, array $opts = []): void
    {
        static $counter = 0;
        static $started = 1;

        if ($started) {
            $started = 0;
            $opts    = \array_merge([
                // 'char' => Cli::isSupportColor() ? '─' : '-', // ——
                'char'        => '-',
                'prefix'      => Cli::isSupportColor() ? '├' : '|',
                'leftPadding' => '',
            ], $opts);

            $opts['_level']   = 1;
            $opts['_is_main'] = true;

            Console::startBuffer();
        }

        foreach ($data as $key => $value) {
            if (\is_scalar($value)) {
                $counter++;
                $leftString = $opts['leftPadding'] . \str_pad($opts['prefix'], $opts['_level'] + 1, $opts['char']);

                Console::write($leftString . ' ' . FormatUtil::typeToString($value));
            } elseif (\is_array($value)) {
                $newOpts             = $opts;
                $newOpts['_is_main'] = false;
                $newOpts['_level']++;

                self::show($value, $newOpts);
            }
        }

        if ($opts['_is_main']) {
            Console::write('node count: ' . $counter);
            // var_dump('f');
            Console::flushBuffer();

            // reset.
            $counter = $started = 0;
        }
    }
1050034
protected function rsyncExec($command, $error_msg = 'Rsync has failed')
	{
		$this->log('execRSync: '. $command, LOG_DEBUG);

		chdir($this->basedir);

		passthru($command, $return);

		$this->log('');

		if ($return !== 0) {
			throw new DeployException($error_msg);
		}
	}
617116
public function execute(Node $node, Application $application, Deployment $deployment, array $options = [])
    {
        if (empty($options['branch']) || !empty($options['tag'])) {
            return;
        }

        $quietFlag = (isset($options['verbose']) && $options['verbose']) ? '' : '-q';

        $commands = [];
        $commands[] = 'cd '.escapeshellarg($deployment->getApplicationReleasePath($application));
        $commands[] = 'if [ -d \'.git\' ] && hash git 2>/dev/null; then '.
            'git branch -f '.escapeshellarg($options['branch']).' deploy && '.
            'git checkout '.$quietFlag.' '.escapeshellarg($options['branch']).' && '.
            'git branch -D deploy; '.
            'fi;';

        $this->shell->executeOrSimulate($commands, $node, $deployment);
    }
223326
public void deploy(final DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
        final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
        final ModuleSpecification moduleSpecification = deploymentUnit.getAttachment(Attachments.MODULE_SPECIFICATION);

        moduleSpecification.addUserDependencies(deploymentUnit.getAttachmentList(Attachments.MANIFEST_DEPENDENCIES));

        if (deploymentUnit.getParent() != null) {
            // propagate parent manifest dependencies
            final List<ModuleDependency> parentDependencies = deploymentUnit.getParent().getAttachmentList(Attachments.MANIFEST_DEPENDENCIES);
            moduleSpecification.addUserDependencies(parentDependencies);
        }
    }
619542
protected function executeCliCommand(array $cliArguments, Node $node, CMS $application, Deployment $deployment, array $options = [])
    {
        $this->determineWorkingDirectoryAndTargetNode($node, $application, $deployment, $options);
        $phpBinaryPathAndFilename = isset($options['phpBinaryPathAndFilename']) ? $options['phpBinaryPathAndFilename'] : 'php';
        $commandPrefix = '';
        if (isset($options['context'])) {
            $commandPrefix = 'TYPO3_CONTEXT=' . escapeshellarg($options['context']) . ' ';
        }
        $commandPrefix .= $phpBinaryPathAndFilename . ' ';

        $this->determineWorkingDirectoryAndTargetNode($node, $application, $deployment, $options);

        return $this->shell->executeOrSimulate([
            'cd ' . escapeshellarg($this->workingDirectory),
            $commandPrefix . implode(' ', array_map('escapeshellarg', $cliArguments))
        ], $this->targetNode, $deployment);
    }
266458
private static void addRedeployOperationStep(final CompositeOperationBuilder builder, final DeploymentDescription deployment) {
        final String deploymentName = deployment.getName();
        final Set<String> serverGroups = deployment.getServerGroups();
        if (serverGroups.isEmpty()) {
            builder.addStep(createOperation(DEPLOYMENT_REDEPLOY_OPERATION, createAddress(DEPLOYMENT, deploymentName)));
        } else {
            for (String serverGroup : serverGroups) {
                builder.addStep(createOperation(DEPLOYMENT_REDEPLOY_OPERATION, createAddress(SERVER_GROUP, serverGroup, DEPLOYMENT, deploymentName)));
            }
        }
    }
581883
public function writeToStage($stage, $forceInsert = false)
    {
        ReadingMode::validateStage($stage);
        $owner = $this->owner;
        return static::withVersionedMode(function () use ($stage, $forceInsert, $owner) {
            $oldParams = $owner->getSourceQueryParams();
            try {
                // Lazy load and reset version in current stage prior to resetting write stage
                $owner->forceChange();
                $owner->Version = null;

                // Migrate stage prior to write
                Versioned::set_stage($stage);
                $owner->setSourceQueryParam('Versioned.mode', 'stage');
                $owner->setSourceQueryParam('Versioned.stage', $stage);

                // Write
                $owner->invokeWithExtensions('onBeforeWriteToStage', $toStage, $forceInsert);
                return $owner->write(false, $forceInsert);
            } finally {
                // Revert global state
                $owner->invokeWithExtensions('onAfterWriteToStage', $toStage, $forceInsert);
                $owner->setSourceQueryParams($oldParams);
            }
        });
    }