如何通过PyGithub将分支合并到master中

0qx6xfy6  于 12个月前  发布在  Git
关注(0)|答案(2)|浏览(155)

例如,我有一个文件t.json,内容是:

{
  "a": "abcdefg"
}

字符串
文件t.json被推送到主分支。然后我向文件添加一些内容,并 checkout 到一个新的分支,所以文件现在看起来像这样:

{
  "a": "abcdefg",
  "b": "mkjuujj"
}


现在我可以使用PyGithub比较两个提交。代码如下:

WORKING_BRANCH = "my_new_branch"
new_branch_ref_str = "refs/heads/%s" % WORKING_BRANCH
branch_ref = None
all_ref = repo.get_git_refs()

for ref in all_ref:
    if ref.ref == new_branch_ref_str:
        branch_ref = ref
        break

if not branch_ref:
    # create branch from this commit
    b = repo.get_branch("master")
    branch_ref = repo.create_git_ref(ref=new_branch_ref_str,
                                 sha=b.commit.sha)

    last_head = repo.get_branch(WORKING_BRANCH)
    fc = repo.get_file_contents("/t.json", ref=WORKING_BRANCH)
    file = 't.json'
    commit_message = "create a new branch with changes"
    input_file = open(file, 'rb')
    data = input_file.read()

    result = repo.update_file("/t.json",
                          commit_message,
                          data,
                          fc.sha, branch=WORKING_BRANCH)

    diff_url = repo.compare(last_head.commit.sha,
                        result['commit'].sha)

    print diff_url.diff_url


这就是我得到的:

diff --git a/t.json b/t.json
index ef03bf5..b775e51 100644
--- a/t.json
+++ b/t.json
@@ -1,3 +1,4 @@
 {
-  "a": "abcdefg"
+  "a": "abcdefg",
+  "b": "mkjuujj"
 }


如何使用PyGithub将我的_new_分支合并到master分支中?非常感谢。

njthzxwz

njthzxwz1#

try:
    base = repo.get_branch("master")
    head = repo.get_branch(WORKING_BRANCH)

    merge_to_master = repo.merge("master",
                        head.commit.sha, "merge to master")

except Exception as ex:
    print ex

字符串

68bkxrlz

68bkxrlz2#

如果你想使用pull requests,你可以使用PyGithub如下:

def create_pull_request(user_repo, base_branch, head_branch):
    try:
        pull_request = user_repo.create_pull(
            title="Merge Request",
            body="Merge branches",
            base=base_branch,  # the target branch where you want to merge your changes (like 'main' or 'master')
            head=head_branch  # aka source branch, contains changes you want to merge (feature or bug-fix branch)
        )
        return pull_request.number
    except GithubException as e:
        reason, detail = e.data['message'], e.data['errors'][0]['message']
        raise Exception(f"Failed to create pull request due to {reason}: {detail}")

字符串
要合并新创建的拉取请求,您可以:

def perform_merge(self, git_repo, base_branch, head_branch):
    pr_number = self.create_pull_request(git_repo, base_branch.name, head_branch.name)
    pull_request = user_repo.get_pull(pull_request_number)
    pull_request.merge()

相关问题