File size: 2,426 Bytes
fd5da23
 
 
 
 
 
 
 
 
 
 
 
 
 
c82eb8a
 
 
 
fd5da23
7711652
 
 
 
fd5da23
 
 
 
 
 
 
 
 
 
 
 
7711652
fd5da23
 
 
 
 
 
7711652
 
 
 
c82eb8a
 
7711652
 
 
 
 
 
 
 
 
fd5da23
7711652
 
c82eb8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
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"