Initialize GitLab by getting base branch
169305
async function initRepo({
  repository,
  endpoint,
  gitPrivateKey,
  gitFs,
  localDir,
}) {
  logger.debug(
    `initRepo("${JSON.stringify(
      { repository, endpoint, gitFs, localDir },
      null,
      2
    )}")`
  );
  const opts = hostRules.find({ platform }, { endpoint });
  // istanbul ignore if
  if (!(opts.username && opts.password)) {
    throw new Error(
      `No username/password found for Bitbucket repository ${repository}`
    );
  }
  // istanbul ignore if
  if (!opts.endpoint) {
    throw new Error(`No endpoint found for Bitbucket Server`);
  }
  hostRules.update({ ...opts, platform, default: true });
  api.reset();

  const [projectKey, repositorySlug] = repository.split('/');
  config = { projectKey, repositorySlug, gitPrivateKey };

  // Always gitFs
  const { host, pathname } = url.parse(opts.endpoint);
  const gitUrl = GitStorage.getUrl({
    gitFs: gitFs || 'https',
    auth: `${opts.username}:${opts.password}`,
    host: `${host}${pathname}${pathname.endsWith('/') ? '' : '/'}scm`,
    repository,
  });

  config.storage = new GitStorage();
  await config.storage.initRepo({
    ...config,
    localDir,
    url: gitUrl,
  });

  const platformConfig = {};

  try {
    const info = (await api.get(
      `./rest/api/1.0/projects/${config.projectKey}/repos/${
        config.repositorySlug
      }`
    )).body;
    platformConfig.privateRepo = info.is_private;
    platformConfig.isFork = !!info.parent;
    platformConfig.repoFullName = info.name;
    config.owner = info.project.key;
    logger.debug(`${repository} owner = ${config.owner}`);
    config.defaultBranch = (await api.get(
      `./rest/api/1.0/projects/${config.projectKey}/repos/${
        config.repositorySlug
      }/branches/default`
    )).body.displayId;
    config.baseBranch = config.defaultBranch;
    config.mergeMethod = 'merge';
  } catch (err) /* istanbul ignore next */ {
    logger.debug(err);
    if (err.statusCode === 404) {
      throw new Error('not-found');
    }
    logger.info({ err }, 'Unknown Bitbucket initRepo error');
    throw err;
  }
  delete config.prList;
  delete config.fileList;
  logger.debug(
    { platformConfig },
    `platformConfig for ${config.projectKey}/${config.repositorySlug}`
  );
  return platformConfig;
}
772787
public function init() {
    $git_repo = exec('basename `git rev-parse --show-toplevel`');

    // Remove instructions for creating a new repo, because we've got one now.
    $readme_contents = file_get_contents('README.md');
    $start_string = '### Initial build (new repo)';
    $end_string = '### Initial build (existing repo)';
    $from = $this->findAllTextBetween($start_string, $end_string, $readme_contents);

    $find_replaces = array(
      array(
        'source' => 'composer.json',
        'from' => '"name": "thinkshout/drupal-project",',
        'to' => '"name": "thinkshout/' . $git_repo . '",',
      ),
      array(
        'source' => '.env.dist',
        'from' => 'TS_PROJECT="SITE"',
        'to' => 'TS_PROJECT="' . $git_repo . '"',
      ),
      array(
        'source' => 'README.md',
        'from' => array($from, 'new-project-name'),
        'to' => array($end_string, $git_repo),
      ),
    );

    foreach ($find_replaces as $find_replace) {
      $this->taskReplaceInFile($find_replace['source'])
        ->from($find_replace['from'])
        ->to($find_replace['to'])
        ->run();
    }
  }
