File size: 1,716 Bytes
fd5da23
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7711652
 
 
 
fd5da23
 
 
 
 
 
 
 
 
 
 
 
 
7711652
fd5da23
 
 
 
 
 
 
7711652
 
 
 
 
 
 
 
 
 
 
 
 
 
fd5da23
7711652
 
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
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 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()
    # Extract necessary information
    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