Spaces:
Runtime error
Runtime error
import requests | |
import base64 | |
import os | |
# GitHub repository information | |
repository_owner = os.environ['GIT_USER_NAME'] | |
repository_name = os.environ['GIT_REPO_NAME'] | |
branch_name = 'main' | |
# GitHub API token (generate one in your GitHub account settings) | |
github_token = os.environ['GIT_TOKEN'] | |
def game_link(): | |
return f"""https://{repository_owner}.github.io/{repository_name}/""" | |
def push(new_content, path, file_name): | |
if len(path) == 0: | |
file_path = file_name | |
else: | |
file_path = f'{path}/{file_name}' | |
# Get the current file content | |
url = f'https://api.github.com/repos/{repository_owner}/{repository_name}/contents/{file_path}?ref={branch_name}' | |
headers = {'Authorization': f'token {github_token}'} | |
response = requests.get(url, headers=headers) | |
response_json = response.json() | |
current_sha = response_json['sha'] | |
encoded_content = base64.b64encode(new_content.encode()).decode() | |
# Update the file content | |
update_data = { | |
'message': f'Update {file_path} via API', | |
'content': encoded_content, | |
'sha': current_sha, | |
'branch': branch_name | |
} | |
update_url = f'https://api.github.com/repos/{repository_owner}/{repository_name}/contents/{file_path}' | |
response = requests.put(update_url, json=update_data, headers=headers) | |
return response | |
def trigger_workflow(workflow_name): | |
api_url = f"""https://api.github.com/repos/ | |
{repository_owner}/{repository_name}/actions/workflows/{workflow_name}/dispatches""" | |
headers = { | |
'Authorization': f'Bearer {github_token}', | |
'Accept': 'application/vnd.github.v3+json', | |
} | |
payload = { | |
'ref': 'main' | |
} | |
response = requests.post(api_url, headers=headers, json=payload) | |
return response | |
def update_repo(text): | |
# TODO: use API's concurrency feature to ensure only 1 user submits at a time. | |
file_dir_path = '' | |
file_name = 'main.py' | |
response = push(text, file_dir_path, file_name) | |
if response.status_code != 200: | |
return response.text | |
else: | |
print(f"{file_name} pushed") | |
workflow_name = 'pygbag.yml' | |
response = trigger_workflow(workflow_name) | |
if response.status_code != 204: | |
return response.text | |
else: | |
print(f"{workflow_name} workflow started") | |
# TODO: poll running workflows and only return once all are done. | |
return "update successful" | |