Name of branch to submit pull request from
 Starts with patch-1 and keeps going until it finds one not taken
558812
def patch_branch
      num = 1
      branch_name = form_data['title'].parameterize
      return branch_name unless branch_exists?(branch_name)
      branch = "#{branch_name}-#{num}"
      while branch_exists?(branch)
        num += 1
        branch = "#{branch_name}-#{num}"
      end
      branch
    end
918764
function findRepos(callback) {
  var cwd = process.cwd(),
      tasks = [];

  fs.readdir(cwd, function(err, files) {
    if (err) return callback(err);

    var repos = [];
    files.forEach(function(file) {
      if (fs.existsSync(path.join(cwd, file, '.git'))) {
        repos.push(path.join(cwd, file));
      }
    });

    if (repos.length === 0) {
      return callback(new Error('No repositories found'));
    }

    repos.forEach(function(dir) {
      tasks.push(function(done) {
        done(err, git(dir));
      });
    });

    async.series(tasks, function(err, results) {
      callback(err, results);
    });
  });
}
58191
def trigger(self, username, project, branch, **build_params):
        """"""
        method = 'POST'
        url = ('/project/{username}/{project}/tree/{branch}?'
               'circle-token={token}'.format(
                   username=username, project=project,
                   branch=branch, token=self.client.api_token))

        if build_params is not None:
            json_data = self.client.request(method, url,
                                            build_parameters=build_params)
        else:
            json_data = self.client.request(method, url)
        return json_data
35683
def mkrelease(finish='yes', version=''):
    
    if not version:
        version = _version_format(_version_guess_next())

    if _git_get_current_branch() != 'release/' + version:
        _tool_run('git checkout develop',
                  'git flow release start ' + version)

    _project_patch_version(version)
    _project_patch_changelog()
    patched_files = ' '.join([VERSION_FILE, CHANGES_FILE])

    run('git diff ' + patched_files, pty=True)
    _tool_run(('git commit -m "Bump Version to {0!s}" {1!s}'
               .format(version, patched_files)))

    if finish not in ('no', 'n', ):
        _tool_run("git flow release finish -m '{0}' {0}".format(version),
                  env={b'GIT_MERGE_AUTOEDIT': b'no', })
        _tool_run('git push origin --tags develop master')
1271838
def get_pull_requests_commits(self, project, repository, pull_request_id):
        
        url = 'rest/api/1.0/projects/{project}/repos/{repository}/pull-requests/{pullRequestId}/commits'.format(
            project=project,
            repository=repository,
            pullRequestId=pull_request_id)
        params = {'start': 0}
        response = self.get(url, params=params)
        if 'values' not in response:
            return []
        commits_list = (response or {}).get('values')
        while not response.get('isLastPage'):
            params['start'] = response.get('nextPageStart')
            response = self.get(url, params=params)
            commits_list += (response or {}).get('values')
        return commits_list
719536
function checkHeadsOnline(pattern, opts, callback) {
  var args = verify(pattern, opts, callback);
  var refs = 'refs/heads/' + cache.branch;
  request(refs, args.opts, args.callback);
}
461389
def check(branch: str = 'master'):
    
    if os.environ.get('TRAVIS') == 'true':
        travis(branch)
    elif os.environ.get('SEMAPHORE') == 'true':
        semaphore(branch)
    elif os.environ.get('FRIGG') == 'true':
        frigg(branch)
    elif os.environ.get('CIRCLECI') == 'true':
        circle(branch)
    elif os.environ.get('GITLAB_CI') == 'true':
        gitlab(branch)
    elif 'BITBUCKET_BUILD_NUMBER' in os.environ:
        bitbucket(branch)
