我正在使用 GitHub API,所以: 我创建了两个存储库:
我想知道是否有一种方法可以使用 GitHub API 从 repo1 中的某个分支挑选提交到 repo2 中的某个分支。
我已经使用本指南通过 git cli 实现了这一点: 在存储库之间挑选
现在我需要使用 GitHub API 执行相同的操作。 如果有人能在这里帮助我,我将不胜感激。
提前致谢。
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.')