Skip to main content
 首页 » 编程设计

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

2025年02月15日9zfyouxi

我正在尝试将 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') 

提交此更改后,我尝试推送此更改并从 branch='banana-refresh' 创建一个 pull request 到 branch='banana-integration'.

请您参考如下方法:

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

您不能使用标准的 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 Auth和 GitHub pull request API endpoint针对 banana-integration 发出分支 banana-refresh 的拉取请求。