Deployment git build repo.

@param bool $throw_exception

@return string
192517
protected function gitRepo($throw_exception = true)
    {
        $options = $this->getOptions();

        $repo = isset($options['repo_url'])
            ? $options['repo_url']
            : null;

        if (!isset($repo) && $throw_exception) {
            throw new DeploymentRuntimeException(
                'Missing Git repository in deploy options.'
            );
        }

        return $repo;
    }
20813
public function main()
    {
        if (null === $this->getRepository()) {
            throw new BuildException('"repository" is required parameter');
        }

        $client = $this->getGitClient(false, $this->getRepository());
        $command = $client->getCommand('fetch');
        $command
            ->setOption('tags', $this->isTags())
            ->setOption('no-tags', $this->isNoTags())
            ->setOption('prune', $this->isPrune())
            ->setOption('keep', $this->isKeepFiles())
            ->setOption('q', $this->isQuiet())
            ->setOption('force', $this->isForce());

        // set operation target
        if ($this->isAllRemotes()) { // --all
            $command->setOption('all', true);
        } elseif ($this->getGroup()) { // <group>
            $command->addArgument($this->getGroup());
        } elseif ($this->getSource()) { // <repository> [<refspec>]
            $command->addArgument($this->getSource());
            if ($this->getRefspec()) {
                $command->addArgument($this->getRefspec());
            }
        } else {
            throw new BuildException('No remote repository specified');
        }

        $this->log('git-fetch command: ' . $command->createCommandString(), Project::MSG_INFO);

        try {
            $output = $command->execute();
        } catch (Exception $e) {
            throw new BuildException('Task execution failed.', $e);
        }

        $this->log(
            sprintf('git-fetch: branch "%s" repository', $this->getRepository()),
            Project::MSG_INFO
        );
        $this->log('git-fetch output: ' . trim($output), Project::MSG_INFO);
    }
606216
public function get_api_release_asset( $git, $request ) {
		$response = isset( $this->response['release_asset'] ) ? $this->response['release_asset'] : false;

		if ( $response && $this->exit_no_update( $response ) ) {
			return false;
		}

		if ( ! $response ) {
			self::$method = 'release_asset';
			$response     = $this->api( $request );
			$response     = $this->parse_release_asset( $git, $request, $response );

			if ( ! $response && ! is_wp_error( $response ) ) {
				$response          = new \stdClass();
				$response->message = 'No release asset found';
			}
		}

		if ( $response && ! isset( $this->response['release_asset'] ) ) {
			$this->set_repo_cache( 'release_asset', $response );
		}

		if ( $this->validate_response( $response ) ) {
			return false;
		}

		return $response;
	}
312867
private function initializeRemotePath($skipSync)
    {
        $this->repoDir = $this->config->get('cache-vcs-dir').'/'.preg_replace('{[^a-z0-9.]}i', '-', $this->url).'/';

        GitUtil::cleanEnv();

        $fs = new Filesystem();
        $fs->ensureDirectoryExists(\dirname($this->repoDir));

        if (!is_writable(\dirname($this->repoDir))) {
            throw new \RuntimeException('Can not clone '.$this->url.' to access package information. The "'.\dirname($this->repoDir).'" directory is not writable by the current user.');
        }

        if (preg_match('{^ssh://[^@]+@[^:]+:[^0-9]+}', $this->url)) {
            throw new \InvalidArgumentException('The source URL '.$this->url.' is invalid, ssh URLs should have a port number after ":".'."\n".'Use ssh://git@example.com:22/path or just git@example.com:path if you do not want to provide a password or custom port.');
        }

        $gitUtil = new GitUtil($this->io, $this->config, $this->process, $fs);
        // patched line, sync from local dir without modifying url
        if (!$skipSync && !$gitUtil->syncMirror($this->url, $this->repoDir)) {
            $this->io->writeError('<error>Failed to update '.$this->url.', package information from this repository may be outdated</error>');
        }

        return $this->url;
    }
