如何在GitPython中创建Git Pull请求

时间:2017-08-01 00:24:08

标签: python github gitpython

我正在尝试使用python作为我的jenkins工作,这个工作下载并刷新项目中的一行然后提交并创建一个拉取请求,我正在尝试尽可能努力地阅读GitPython的文档,但我的下级脑是无法理解它。

import git
import os
import os.path as osp


path = "banana-post/infrastructure/"
repo = git.Repo.clone_from('https://github.myproject.git',
                           osp.join('/Users/monkeyman/PycharmProjects/projectfolder/', 'monkey-post'), branch='banana-refresh')
os.chdir(path)

latest_banana = '123456'
input_file_name = "banana.yml"
output_file_name = "banana.yml"
with open(input_file_name, 'r') as f_in, open(output_file_name, 'w') as f_out:
    for line in f_in:
        if line.startswith("banana_version:"):
            f_out.write("banana_version: {}".format(latest_banana))
            f_out.write("\n")
        else:
            f_out.write(line)
os.remove("deploy.yml")
os.rename("deploy1.yml", "banana.yml")
files = repo.git.diff(None, name_only=True)
for f in files.split('\n'):
    repo.git.add(f)
repo.git.commit('-m', 'This an Auto banana Refresh, contact bannana@monkey.com',
                author='moneky@banana.com')

提交此更改后,我尝试push此更改,并从pull requestbranch='banana-refresh'创建branch='banana-integration'

3 个答案:

答案 0 :(得分:1)

好像拉请求尚未被此库包装。

您可以按git command line直接致电the documentation

repo.git.pull_request(...)

答案 1 :(得分:1)

GitPython只是Git的包装。我假设您要在Git托管服务(Github / Gitlab / etc。)中创建拉取请求。

您无法使用标准git命令行创建提取请求。 git request-pull,例如,仅Generates a summary of pending changes。它不会在GitHub中创建拉取请求。

如果要在GitHub中创建拉取请求,可以使用PyGithub库。

或通过请求库向Github API发出简单的HTTP请求:

import json
import requests

def create_pull_request(project_name, repo_name, title, description, head_branch, base_branch, git_token):
    """Creates the pull request for the head_branch against the base_branch"""
    git_pulls_api = "https://github.com/api/v3/repos/{0}/{1}/pulls".format(
        project_name,
        repo_name)
    headers = {
        "Authorization": "token {0}".format(git_token),
        "Content-Type": "application/json"}

    payload = {
        "title": title,
        "body": description,
        "head": head_branch,
        "base": base_branch,
    }

    r = requests.post(
        git_pulls_api,
        headers=headers,
        data=json.dumps(payload))

    if not r.ok:
        print("Request Failed: {0}".format(r.text))

create_pull_request(
    "<your_project>", # project_name
    "<your_repo>", # repo_name
    "My pull request title", # title
    "My pull request description", # description
    "banana-refresh", # head_branch
    "banana-integration", # base_branch
    "<your_git_token>", # git_token
)

这使用GitHub OAuth2 Token AuthGitHub pull request API endpointbanana-refresh发出分支banana-integration的拉取请求。

答案 2 :(得分:0)

我已经按照 frederix's 回答也使用了 https://api.github.com/repos/ 而不是 https://github.com/api/v3/repos/

也使用 owner_name 而不是 project_name