Merge a pull request (Merge Button)

@link https://developer.github.com/v3/pulls/#merge-a-pull-request-merge-button

@param int    $number
@param string $commitMessage
@param string $sha

@return array
@throws \Exception
353726
public function mergePullRequest(int $number, string $commitMessage = null, string $sha = null): array
    {
        return $this->getApi()->request($this->getApi()
                                             ->sprintf('/repos/:owner/:repo/pulls/:number/merge', $this->getOwner(),
                                                 $this->getRepo(), $number), Request::METHOD_PUT, [
                'commit_message' => $commitMessage,
                'sha'            => $sha
            ]);
    }
777299
def merge(self, commit_message=github.GithubObject.NotSet, commit_title=github.GithubObject.NotSet, merge_method=github.GithubObject.NotSet, sha=github.GithubObject.NotSet):
        
        assert commit_message is github.GithubObject.NotSet or isinstance(commit_message, (str, unicode)), commit_message
        assert commit_title is github.GithubObject.NotSet or isinstance(commit_title, (str, unicode)), commit_title
        assert merge_method is github.GithubObject.NotSet or isinstance(merge_method, (str, unicode)), merge_method
        assert sha is github.GithubObject.NotSet or isinstance(sha, (str, unicode)), sha
        post_parameters = dict()
        if commit_message is not github.GithubObject.NotSet:
            post_parameters["commit_message"] = commit_message
        if commit_title is not github.GithubObject.NotSet:
            post_parameters["commit_title"] = commit_title
        if merge_method is not github.GithubObject.NotSet:
            post_parameters["merge_method"] = merge_method
        if sha is not github.GithubObject.NotSet:
            post_parameters["sha"] = sha
        headers, data = self._requester.requestJsonAndCheck(
            "PUT",
            self.url + "/merge",
            input=post_parameters
        )
        return github.PullRequestMergeStatus.PullRequestMergeStatus(self._requester, headers, data, completed=True)
161327
public List<GitlabCommitDiff> getCommitDiffs(Serializable projectId, String commitHash) throws IOException {
        return getCommitDiffs(projectId, commitHash, new Pagination());
    }
131600
def generic_commit_and_try_merge2master_wf(git_action,
                                           file_content,
                                           doc_id,
                                           auth_info,
                                           parent_sha,
                                           commit_msg='',
                                           merged_sha=None,
                                           doctype_display_name="document"):
    
    # _LOG.debug('generic_commit_and_try_merge2master_wf: doc_id="{s}" \
    #            parent_sha="{p}" merged_sha="{m}"'.format(
    #            s=doc_id, p=parent_sha, m=merged_sha))
    merge_needed = False
    fc = tempfile.NamedTemporaryFile()
    # N.B. we currently assume file_content is text/JSON, or should be serialized from a dict
    try:
        if is_str_type(file_content):
            fc.write(file_content)
        else:
            write_as_json(file_content, fc)
        fc.flush()
        try:
            max_file_size = git_action.max_file_size
        except:
            max_file_size = None
        if max_file_size is not None:
            file_size = os.stat(fc.name).st_size
            if file_size > max_file_size:
                m = 'Commit of {t} "{i}" had a file size ({a} bytes) which ' \
                    'exceeds the maximum size allowed ({b} bytes).'
                m = m.format(t=doctype_display_name, i=doc_id, a=file_size, b=max_file_size)
                raise GitWorkflowError(m)
        f = "Could not acquire lock to write to %s #%s" % (doctype_display_name, doc_id)
        acquire_lock_raise(git_action, fail_msg=f)
        try:
            try:
                commit_resp = git_action.write_doc_from_tmpfile(doc_id,
                                                                fc,
                                                                parent_sha,
                                                                auth_info,
                                                                commit_msg,
                                                                doctype_display_name)
            except Exception as e:
                _LOG.exception('write_doc_from_tmpfile exception')
                raise GitWorkflowError("Could not write to %s #%s ! Details: \n%s" %
                                       (doctype_display_name, doc_id, e.message))
            written_fp = git_action.path_for_doc(doc_id)
            branch_name = commit_resp['branch']
            new_sha = commit_resp['commit_sha']
            _LOG.debug('write of {t} {i} on parent {p} returned = {c}'.format(t=doctype_display_name,
                                                                              i=doc_id,
                                                                              p=parent_sha,
                                                                              c=str(commit_resp)))
            m_resp = _do_merge2master_commit(git_action,
                                             new_sha,
                                             branch_name,
                                             written_fp,
                                             merged_sha=merged_sha,
                                             prev_file_sha=commit_resp.get('prev_file_sha'))
            new_sha, branch_name, merge_needed = m_resp
        finally:
            git_action.release_lock()
    finally:
        fc.close()
    # What other useful information should be returned on a successful write?
    r = {
        "error": 0,
        "resource_id": doc_id,
        "branch_name": branch_name,
        "description": "Updated %s #%s" % (doctype_display_name, doc_id),
        "sha": new_sha,
        "merge_needed": merge_needed,
    }
    _LOG.debug('returning {r}'.format(r=str(r)))
    return r
811419
public function updateFailedMessage($number, $message = null)
    {
        if (Lang::has('resource-controller.updatefailed')) {
            return trans(
                'resource-controller.updatefailed', [
                    'number' => $number,
                    'message' => $message
                ]
            );
        }

        return 'Operation failed while updating the record '.$number.' with message: '.$message;
    }
1343552
public function combined($username, $repository, $sha)
    {
        return $this->get('/repos/'.rawurlencode($username).'/'.rawurlencode($repository).'/commits/'.rawurlencode($sha).'/status');
    }