1116675
public function buildOperationList()
    {
        $this->log('Building install/update operations list...');
        $current = $this->versionManager->openRepository($this->installedRepoFile);

        foreach ($current->getCanonicalPackages() as $currentPackage) {
            $extra = $currentPackage->getExtra();
            //this is a meta package if the bundles key exists
            if (array_key_exists('bundles', $extra)) {
                //this is only valid for installable bundles
                $bundles = array_filter($extra['bundles'], function ($var) {
                    try {
                        return in_array('Claroline\InstallationBundle\Bundle\InstallableInterface', class_implements($var)) ? true : false;
                    } catch (\Exception $e) {
                        $this->log($var.' not found.', LogLevel::ERROR);

                        return false;
                    }
                });

                foreach ($bundles as $bundle) {
                    //if the corebundle is already installed, we can do database checks to be sure a plugin is already installed
                    //and not simply set to false in bundles.ini in previous versions.
                    $foundBundle = $this->isBundleAlreadyInstalled($bundle);

                    $previousPackage = $this->findPreviousPackage($bundle);

                    if ($foundBundle && $previousPackage) {
                        $isDistribution = 'claroline/distribution' === $currentPackage->getName();
                        $fromVersionEntity = $this->versionManager->getLatestUpgraded($bundle);
                        $toVersion = $this->versionManager->getCurrent();

                        if ($isDistribution && $fromVersionEntity && $toVersion) {
                            if ($fromVersionEntity->getVersion() === $toVersion && $fromVersionEntity->isUpgraded()) {
                                $this->log('Package '.$bundle.'already upgraded to the '.$toVersion.'version. Skipping...');
                            } else {
                                $operations[$bundle] = new Operation(Operation::UPDATE, $currentPackage, $bundle);
                                $operations[$bundle]->setFromVersion($fromVersionEntity->getVersion());
                                $operations[$bundle]->setToVersion($toVersion);
                            }
                            //old update <= v10
                        } else {
                            $operations[$bundle] = new Operation(Operation::UPDATE, $currentPackage, $bundle);
                            $operations[$bundle]->setFromVersion($previousPackage->getVersion());
                            $operations[$bundle]->setToVersion($currentPackage->getVersion());
                        }
                    } else {
                        //if we found something in the database, it means it was removed from composer.json and not properly uninstalled
                        if ($foundBundle) {
                            $operations[$bundle] = new Operation(Operation::UPDATE, $currentPackage, $bundle);
                            //we don't know wich version it came from so we trigger everything, we only know it's already here
                            $operations[$bundle]->setFromVersion('0.0.0');
                            $operations[$bundle]->setToVersion($currentPackage->getVersion());
                        } else {
                            $operations[$bundle] = new Operation(Operation::INSTALL, $currentPackage, $bundle);
                        }
                    }
                }
            } else {
                $previous = $this->versionManager->openRepository($this->previousRepoFile, true);
                $previousPackage = $previous->findPackage($currentPackage->getName(), '*');
                //old <= v6 package detection
                if (!$previousPackage) {
                    $this->log("Installation of {$currentPackage->getName()} required");
                    $operation = $this->buildOperation(Operation::INSTALL, $currentPackage);
                    $operation->setToVersion($currentPackage->getVersion());
                    $operations[$operation->getBundleFqcn()] = $operation;
                } else {
                    $this->log(sprintf(
                        'Update of %s from %s to %s required',
                        $previousPackage->getName(),
                        $previousPackage->getVersion(),
                        $currentPackage->getVersion()
                    ));
                    $operation = $this->buildOperation(Operation::UPDATE, $currentPackage);
                    $operation->setFromVersion($previousPackage->getVersion());
                    $operation->setToVersion($currentPackage->getVersion());
                    $operations[$operation->getBundleFqcn()] = $operation;
                }
            }
        }

        // TODO: we *should* do something in case a platform package is
        // removed (e.g. if the package is a plugin, at least unregister it)
        // but AFAIK we don't have anything now to support removal of a bundle
        // whose sources are already gone. Maybe the platform installer could
        // look after each update if there are records in the plugin table
        // that don't match any known bundle?

        $this->log('Sorting operations...');
        $bundles = $this->kernel->getBundles();
        $sortedOperations = [];

        foreach ($bundles as $bundle) {
            $bundleClass = $bundle->getNamespace() ?
                $bundle->getNamespace().'\\'.$bundle->getName() :
                $bundle->getName();

            if (isset($operations[$bundleClass])) {
                $sortedOperations[] = $operations[$bundleClass];
            }
        }

        return $sortedOperations;
    }