572171
function initScaffold(fis) {
    fis.set('scaffold.namespace', 'tfux-scaffold');
    fis.set('scaffold.gitlabDomain', DEFAULT_GITLAB_DOMAIN);
    fis.set('scaffold.gitlabToken', process.env.GITLAB_TOKEN || 'XsYDeyqyFD777qgovh15');
}
1286740
public function init($path = null)
    {
        $path = is_null($path) ? $this->environment->path : $path;

        // Check if clone already exists at this path. If so we can safely skip.
        if (file_exists($path)) {
            $wrapper = new GitWrapper();
            $wrapper->setTimeout(3600);

            try {
                $working_copy = new GitWorkingCopy($wrapper, $path);
                $output = $working_copy->remote('-v');
            } catch (GitException $e) {
                throw new \Exception('Path already exists.');
            }

            // if repo exists in the remotes already, this working copy is ok.
            if (strpos(strtolower($output), strtolower($this->app->repo)) !== false) {
                return true;
            } else {
                throw new Exception('Git clone already exists at that path, but it is not for this app.');
            }
        }

        try {
            // Create App folder
            mkdir($path, 0755, TRUE);
            chdir($path);

            // Clone repo
            $wrapper = new GitWrapper();
            $wrapper->setTimeout(3600);
            $wrapper->streamOutput();
            $wrapper->cloneRepository($this->app->repo, $path);

            // Checkout correct version.
            $git = new GitWorkingCopy($wrapper, $this->getSourcePath());
            $git->checkout($this->environment->version);

        } catch (\GitWrapper\GitException $e) {

            // If exception is because there is no git ref, continue.
            if (strpos($e->getMessage(), 'error: pathspec') !== 0) {
                return false;
            }
        }

        chdir($path);
        $wrapper->git('branch');
        $wrapper->git('status');
        $this->loadConfig();

        // Run the build hooks
        if (!empty($this->config['hooks']['build'])) {
            chdir($this->getSourcePath());
            $process = new Process($this->config['hooks']['build']);
            $process->run(function ($type, $buffer) {
                if (Process::ERR === $type) {
                    echo $buffer;
                } else {
                    echo $buffer;
                }
            });
        }

        return $this->writeConfig();
    }
515660
def _get_branch(self, remotes=False):
        '''
        
        '''

        return self.m(
            'getting git branch information',
            cmdd=dict(
                cmd='git branch %s' % ('-r' if remotes else ''),
                cwd=self.local
            ),
            verbose=False
        )
946828
function _initBranch(branchToken) {
  const [, keyword, name, remainder] = branchToken.match(BRANCH_REGEX);

  return {
    name: name.toLowerCase(),
    keyword,
    params: _parseParams(remainder),
    fields: {},
  };
}
76257
def get_default_branch(repo):
    """"""
    url = "{}/repos/{}".format(GITHUB_API_BASE, repo)
    response = requests.get(url)
    if response.status_code == 200:
        api_response = json.loads(response.text)
        return api_response['default_branch']
    else:
        return 'master'
1287942
public function actionInit()
    {
        // username
        $username = $this->getConfig(self::CONFIG_VAR_USERNAME);
        if (!$username) {
            $username = $this->prompt('Whats your Github username?');
            $this->saveConfig(self::CONFIG_VAR_USERNAME, $username);
        }
        
        // clonetype
        $cloneType = $this->getConfig(self::CONFIG_VAR_CLONETYPE);
        if (!$cloneType) {
            $cloneType = $this->select('Are you connected via ssh or https?', ['ssh' => 'ssh', 'http' => 'http']);
            $this->saveConfig(self::CONFIG_VAR_CLONETYPE, $cloneType);
        }
        
        $summary = [];
        $itemWithoutFork = false;
        
        // generate summary overview
        foreach ($this->repos as $repo) {
            $newRepoHome = $this->getFilesystemRepoPath($repo);
            if (file_exists($newRepoHome . DIRECTORY_SEPARATOR . '.git')) {
                $summary[] = $this->summaryItem($repo, false, true);
            } elseif ($this->forkExists($username, $repo)) {
                $summary[] = $this->summaryItem($repo, true, false);
            } else {
                $itemWithoutFork = true;
                $summary[] = $this->summaryItem($repo, false, false);
            }
        }
        
        if ($itemWithoutFork) {
            Console::clearScreen();
            $this->outputInfo($this->markdown($this->text));
            foreach ($summary as $sum) {
                if (!$sum[2] && !$sum[1]) {
                    $this->outputInfo($this->markdown("**{$sum[0]}**: https://github.com/luyadev/{$sum[0]}/fork", true));
                }
            }
            echo (new Table())->setHeaders(['Repo', 'Already initialized', 'Fork exists'])->setRows($summary)->run();
            $this->outputError("Repos without fork detected. Those repos will be initialized as READ ONLY. It means you can not push any changes to them.");
            
            if (!$this->confirm("Continue?")) {
                return $this->outputError('Abort by User.');
            }
        }
        
        // foreach summary and clone
        foreach ($summary as $sum) {
            $repo = $sum[0];
            $hasFork = $sum[2];
            $exists = $sum[1];
            
            // continue already initialized repos.
            if ($exists) {
                continue;
            }
            
            $newRepoHome = $this->getFilesystemRepoPath($repo);
            
            if ($hasFork) {
                $cloneUrl = ($cloneType == 'ssh') ? "git@github.com:{$username}/{$repo}.git" : "https://github.com/{$username}/{$repo}.git";
            } else {
                $cloneUrl = ($cloneType == 'ssh') ? "git@github.com:luyadev/{$repo}.git" : "https://github.com/{$username}/{$repo}.git";
            }
            
            $this->cloneRepo($repo, $cloneUrl, $newRepoHome, 'luyadev');
        }
        
        return $this->outputSuccess("init complete.");
    }