442266
async function ensurePr(prConfig) {
  const config = { ...prConfig };

  logger.trace({ config }, 'ensurePr');
  // If there is a group, it will use the config of the first upgrade in the array
  const { branchName, prTitle, upgrades } = config;
  // Check if existing PR exists
  const existingPr = await platform.getBranchPr(branchName);
  if (existingPr) {
    logger.debug('Found existing PR');
  }
  config.upgrades = [];

  if (config.artifactErrors && config.artifactErrors.length) {
    logger.debug('Forcing PR because of artifact errors');
    config.forcePr = true;
  }

  let branchStatus;
  async function getBranchStatus() {
    if (!branchStatus) {
      branchStatus = await platform.getBranchStatus(
        branchName,
        config.requiredStatusChecks
      );
      logger.debug({ branchStatus, branchName }, 'getBranchStatus() result');
    }
    return branchStatus;
  }

  // Only create a PR if a branch automerge has failed
  if (
    config.automerge === true &&
    config.automergeType.startsWith('branch') &&
    !config.forcePr
  ) {
    logger.debug(
      `Branch is configured for branch automerge, branch status) is: ${await getBranchStatus()}`
    );
    if (
      (await getBranchStatus()) === 'pending' ||
      (await getBranchStatus()) === 'running'
    ) {
      logger.debug('Checking how long this branch has been pending');
      const lastCommitTime = await platform.getBranchLastCommitTime(branchName);
      const currentTime = new Date();
      const millisecondsPerHour = 1000 * 60 * 60;
      const elapsedHours = Math.round(
        (currentTime.getTime() - lastCommitTime.getTime()) / millisecondsPerHour
      );
      if (elapsedHours >= config.prNotPendingHours) {
        logger.info('Branch exceeds prNotPending hours - forcing PR creation');
        config.forcePr = true;
      }
    }
    if (config.forcePr || (await getBranchStatus()) === 'failure') {
      logger.debug(`Branch tests failed, so will create PR`);
    } else {
      return null;
    }
  }
  if (config.prCreation === 'status-success') {
    logger.debug('Checking branch combined status');
    if ((await getBranchStatus()) !== 'success') {
      logger.debug(
        `Branch status is "${await getBranchStatus()}" - not creating PR`
      );
      return null;
    }
    logger.debug('Branch status success');
  } else if (
    config.prCreation === 'not-pending' &&
    !existingPr &&
    !config.forcePr
  ) {
    logger.debug('Checking branch combined status');
    if (
      (await getBranchStatus()) === 'pending' ||
      (await getBranchStatus()) === 'running'
    ) {
      logger.debug(
        `Branch status is "${await getBranchStatus()}" - checking timeout`
      );
      const lastCommitTime = await platform.getBranchLastCommitTime(branchName);
      const currentTime = new Date();
      const millisecondsPerHour = 1000 * 60 * 60;
      const elapsedHours = Math.round(
        (currentTime.getTime() - lastCommitTime.getTime()) / millisecondsPerHour
      );
      if (elapsedHours < config.prNotPendingHours) {
        logger.debug(
          `Branch is ${elapsedHours} hours old - skipping PR creation`
        );
        return null;
      }
      logger.debug(
        `prNotPendingHours=${
          config.prNotPendingHours
        } threshold hit - creating PR`
      );
    }
    logger.debug('Branch status success');
  }

  const processedUpgrades = [];
  const commitRepos = [];

  // Get changelog and then generate template strings
  for (const upgrade of upgrades) {
    const upgradeKey = `${upgrade.depType}-${upgrade.depName}-${
      upgrade.manager
    }-${upgrade.fromVersion || upgrade.currentValue}-${upgrade.toVersion}`;
    if (processedUpgrades.includes(upgradeKey)) {
      continue; // eslint-disable-line no-continue
    }
    processedUpgrades.push(upgradeKey);
    upgrade.hasUrls = !!(upgrade.sourceUrl || upgrade.homepage);

    const logJSON = await changelogHelper.getChangeLogJSON({
      manager: upgrade.manager,
      versionScheme: upgrade.versionScheme,
      depType: upgrade.depType,
      depName: upgrade.depName,
      fromVersion: upgrade.fromVersion,
      toVersion: upgrade.toVersion,
      sourceUrl: upgrade.sourceUrl,
      releases: upgrade.releases,
    });

    if (logJSON) {
      upgrade.githubName = logJSON.project ? logJSON.project.github : undefined;
      upgrade.hasReleaseNotes = logJSON.hasReleaseNotes;
      upgrade.releases = [];
      if (
        upgrade.hasReleaseNotes &&
        upgrade.githubName &&
        !commitRepos.includes(upgrade.githubName)
      ) {
        commitRepos.push(upgrade.githubName);
        logJSON.versions.forEach(version => {
          const release = { ...version };
          upgrade.releases.push(release);
        });
      }
    }
    config.upgrades.push(upgrade);
  }

  // Update the config object
  Object.assign(config, upgrades[0]);
  config.hasReleaseNotes = config.upgrades.some(upg => upg.hasReleaseNotes);

  const releaseNoteRepos = [];
  for (const upgrade of config.upgrades) {
    if (upgrade.hasReleaseNotes) {
      if (releaseNoteRepos.includes(upgrade.sourceUrl)) {
        logger.debug(
          { depName: upgrade.depName },
          'Removing duplicate release notes'
        );
        upgrade.hasReleaseNotes = false;
      } else {
        releaseNoteRepos.push(upgrade.sourceUrl);
      }
    }
  }

  const prBody = await getPrBody(config);

  try {
    if (existingPr) {
      logger.debug('Processing existing PR');
      // istanbul ignore if
      if (
        config.automerge &&
        ['failure', 'error', 'failed'].includes(await getBranchStatus())
      ) {
        logger.debug(`Setting assignees and reviewers as status checks failed`);
        await addAssigneesReviewers(config, existingPr);
      }
      // Check if existing PR needs updating
      const reviewableIndex = existingPr.body.indexOf(
        '<!-- Reviewable:start -->'
      );
      let existingPrBody = existingPr.body;
      if (reviewableIndex > -1) {
        logger.debug('Stripping Reviewable content');
        existingPrBody = existingPrBody.slice(0, reviewableIndex);
      }
      existingPrBody = existingPrBody.trim();
      if (
        existingPr.title === prTitle &&
        noWhitespace(existingPrBody) === noWhitespace(prBody)
      ) {
        logger.debug(`${existingPr.displayNumber} does not need updating`);
        return existingPr;
      }
      // PR must need updating
      if (existingPr.title !== prTitle) {
        logger.info(
          {
            branchName,
            oldPrTitle: existingPr.title,
            newPrTitle: prTitle,
          },
          'PR title changed'
        );
      } else if (!config.committedFiles) {
        logger.debug(
          {
            prTitle,
            oldPrBody: existingPrBody,
            newPrBody: prBody,
          },
          'PR body changed'
        );
      }
      // istanbul ignore if
      if (config.dryRun) {
        logger.info('DRY-RUN: Would update PR #' + existingPr.number);
      } else {
        await platform.updatePr(existingPr.number, prTitle, prBody);
        logger.info(
          { committedFiles: config.committedFiles, pr: existingPr.number },
          `PR updated`
        );
      }
      return existingPr;
    }
    logger.debug({ branch: branchName, prTitle }, `Creating PR`);
    // istanbul ignore if
    if (config.updateType === 'rollback') {
      logger.info('Creating Rollback PR');
    }
    let pr;
    try {
      // istanbul ignore if
      if (config.dryRun) {
        logger.info('DRY-RUN: Would create PR: ' + prTitle);
        pr = { number: 0, displayNumber: 'Dry run PR' };
      } else {
        pr = await platform.createPr(
          branchName,
          prTitle,
          prBody,
          config.labels,
          false,
          config.statusCheckVerify
        );
        logger.info({ branch: branchName, pr: pr.number }, 'PR created');
      }
    } catch (err) /* istanbul ignore next */ {
      if (err.message === 'Validation Failed (422)') {
        logger.info({ branch: branchName }, 'Deleting invalid branch');
        // istanbul ignore if
        if (config.dryRun) {
          logger.info('DRY-RUN: Would delete branch: ' + config.branchName);
        } else {
          await platform.deleteBranch(branchName);
        }
        return null;
      }
      logger.warn({ err }, `Failed to create PR`);
      if (err.statusCode === 502) {
        logger.info(
          { branch: branchName },
          'Deleting branch due to server error'
        );
        // istanbul ignore if
        if (config.dryRun) {
          logger.info('DRY-RUN: Would delete branch: ' + config.branchName);
        } else {
          await platform.deleteBranch(branchName);
        }
      }
      return null;
    }
    if (
      config.branchAutomergeFailureMessage &&
      !config.suppressNotifications.includes('branchAutomergeFailure')
    ) {
      const subject = 'Branch automerge failure';
      let content =
        'This PR was configured for branch automerge, however this is not possible so it has been raised as a PR instead.';
      if (config.branchAutomergeFailureMessage === 'branch status error') {
        content += '\n___\n * Branch has one or more failed status checks';
      }
      logger.info('Adding branch automerge failure message to PR');
      // istanbul ignore if
      if (config.dryRun) {
        logger.info('Would add comment to PR #' + pr.number);
      } else {
        await platform.ensureComment(pr.number, subject, content);
      }
    }
    // Skip assign and review if automerging PR
    if (
      config.automerge &&
      !['failure', 'error', 'failed'].includes(await getBranchStatus())
    ) {
      logger.debug(
        `Skipping assignees and reviewers as automerge=${config.automerge}`
      );
    } else {
      await addAssigneesReviewers(config, pr);
    }
    logger.info(`Created ${pr.displayNumber}`);
    return pr;
  } catch (err) {
    // istanbul ignore if
    if (
      err.message === 'repository-changed' ||
      err.message === 'rate-limit-exceeded' ||
      err.message === 'platform-failure' ||
      err.message === 'integration-unauthorized'
    ) {
      logger.debug('Passing error up');
      throw err;
    }
    logger.error({ err }, 'Failed to ensure PR:', err);
  }
  return null;
}
1079971
async function getBranchStatus(branchName, requiredStatusChecks) {
  logger.debug(`getBranchStatus(${branchName})`);
  if (!requiredStatusChecks) {
    // null means disable status checks, so it always succeeds
    logger.debug('Status checks disabled = returning "success"');
    return 'success';
  }
  if (requiredStatusChecks.length) {
    // This is Unsupported
    logger.warn({ requiredStatusChecks }, `Unsupported requiredStatusChecks`);
    return 'failed';
  }
  const commitStatusUrl = `repos/${
    config.repository
  }/commits/${branchName}/status`;
  let commitStatus;
  try {
    commitStatus = (await get(commitStatusUrl)).body;
  } catch (err) /* istanbul ignore next */ {
    if (err.statusCode === 404) {
      logger.info(
        'Received 404 when checking branch status, assuming that branch has been deleted'
      );
      throw new Error('repository-changed');
    }
    logger.info('Unknown error when checking branch status');
    throw err;
  }
  logger.debug(
    { state: commitStatus.state, statuses: commitStatus.statuses },
    'branch status check result'
  );
  let checkRuns = [];
  if (!config.isGhe) {
    try {
      const checkRunsUrl = `repos/${
        config.repository
      }/commits/${branchName}/check-runs`;
      const opts = {
        headers: {
          Accept: 'application/vnd.github.antiope-preview+json',
        },
      };
      const checkRunsRaw = (await get(checkRunsUrl, opts)).body;
      if (checkRunsRaw.check_runs && checkRunsRaw.check_runs.length) {
        checkRuns = checkRunsRaw.check_runs.map(run => ({
          name: run.name,
          status: run.status,
          conclusion: run.conclusion,
        }));
        logger.debug({ checkRuns }, 'check runs result');
      } else {
        // istanbul ignore next
        logger.debug({ result: checkRunsRaw }, 'No check runs found');
      }
    } catch (err) /* istanbul ignore next */ {
      if (
        err.statusCode === 403 ||
        err.message === 'integration-unauthorized'
      ) {
        logger.info('No permission to view check runs');
      } else {
        logger.warn({ err }, 'Error retrieving check runs');
      }
    }
  }
  if (checkRuns.length === 0) {
    return commitStatus.state;
  }
  if (
    commitStatus.state === 'failed' ||
    checkRuns.some(run => run.conclusion === 'failed')
  ) {
    return 'failed';
  }
  if (
    (commitStatus.state === 'success' || commitStatus.statuses.length === 0) &&
    checkRuns.every(run => ['neutral', 'success'].includes(run.conclusion))
  ) {
    return 'success';
  }
  return 'pending';
}
172171
def finish():
    # type: () -> None
    
    pretend = context.get('pretend', False)

    if not pretend and (git.staged() or git.unstaged()):
        log.err(
            "You have uncommitted changes in your repo!\n"
            "You need to stash them before you merge the hotfix branch"
        )
        sys.exit(1)

    branch = git.current_branch(refresh=True)
    base = common.get_base_branch()

    prompt = "<32>Merge <33>{}<32> into <33>{}<0>?".format(branch.name, base)
    if not click.confirm(shell.fmt(prompt)):
        log.info("Cancelled")
        return

    common.assert_branch_type('task')

    # Merge task into it's base feature branch
    common.git_checkout(base)
    common.git_pull(base)
    common.git_merge(base, branch.name)

    # Cleanup
    common.git_branch_delete(branch.name)
    common.git_prune()

    common.git_checkout(base)
