如何在 GitPython 中创建 Git 拉取请求

She*_*hek 6 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')
Run Code Online (Sandbox Code Playgroud)

提交此更改后,我正在尝试push此更改并创建一个pull requestfrom branch='banana-refresh'to branch='banana-integration'

fre*_*rix 9

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

您无法使用标准 git 命令行创建拉取请求。git request-pull,例如,仅生成挂起更改的摘要。它不会在 GitHub 中创建拉取请求。

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

或者使用 requests 库向 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
)
Run Code Online (Sandbox Code Playgroud)

这使用GitHub OAuth2 令牌身份验证GitHub 拉取请求 API 端点banana-refresh针对banana-integration.

  • 请求失败:必须启用 Cookie 才能使用 GitHub。当我使用这个脚本时出现这个错误。 (2认同)

Mil*_*ilk 3

看起来好像拉取请求还没有被这个库包装。

您可以按照文档直接调用git 命令行。

repo.git.pull_request(...)