244158
public static <T> void mergeFrom(byte[] data, int offset, int length, T message, Schema<T> schema, boolean numeric)
            throws IOException
    {

        ArrayBufferInput bios = new ArrayBufferInput(data, offset, length);

        MessageUnpacker unpacker = MessagePack.newDefaultUnpacker(bios);

        try
        {
            mergeFrom(unpacker, message, schema, numeric);
        }
        finally
        {
            unpacker.close();
        }
    }
850688
public function listCommentsPullRequest(int $number): array
    {
        return $this->getApi()->request($this->getApi()->sprintf('/repos/:owner/:repo/pulls/:number/comments',
            $this->getPullRequests()->getOwner(), $this->getPullRequests()->getRepo(), $number));
    }
747034
function checkCommitMessage (commitMessage, settings) {
  const {
    summaryMaxLength,
    lineMaxLength,
    patterns = {},
    examples = {}
  } = settings

  const isSummaryValid = commitMessage
    ? commitMessage.split('\n')[0].length <= summaryMaxLength
    : true
  const linesExceedingMaxLength = commitMessage
    .split('\n')
    .slice(1) // skip the summary line
    .reduce((a, l, k) => {
      return l.length > lineMaxLength
        ? a.concat({ n: k + 2, text: l })
        : a
    }, [])
  const isLineLengthValid = linesExceedingMaxLength.length === 0
  const isPatternValid = Object.keys(patterns || {}).some(key => {
    return patterns[key].test(commitMessage)
  })

  let errors = []

  if (!isSummaryValid) {
    errors = errors.concat(
      Object.assign(new Error(`Summary is more than ${summaryMaxLength} characters.`), {
        code: 'ESUMRY'
      })
    )
  }

  if (!isLineLengthValid) {
    errors = errors.concat(
      Object.assign(new Error([
        `The following lines have more than ${lineMaxLength} characters :`,
        `${linesExceedingMaxLength.map(l => 'line ' + l.n + ' : ' + l.text).join('\n')}`
      ].join('\n')), { code: 'ELINES', lines: linesExceedingMaxLength })
    )
  }

  if (!isPatternValid) {
    errors = errors.concat(
      Object.assign(new Error([
        'Commit message doesn\'t follow any message pattern.'
      ].concat(
        Object.keys(examples || {})
          .map(key => ['', `${key}:`].concat(examples[key]))
          .reduce((a, b) => a.concat(b), [])
      ).join('\n')), { code: 'EFRMT' })
    )
  }

  return {
    isSummaryValid,
    isLineLengthValid,
    linesExceedingMaxLength,
    isPatternValid,
    isValid: isSummaryValid && isLineLengthValid && isPatternValid,
    errors
  }
}
269384
public function listCommits(string $sha = AbstractApi::BRANCH_MASTER, string $path = null, string $author = null,
                                string $since = null, string $until = null): array
    {
        return $this->getApi()->request($this->getApi()->sprintf('/repos/:owner/:repo/commits?:args',
            $this->getRepositories()->getOwner(), $this->getRepositories()->getRepo(), http_build_query([
                "sha"    => $sha,
                "path"   => $path,
                "author" => $author,
                "since"  => $since,
                "until"  => $until
            ])));
    }
1271096
public static function fromSha($sha, $baseUrl, ClientInterface $client)
    {
        $url = Project::getProjectBaseFromUrl($baseUrl) . '/git/trees';

        return static::get($sha, $url, $client);
    }
593503
public void commitWorkingCopy(final String commitMessage) throws IOException, InterruptedException {
        build.getWorkspace().act(new SVNCommitWorkingCopyCallable(commitMessage, getLocation(),
                getSvnAuthenticationProvider(build), buildListener));
    }
617836
protected function getCommitHash($hash = null)
    {
        if (!$hash) {
            $gClient = new GitClient(getcwd());
            return $gClient->getHashOfLatestCommit();
        }

        if (strlen($hash) != 40) {
            throw new \InvalidArgumentException(
                sprintf("Invalid git commit hash %s specified", $hash)
            );
        }

        return urlencode($hash);
    }
1143784
public function addCommitComment(string $sha, string $body, string $path = '', int $position = 0): array
    {
        return $this->getApi()->request($this->getApi()->sprintf('/repos/:owner/:repo/commits/:sha/comments',
            $this->getRepositories()->getOwner(), $this->getRepositories()->getRepo(), $sha), Request::METHOD_POST, [
                'body'     => $body,
                'path'     => $path,
                'position' => $position
            ]);
    }
225974
public function getCommitMessage()
    {
        $rtn = parent::getCommitMessage($this->data['commit_message']);

        $project = $this->getProject();

        if (!is_null($project)) {
            $reference = $project->getReference();
            $commitLink = '<a target="_blank" href="https://github.com/' . $reference . '/issues/$1">#$1</a>';
            $rtn = preg_replace('/\#([0-9]+)/', $commitLink, $rtn);
            $rtn = preg_replace('/\@([a-zA-Z0-9_]+)/', '<a target="_blank" href="https://github.com/$1">@$1</a>', $rtn);
        }

        return $rtn;
    }
391583
public function storeCommitComment(Commit $commit, $message) {
		$url = $this->getRepository()->resolveApiUrl(Repository::API_URL_COMMITS);
		$url = str_replace('{/sha}', '/' . $commit->getId(), $url);
		$url .= '/comments';
		$parameters = array(
			'body' => $message
		);
		$this->getApi()->post($url, json_encode($parameters));
	}
931460
public function getSinglePullRequest(int $number): array
    {
        return $this->getApi()->request($this->getApi()->sprintf('/repos/:owner/:repo/pulls/:number', $this->getOwner(),
            $this->getRepo(), $number));
    }