835283
def grab(branch, path = Dir.pwd, remote = 'origin')
      exit_status = 1
      error "no branch provided" if branch.nil?
      #remotes  = FalkorLib::Git.remotes(path)
      branches = FalkorLib::Git.list_branch(path)
      if branches.include? "remotes/#{remote}/#{branch}"
        info "Grab the branch '#{remote}/#{branch}'"
        exit_status = execute_in_dir(FalkorLib::Git.rootdir( path ), "git branch --track #{branch} #{remote}/#{branch}")
      else
        warning "the remote branch '#{remote}/#{branch}' cannot be found"
      end
      exit_status
    end
605640
async function getBranchCommit(branchName) {
  try {
    const branch = (await api.get(
      `/2.0/repositories/${config.repository}/refs/branches/${branchName}`
    )).body;
    return branch.target.hash;
  } catch (err) /* istanbul ignore next */ {
    logger.debug({ err }, `getBranchCommit('${branchName}') failed'`);
    return null;
  }
}
1293041
def get_pull_requests_changes(self, project, repository, pull_request_id):
        
        url = 'rest/api/1.0/projects/{project}/repos/{repository}/pull-requests/{pullRequestId}/changes'.format(
            project=project,
            repository=repository,
            pullRequestId=pull_request_id)
        params = {'start': 0}
        response = self.get(url, params=params)
        if 'values' not in response:
            return []
        changes_list = (response or {}).get('values')
        while not response.get('isLastPage'):
            params['start'] = response.get('nextPageStart')
            if params['start'] is None:
                log.warning('Too many changes in pull request. Changes list is incomplete.')
                break
            response = self.get(url, params=params)
            changes_list += (response or {}).get('values')
        return changes_list