924305
@SuppressWarnings("PMD")
    private List<RepoBranch> getGitRepoBranch(JSONObject buildJson) {
        List<RepoBranch> list = new ArrayList<>();        
        
        JSONArray actions = getJsonArray(buildJson, "actions");
        for (Object action : actions) {
            JSONObject jsonAction = (JSONObject) action;
            if (jsonAction.size() > 0) {
                JSONObject lastBuiltRevision = null;
                JSONArray branches = null;
                JSONArray remoteUrls = getJsonArray ((JSONObject) action, "remoteUrls");       
                if (!remoteUrls.isEmpty()) {
                	lastBuiltRevision = (JSONObject) jsonAction.get("lastBuiltRevision");
                }
                if (lastBuiltRevision != null) {
                	branches = getJsonArray (lastBuiltRevision, "branch");
                }
                // As of git plugin 3.0.0, when multiple repos are configured in the git plugin itself instead of MultiSCM plugin, 
            	// they are stored unordered in a HashSet. So it's buggy and we cannot associate the correct branch information.
                // So for now, we loop through all the remoteUrls and associate the built branch(es) with all of them.
                if (branches != null && !branches.isEmpty()) {
                	for (Object url : remoteUrls) {
                		String sUrl = (String) url;
                		if (sUrl != null && !sUrl.isEmpty()) {
                			sUrl = removeGitExtensionFromUrl(sUrl);
		                	for (Object branchObj : branches) {
		                		String branchName = getString((JSONObject) branchObj, "name");
		                		if (branchName != null) {
		                			String unqualifiedBranchName = getUnqualifiedBranch(branchName);
		                			RepoBranch grb = new RepoBranch(sUrl, unqualifiedBranchName, RepoBranch.RepoType.GIT);
		                			list.add(grb);
		                		}
		                	}
                		}
                	}
                }
            }
        }
        return list;
    }
158974
public function get_remote_repo_meta( $repo ) {
		$file = 'style.css';
		if ( false !== stripos( $repo->type, 'plugin' ) ) {
			$file = basename( $repo->file );
		}

		$repo_api = Singleton::get_instance( 'API', $this )->get_repo_api( $repo->git, $repo );
		if ( null === $repo_api ) {
			return false;
		}

		$this->{$repo->type} = $repo;
		$this->set_defaults( $repo->type );

		if ( $repo_api->get_remote_info( $file ) ) {
			if ( ! self::is_wp_cli() ) {
				if ( ! apply_filters( 'github_updater_run_at_scale', false ) ) {
					$repo_api->get_repo_meta();
					$changelog = $this->get_changelog_filename( $repo );
					if ( $changelog ) {
						$repo_api->get_remote_changes( $changelog );
					}
					$repo_api->get_remote_readme();
				}
				if ( ! empty( self::$options['branch_switch'] ) ) {
					$repo_api->get_remote_branches();
				}
			}
			$repo_api->get_remote_tag();
			$repo->download_link = $repo_api->construct_download_link();
			$language_pack       = new Language_Pack( $repo, new Language_Pack_API( $repo ) );
			$language_pack->run();
		}

		$this->remove_hooks( $repo_api );

		return true;
	}
230443
private void doCleanBranch() throws Exception {
        Path repo = getSiteDir();
        copySite(repo);

        initRepo(repo);

        createCommit(repo);
        pushBranch(repo, "master", true);
    }
323397
static public function askForUserConfirmation(bool $throwException = false): bool {
		echo "\n######################################################\n\n";
		echo "Are you sure that you want to import data to the following instance?! \n\n ";
		echo "Type 'yes' to continue! \n\n";
		echo self::get('sparqlUrl') . "\n";
		echo self::get('fedoraApiUrl') . "\n";
		$handle = fopen ("php://stdin","r");
		$line = trim(fgets($handle));
		fclose($handle);
		if ($line !== 'yes' && $throwException) {
			throw new RuntimeException('Configuration revoked by the user');
		}
		return $line === 'yes';
	}
