-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.py
More file actions
187 lines (156 loc) · 5.54 KB
/
api.py
File metadata and controls
187 lines (156 loc) · 5.54 KB
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
import requests
from github_rest_cli.globals import GITHUB_URL, get_headers
from github_rest_cli.utils import rich_output, rprint
def request_with_handling(
method, url, success_msg: str = None, error_msg: str = None, **kwargs
):
try:
response = requests.request(method, url, **kwargs)
response.raise_for_status()
if success_msg:
rich_output(success_msg)
else:
return response
except requests.exceptions.HTTPError as e:
status = e.response.status_code
if error_msg and status in error_msg:
rich_output(error_msg[status], format_str="bold red")
else:
rich_output(f"Request failed: status code {status}", format_str="bold red")
return None
except requests.exceptions.RequestException as e:
rich_output(f"Request error: {e}", format_str="bold red")
return None
def build_url(*segments: str) -> str:
"""
Build an GitHub REST API endpoint
Example:
build_url("repos", "org", "repo", "environments", "prod")
Result:
https://api.github.com/repos/org/repo/environments/prod
"""
base = GITHUB_URL.rstrip("/")
path = "/".join(segment.strip("/") for segment in segments)
return f"{base}/{path}"
def fetch_user() -> str:
headers = get_headers()
url = build_url("user")
response = request_with_handling("GET", url, headers=headers)
if response:
data = response.json()
return data.get("login")
return None
def get_repository(name: str, org: str = None):
owner = fetch_user()
headers = get_headers()
url = build_url("repos", org or owner, name)
response = request_with_handling(
"GET",
url,
headers=headers,
error_msg={
401: "Unauthorized access. Please check your token or credentials.",
404: "The requested repository does not exist.",
},
)
if response:
data = response.json()
rprint(data)
return None
def create_repository(name: str, visibility: str, org: str = None):
data = {
"name": name,
"auto_init": "true",
"visibility": visibility,
}
if visibility == "private":
data["private"] = True
owner = fetch_user()
headers = get_headers()
url = build_url("orgs", org, "repos") if org else build_url("user", "repos")
return request_with_handling(
"POST",
url,
headers=headers,
json=data,
success_msg=f"Repository successfully created in {org or owner}/{name}.",
error_msg={
401: "Unauthorized access. Please check your token or credentials.",
422: "Repository name already exists on this account or organization.",
},
)
def delete_repository(name: str, org: str = None):
owner = fetch_user()
headers = get_headers()
url = build_url("repos", org, name) if org else build_url("repos", owner, name)
return request_with_handling(
"DELETE",
url,
headers=headers,
success_msg=f"Repository sucessfully deleted in {org or owner}/{name}.",
error_msg={
403: "The authenticated user does not have sufficient permissions to delete this repository.",
404: "The requested repository does not exist.",
},
)
def list_repositories(page: int, property: str, role: str):
headers = get_headers()
url = build_url("user", "repos")
params = {"per_page": page, "sort": property, "type": role}
response = request_with_handling(
"GET",
url,
params=params,
headers=headers,
error_msg={401: "Unauthorized access. Please check your token or credentials."},
)
if response:
data = response.json()
repo_full_name = [repo["full_name"] for repo in data]
for repos in repo_full_name:
rich_output(f"- {repos}")
rich_output(f"\nTotal repositories: {len(repo_full_name)}")
def dependabot_security(name: str, enabled: bool, org: str = None):
is_enabled = bool(enabled)
owner = fetch_user()
headers = get_headers()
url = build_url("repos", org, name) if org else build_url("repos", owner, name)
security_urls = ["vulnerability-alerts", "automated-security-fixes"]
if is_enabled:
for endpoint in security_urls:
full_url = f"{url}/{endpoint}"
request_with_handling(
"PUT",
url=full_url,
headers=headers,
success_msg=f"Enabled {endpoint}",
error_msg={
401: "Unauthorized. Please check your credentials.",
},
)
else:
full_url = f"{url}/{security_urls[0]}"
request_with_handling(
"DELETE",
url=full_url,
headers=headers,
success_msg=f"Dependabot has been disabled on repository {org or owner}/{name}.",
error_msg={401: "Unauthorized. Please check your credentials."},
)
def deployment_environment(name: str, env: str, org: str = None):
owner = fetch_user()
headers = get_headers()
url = (
build_url("repos", org, name, "environments", env)
if org
else build_url("repos", owner, name, "environments", env)
)
return request_with_handling(
"PUT",
url,
headers=headers,
success_msg=f"Environment {env} has been created successfully in {org or owner}/{name}.",
error_msg={
422: f"Failed to create repository enviroment {owner or org}/{name}."
},
)