411826
def _pull_branch_from_origin(self):
        
        try:
            ## self.repo.git.pull()
            subprocess.check_call(["git", "pull", "origin", self.branch])
        except Exception as inst:
            sys.exit("""
        Your HEAD commit conflicts with origin/{tag}. 
        Resolve, merge, and rerun versioner.py
        """)
113846
def pull(self, remote, branch=None):
        '''
        '''
        pb = ProgressBar()
        pb.setup(self.name)
        if branch:
            remote.pull(branch, progress=pb)
        else: # pragma: no cover
            remote.pull(progress=pb)
        print()
1278813
def git_pull_view(self, request, repo_name):
        """"""
        LOG.info("Pull requested for %s." % repo_name)
        repo = get_object_or_404(self.model, name=repo_name)
        repo.pull()
        self.message_user(request, "Repo %s successfully updated." % repo_name,
                          level=messages.SUCCESS)
        return redirect('admin:registry_clonedrepo_change', repo_name)
648859
def handle_branch(repo, **kwargs):
    """"""
    log.info('branch: %s %s' %(repo, kwargs))
    if type(repo) in [unicode, str]:
        path = os.path.join(repo, kwargs.get('name', 'Unnamed'))
        desc = kwargs.get('desc')
        branch = Repo.new(path=path, desc=desc, bare=True)
    else:
        name = kwargs.get('name')
        path = kwargs.get('path')
        if path and not name:
            name = os.path.basename(path)
        desc = kwargs.get('desc')
        branch = repo.branch(name=name, desc=desc)
    return branch.serialize()