196338
public function deployCode(
        string $buildId = null,
        string $buildPath = null,
        string $repoReference = null
    ): void {
        if (!($buildId || $repoReference)) {
            throw new Exception\BadMethodCallException('$buildId or $repoReference must be set.');
        }

        if ($buildId) {
            $this->deployFromBuild($buildId, $buildPath);
        } else {
            $this->deployFromRepo($repoReference);
        }
    }
232865
public function construct_download_link( $branch_switch = false ) {
		self::$method       = 'download_link';
		$download_link_base = $this->get_api_url( '/repos/:owner/:repo/zipball/', true );
		$endpoint           = '';

		// Release asset.
		if ( $this->type->release_asset && '0.0.0' !== $this->type->newest_tag ) {
			$release_asset = $this->get_release_asset();
			if ( property_exists( $this->type, 'is_private' ) && $this->type->is_private ) {
				return $this->get_release_asset_redirect( $release_asset, true );
			}
			return $release_asset;
		}

		/*
		 * If a branch has been given, use branch.
		 * If branch is master (default) and tags are used, use newest tag.
		 */
		if ( 'master' !== $this->type->branch || empty( $this->type->tags ) ) {
			$endpoint .= $this->type->branch;
		} else {
			$endpoint .= $this->type->newest_tag;
		}

		// Create endpoint for branch switching.
		if ( $branch_switch ) {
			$endpoint = $branch_switch;
		}

		$endpoint      = $this->add_access_token_endpoint( $this, $endpoint );
		$download_link = $download_link_base . $endpoint;

		/**
		 * Filter download link so developers can point to specific ZipFile
		 * to use as a download link during a branch switch.
		 *
		 * @since 8.8.0
		 *
		 * @param string    $download_link Download URL.
		 * @param /stdClass $this->type    Repository object.
		 * @param string    $branch_switch Branch or tag for rollback or branch switching.
		 */
		return apply_filters( 'github_updater_post_construct_download_link', $download_link, $this->type, $branch_switch );
	}
678792
protected function getGithubForm()
    {
        $form = new Form();
        $form->setMethod('POST');
        $form->setAction(PHPCI_URL . 'settings/github');
        $form->addField(new Form\Element\Csrf('csrf'));

        $field = new Form\Element\Text('githubid');
        $field->setRequired(true);
        $field->setPattern('[a-zA-Z0-9]+');
        $field->setLabel(Lang::get('application_id'));
        $field->setClass('form-control');
        $field->setContainerClass('form-group');
        $form->addField($field);

        if (isset($this->settings['phpci']['github']['id'])) {
            $field->setValue($this->settings['phpci']['github']['id']);
        }

        $field = new Form\Element\Text('githubsecret');
        $field->setRequired(true);
        $field->setPattern('[a-zA-Z0-9]+');
        $field->setLabel(Lang::get('application_secret'));
        $field->setClass('form-control');
        $field->setContainerClass('form-group');
        $form->addField($field);

        if (isset($this->settings['phpci']['github']['secret'])) {
            $field->setValue($this->settings['phpci']['github']['secret']);
        }

        $field = new Form\Element\Submit();
        $field->setValue(Lang::get('save'));
        $field->setClass('btn btn-success pull-right');
        $form->addField($field);

        return $form;
    }
276031
public function subsplitUpdate()
    {
        $repo = $this->getRepository();
        $this->log('git-subsplit update...');
        $cmd = $this->client->getCommand('subsplit');
        $cmd->addArgument('update');
        try {
            $cmd->execute();
        } catch (Exception $e) {
            throw new BuildException('git subsplit update failed'. $e);
        }
        chdir($repo . '/.subsplit');
        passthru('php ../composer.phar update --dev');
        chdir($repo);
    }
