Created
April 14, 2022 20:21
-
-
Save Satak/ef5606ee2154353e4d08710cf0adda6d to your computer and use it in GitHub Desktop.
Create new file commit via GitHub REST API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
import json | |
def get_latest_commit_sha(base_url, headers, owner, repo, branch='main'): | |
url = f'{base_url}/repos/{owner}/{repo}/branches/{branch}' | |
return requests.get(url, headers=headers).json()['commit']['sha'] | |
def get_base_tree_sha(base_url, headers, owner, repo, sha): | |
url = f'{base_url}/repos/{owner}/{repo}/git/commits/{sha}' | |
return requests.get(url, headers=headers).json()['tree']['sha'] | |
def new_tree(base_url, headers, owner, repo, base_tree_sha, order_id, payload): | |
url = f'{base_url}/repos/{owner}/{repo}/git/trees' | |
file_name = f'order_{order_id}.json' | |
data = { | |
'base_tree': f'{base_tree_sha}', | |
'tree': [ | |
{ | |
'path': file_name, | |
'mode': '100644', | |
'type': 'blob', | |
'content': json.dumps(payload) | |
} | |
] | |
} | |
return requests.post(url, headers=headers, json=data).json()['sha'] | |
def create_commit_sha(base_url, headers, owner, repo, latest_commit_sha, new_tree_sha, order_id): | |
url = f'{base_url}/repos/{owner}/{repo}/git/commits' | |
data = { | |
'parents': [latest_commit_sha], | |
'tree': f'{new_tree_sha}', | |
'message': f'Add new order {order_id}' | |
} | |
return requests.post(url, headers=headers, json=data).json()['sha'] | |
def new_commit(base_url, headers, owner, repo, commit_sha, branch='main'): | |
url = f'{base_url}/repos/{owner}/{repo}/git/refs/heads/{branch}' | |
data = { | |
"sha": commit_sha | |
} | |
return requests.post(url, headers=headers, json=data).json() | |
def commit_handler(owner, repo, gh_token, order_id, payload): | |
base_url = 'https://api.github.com' | |
headers = { | |
'Authorization': f'token {gh_token}', | |
'accept': 'application/vnd.github.v3+json' | |
} | |
latest_commit_sha = get_latest_commit_sha(base_url, headers, owner, repo) | |
base_tree_sha = get_base_tree_sha( | |
base_url, headers, owner, repo, latest_commit_sha) | |
new_tree_sha = new_tree(base_url, headers, owner, repo, | |
base_tree_sha, order_id, payload) | |
commit_sha = create_commit_sha(base_url, headers, owner, repo, | |
latest_commit_sha, new_tree_sha, order_id) | |
commit = new_commit(base_url, headers, owner, repo, commit_sha) | |
return commit |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment