How to cherry-pick a commit from another repository using GitHub API

41 views Asked by At

I'm playing a bit with GitHub API, so: I've created two repositories:

  • repo1
  • repo2

And I wanted to know if there is a way to cherry-pick a commit from a certain branch in repo1 to a certain branch in repo2 using GitHub API.

I've achieved this with git cli using this guide: cherry-pick between repos

And now I need to do the same using GitHub API. I would appreciate if someone could give me a hand here.

Thanks in advance.

1

There are 1 answers

2
CodeWizard On
  • Here is a sample file which you can use.
  • Don't forget to set all the variables
import requests
import json

# GitHub credentials
username = 'username' 
token = 'token'

# Repositories and commit details
source_repo = 'source_repo'
target_repo = 'target_repo'
commit_sha = 'commit_sha'
branch = 'branch'

# Headers for the API request
headers = {
    'Accept': 'application/vnd.github.v3+json',
    'Authorization': f'token {token}',
}

# Get the commit from the source repository
commit_url = f'https://api.github.com/repos/{username}/{source_repo}/git/commits/{commit_sha}'
response = requests.get(commit_url, headers=headers)
commit_data = response.json()

# Create the same commit in the target repository
commit_url = f'https://api.github.com/repos/{username}/{target_repo}/git/commits'
payload = {
    'message': commit_data['message'],
    'tree': commit_data['tree']['sha'],
    'parents': [branch],
}
response = requests.post(commit_url, headers=headers, data=json.dumps(payload))

if response.status_code == 201:
    print('Commit created successfully in the target repository.')
else:
    print('Failed to create commit in the target repository.')