400665
def _get_repo():
    """"""
    command = ['git', 'rev-parse', '--show-toplevel']
    if six.PY2:
        try:
            return check_output(command).decode('utf-8').strip()    # nosec
        except CalledProcessError:
            return ''
    else:
        return (run(command, stdout=PIPE, stderr=PIPE)
                .stdout.decode('utf-8').strip())
173216
public function main()
    {
        if (null === $this->getRepository()) {
            throw new BuildException('"repository" is required parameter');
        }

        $client = $this->getGitClient(false, $this->getRepository());
        $command = $client->getCommand('describe');
        $command
            ->setOption('all', $this->isAll())
            ->setOption('tags', $this->isTags())
            ->setOption('contains', $this->isContains())
            ->setOption('long', $this->isLong())
            ->setOption('always', $this->isAlways());

        if (null !== $this->getAbbrev()) {
            $command->setOption('abbrev', $this->getAbbrev());
        }
        if (null !== $this->getCandidates()) {
            $command->setOption('candidates', $this->getCandidates());
        }
        if (null !== $this->getMatch()) {
            $command->setOption('match', $this->getMatch());
        }
        if (null !== $this->getCommittish()) {
            $command->addArgument($this->getCommittish());
        }

        try {
            $output = $command->execute();
        } catch (Exception $e) {
            throw new BuildException('Task execution failed');
        }

        if (null !== $this->outputProperty) {
            $this->project->setProperty($this->outputProperty, $output);
        }

        $this->log(
            sprintf('git-describe: recent tags for "%s" repository', $this->getRepository()),
            Project::MSG_INFO
        );
        $this->log('git-describe output: ' . trim($output), Project::MSG_INFO);
    }
687833
public static function get_by_package($package_name = 'project') {
		if (!file_exists(Config::$migration_directory)) {
			throw new \Exception('Config::$migration_directory is not set to a valid directory');
		}

		/**
		 * Array with results
		 */
		$migrations = [];

		if ($package_name == 'project') {
			$files = scandir(Config::$migration_directory, SCANDIR_SORT_ASCENDING);

			foreach ($files as $key => $file) {
				if ($file[0] == '.') {
					unset($files[$key]);
					continue;
				}

				if ($file == 'db_version') {
					unset($files[$key]);
					continue;
				}

				if (!preg_match("/^\d{8}_\d{6}_.*$/", $file)) {
					unset($files[$key]);
					continue;
				}


				$parts = explode('_', $file);
				foreach ($parts as $key => $part) {
					$parts[$key] = ucfirst($part);
				}

				$classname = 'Migration_' . str_replace('.php', '', implode('_', $parts));
				include_once Config::$migration_directory . '/' . $file;
				$migrations[] = new $classname();
			}
		} else {

			/**
			 * Make a list of all migrations to be execute
			 */
			$packages = \Skeleton\Core\Skeleton::get_all();

			foreach ($packages as $package) {
				if ($package->name != $package_name) {
					continue;
				}
				if (!file_exists($package->migration_path)) {
					continue;
				}
				$files = scandir($package->migration_path, SCANDIR_SORT_ASCENDING);

				foreach ($files as $key => $file) {
					if ($file[0] == '.') {
						unset($files[$key]);
						continue;
					}

					if ($file == 'db_version') {
						unset($files[$key]);
						continue;
					}

					if (!preg_match("/^\d{8}_\d{6}_.*$/", $file)) {
						unset($files[$key]);
						continue;
					}


					$parts = explode('_', $file);
					foreach ($parts as $key => $part) {
						$parts[$key] = ucfirst($part);
					}

					$namespace_parts = explode('-', $package->name);
					foreach ($namespace_parts as $key => $namespace_part) {
						$namespace_parts[$key] = ucfirst($namespace_part);
					}
					$namespace = implode('\\', $namespace_parts);

					$classname = $namespace . '\Migration_' . str_replace('.php', '', implode('_', $parts));
					include_once $package->migration_path . '/' . $file;
					$migrations[] = new $classname();
				}
			}
		}


		return $migrations;
	}
243690
def git_rebuild(repo, options = {})
      ensure_ready!(:authorization)
      url = "#{git_repo_path(repo)}/builds"
      api = connection(:api_format => :text)
      checked_response_body(api.post(url, options))
    end