How to create a Git Pull Request in GitPython
Asked Answered
P

3

14

I am trying to use python for my jenkins job, this job downloads and refreshes a line in the project then commits and creates a pull request, I am trying read the documentation for GitPython as hard as I can but my inferior brain is not able to make any sense out of it.

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 [email protected]',
                author='[email protected]')

After committing this change I am trying to push this change and create a pull request from branch='banana-refresh' to branch='banana-integration'.

Pronto answered 1/8, 2017 at 0:24 Comment(2)
I don't know about GitPython, but you can do it from the command line: git-scm.com/docs/git-request-pull. I imagine GitPython is simply a wrapper around that.Weisbart
Maybe this pip Git PR package helps.Nessim
T
9

GitPython is only a wrapper around Git. I assume you are wanting to create a pull request in a Git hosting service (Github/Gitlab/etc.).

You can't create a pull request using the standard git command line. git request-pull, for example, only Generates a summary of pending changes. It doesn't create a pull request in GitHub.

If you want to create a pull request in GitHub, you can use the PyGithub library.

Or make a simple HTTP request to the Github API with the requests library:

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
)

This uses the GitHub OAuth2 Token Auth and the GitHub pull request API endpoint to make a pull request of the branch banana-refresh against banana-integration.

Tindall answered 30/4, 2020 at 21:48 Comment(1)
Request Failed: Cookies must be enabled to use GitHub. This error comes when I used this script.Agata
L
3

It appears as though pull requests have not been wrapped by this library.

You can call the git command line directly as per the documentation.

repo.git.pull_request(...)

Lanneret answered 1/8, 2017 at 2:5 Comment(2)
I can't find this command in the documentation, can you be little more specific about arguments such as where would feature_branch and target_branch would go?Pronto
The command isn't supported in GitPython. You need to figure out how to run the command using the Git CLI (first link) with your parameters. And then convert that to a GitPython direct call (second link)Lanneret
K
1

I have followed frederix's answer also used https://api.github.com/repos/ instead of https://github.com/api/v3/repos/

Also use owner_name instead of project_name

Knighthead answered 11/1, 2021 at 13:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.