183009
protected void initGitFlowConfig() throws MojoFailureException,
            CommandLineException {
        gitSetConfig("gitflow.branch.master",
                gitFlowConfig.getProductionBranch());
        gitSetConfig("gitflow.branch.develop",
                gitFlowConfig.getDevelopmentBranch());

        gitSetConfig("gitflow.prefix.feature",
                gitFlowConfig.getFeatureBranchPrefix());
        gitSetConfig("gitflow.prefix.release",
                gitFlowConfig.getReleaseBranchPrefix());
        gitSetConfig("gitflow.prefix.hotfix",
                gitFlowConfig.getHotfixBranchPrefix());
        gitSetConfig("gitflow.prefix.support",
                gitFlowConfig.getSupportBranchPrefix());
        gitSetConfig("gitflow.prefix.versiontag",
                gitFlowConfig.getVersionTagPrefix());

        gitSetConfig("gitflow.origin", gitFlowConfig.getOrigin());
    }
1023707
def get_branch():
        
        if os.getenv('GIT_BRANCH'):
            # Travis
            branch = os.getenv('GIT_BRANCH')
        elif os.getenv('BRANCH_NAME'):
            # Jenkins 2
            branch = os.getenv('BRANCH_NAME')
        else:
            branch = check_output(
                "git rev-parse --abbrev-ref HEAD".split(" ")
                ).decode('utf-8').strip()

        return branch.replace("/", "_")
339168
def call_git_branch():
    """"""
    try:
        with open(devnull, "w") as fnull:
            arguments = [GIT_COMMAND, 'rev-parse', '--abbrev-ref', 'HEAD']
            return check_output(arguments, cwd=CURRENT_DIRECTORY,
                                stderr=fnull).decode("ascii").strip()
    except (OSError, CalledProcessError):
        return None
1295146
def get_or_create_environment(self, repo: str, branch: str, git_repo: Repo, repo_path: Path) -> str:
        
        return sys.executable
404839
def workdir=(dir)
      workdir = GitLib.find_workdir(dir)
      if workdir.nil?
        @workdir = dir
        logger.info { "Initializing new repository at #{dir}" }
        return command(:init)
      else
        @workdir = workdir
        logger.debug { "Opening existing repository at #{dir}" }
      end
    end
511469
public void deployInitialApplications() {
        initDeployAppAttributeIfIsNull();

        String gitRepoUrl = getConfig(GIT_URL);
        String tarballResourceUrl = getConfig(TARBALL_URL);
        
        if (gitRepoUrl != null) {
            String targetName = inferCorrectAppGitName();
            deployGitResource(gitRepoUrl, targetName);
        } else if (tarballResourceUrl != null) {
            String targetName = inferCorrectAppTarballName();
            deployTarballResource(tarballResourceUrl, targetName);
        }
        
    }
41798
def rebase(self, target_branch):
        
        current_branch = self.repo.active_branch

        arguments = (
                ([self.config('git-up.rebase.arguments')] or []) +
                [target_branch.name]
        )
        try:
            self._run('rebase', *arguments)
        except GitError as e:
            raise RebaseError(current_branch.name, target_branch.name,
                              **e.__dict__)
275572
def ext_pillar(minion_id, pillar, repo, branch='default', root=None):
    '''
    
    '''
    with Repo(repo) as repo:
        repo.update(branch)
    envname = 'base' if branch == 'default' else branch
    if root:
        path = os.path.normpath(os.path.join(repo.working_dir, root))
    else:
        path = repo.working_dir

    opts = copy.deepcopy(__opts__)
    opts['pillar_roots'][envname] = [path]
    pil = salt.pillar.Pillar(opts, __grains__, minion_id, envname)
    return pil.compile_pillar(ext=False)
422304
function initSubmodules(cb) {
  console.log('Detected a git install');
  console.log('Cloning libSass into src/libsass');

  var clone = spawn('git', ['clone', 'git@github.com:sass/libsass.git', './src/libsass']);
  manageProcess(clone, function(err) {
    if (err) {
      cb(err);
      return;
    }

    console.log('Checking out libsass to ' + pkg.libsass);

    var checkout = spawn('git', ['checkout', pkg.libsass], { cwd: './src/libsass' });
    manageProcess(checkout, function(err) {
      cb(err);
    });
  });
}