-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathutils.py
More file actions
169 lines (129 loc) · 4.22 KB
/
Copy pathutils.py
File metadata and controls
169 lines (129 loc) · 4.22 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
"""Utility functions for GitHub Actions"""
import http.client
import json
import os
import urllib.parse
from typing import Any, Dict, Optional, Tuple, Union
def get_input(key: str) -> str:
"""
Read the GitHub action input.
Args:
key (str): Input key.
Returns:
str: The value of the input.
"""
key = key.upper()
return os.environ[f"INPUT_{key}"]
def get_boolean_input(key: str) -> bool:
"""
Parse the input environment key of boolean type in the YAML 1.2
"core schema" specification.
Support boolean input list:
`true | True | TRUE | false | False | FALSE`.
ref: https://yaml.org/spec/1.2/spec.html#id2804923
Args:
key (str): Input key.
Returns:
bool: The parsed boolean value.
Raises:
TypeError: If the environment variable's value does not meet the
YAML 1.2 "core schema" specification for booleans.
"""
val = get_input(key)
if val.upper() == "TRUE":
return True
if val.upper() == "FALSE":
return False
raise TypeError(
"""
Input does not meet YAML 1.2 "Core Schema" specification.\n'
Support boolean input list:
`true | True | TRUE | false | False | FALSE`.
"""
)
def get_int_input(key: str) -> int | None:
"""
Read the GitHub action integer input.
Args:
key: Input key.
Returns:
The integer value of the input. If not integer, returns None
Raises:
ValueError: If the value is a non-empty, non-integer string.
"""
val = get_input(key)
if val == "":
# GitHub Action passes empty data as a empty string ("")
return None
try:
return int(val)
except ValueError:
raise ValueError(f"Input '{key}' must be a valid integer.") from None
def get_positive_int_input(key: str) -> int | None:
"""
Read the GitHub action integer input.
Args:
key: Input key.
Returns:
The integer value of the input. If not integer, returns None
Raises:
ValueError: If the value is a non-empty, non-integer string.
"""
int_val = get_int_input(key)
if int_val is not None and int_val <= 0:
raise ValueError(f"Input '{key}' must be a positive integer.")
return int_val
def write_line_to_file(filepath: str, line: str) -> None:
"""
Write line to a specified filepath.
Args:
filepath (str): The path of the file.
line (str): The Line to write in the file.
"""
with open(file=filepath, mode="a", encoding="utf-8") as output_file:
output_file.write(f"{line}\n")
def write_output(name: str, value: Union[str, int]) -> None:
"""
Write an output to the GitHub Actions environment.
Args:
name (str): The name of the output variable.
value (Union[str, int]): The value to be assigned to the output variable.
"""
output_filepath = os.environ["GITHUB_OUTPUT"]
write_line_to_file(output_filepath, f"{name}={value}")
def request_github_api(
method: str,
url: str,
token: str,
body: Optional[Dict[str, Any]] = None,
params: Optional[Dict[str, Any]] = None,
) -> Tuple[int, Any]:
"""
Sends a request to the GitHub API.
Args:
method (str): The HTTP request method, e.g., "GET" or "POST".
url (str): The endpoint URL for the GitHub API.
token (str): The GitHub API token for authentication.
body (Optional[Dict[str, Any]]): The request body as a dictionary.
params (Optional[Dict[str, str]]): The query parameters as a dictionary.
Returns:
Tuple[int, Any]: A tuple with the status as the first element and the response
data as the second element.
"""
if params:
url += "?" + urllib.parse.urlencode(params)
conn = http.client.HTTPSConnection(host="api.github.com")
conn.request(
method=method,
url=url,
body=json.dumps(body) if body else None,
headers={
"Authorization": f"Bearer {token}",
"Content-Type": "application/json",
"User-Agent": "commitlint",
},
)
res = conn.getresponse()
json_data = res.read().decode("utf-8")
data = json.loads(json_data)
return res.status, data