Skip to content

Commit 71f0781

Browse files
committed
chore: declass utils
1 parent d190d17 commit 71f0781

9 files changed

Lines changed: 104 additions & 97 deletions

File tree

homebrew_releaser/app.py

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,12 @@
3939
update_python_resources,
4040
)
4141
from homebrew_releaser.readme_updater import update_readme
42-
from homebrew_releaser.utils import Utils
42+
from homebrew_releaser.utils import (
43+
get_filename_from_path,
44+
get_working_dir,
45+
make_github_get_request,
46+
write_file,
47+
)
4348

4449

4550
GITHUB_BASE_URL = 'https://api.github.com'
@@ -84,8 +89,8 @@ def run_github_action():
8489
setup_git(COMMIT_OWNER, COMMIT_EMAIL, HOMEBREW_OWNER, HOMEBREW_TAP)
8590

8691
logger.info(f'Collecting data about {GITHUB_REPO}...')
87-
repository = Utils.make_github_get_request(url=f'{GITHUB_BASE_URL}/repos/{GITHUB_OWNER}/{GITHUB_REPO}').json()
88-
latest_release = Utils.make_github_get_request(
92+
repository = make_github_get_request(url=f'{GITHUB_BASE_URL}/repos/{GITHUB_OWNER}/{GITHUB_REPO}').json()
93+
latest_release = make_github_get_request(
8994
url=f'https://api.github.com/repos/{GITHUB_OWNER}/{GITHUB_REPO}/releases/latest'
9095
).json()
9196
assets = latest_release['assets']
@@ -144,7 +149,7 @@ def run_github_action():
144149
stream = False if archive_url.find("api.github.com") != -1 else True
145150
downloaded_filename = App.download_archive(download_url, stream)
146151
checksum = calculate_checksum(downloaded_filename)
147-
archive_filename = Utils.get_filename_from_path(archive_url)
152+
archive_filename = get_filename_from_path(archive_url)
148153
archive_checksum_entries += f'{checksum} {archive_filename}\n'
149154
checksums.append(
150155
{
@@ -157,7 +162,7 @@ def run_github_action():
157162
# We break here so we don't include duplicate checksums for the auto generated URLs
158163
break
159164

160-
Utils.write_file(CHECKSUM_FILE, archive_checksum_entries)
165+
write_file(CHECKSUM_FILE, archive_checksum_entries)
161166

162167
logger.info(f'Generating Homebrew formula for {GITHUB_REPO}...')
163168
template = generate_formula_data(
@@ -177,9 +182,9 @@ def run_github_action():
177182
)
178183

179184
formula_filename = f'{repository["name"]}.rb'
180-
formula_dir = Utils.get_working_dir(os.path.join(HOMEBREW_TAP, FORMULA_FOLDER))
185+
formula_dir = get_working_dir(os.path.join(HOMEBREW_TAP, FORMULA_FOLDER))
181186
formula_filepath = os.path.join(formula_dir, formula_filename)
182-
Utils.write_file(formula_filepath, template, 'w')
187+
write_file(formula_filepath, template, 'w')
183188

184189
if UPDATE_PYTHON_RESOURCES:
185190
logger.info('Attempting to update Python resources in the formula...')
@@ -245,12 +250,12 @@ def check_required_env_variables():
245250
@staticmethod
246251
def download_archive(url: str, stream: Optional[bool] = False) -> str:
247252
"""Gets an archive (eg: zip, tar) from GitHub and saves it locally."""
248-
response = Utils.make_github_get_request(
253+
response = make_github_get_request(
249254
url=url,
250255
stream=stream,
251256
)
252-
filename = Utils.get_filename_from_path(url)
253-
Utils.write_file(filename, response.content, 'wb')
257+
filename = get_filename_from_path(url)
258+
write_file(filename, response.content, 'wb')
254259

255260
return filename
256261

homebrew_releaser/checksum.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,15 +12,15 @@
1212
LOGGER_NAME,
1313
TIMEOUT,
1414
)
15-
from homebrew_releaser.utils import Utils
15+
from homebrew_releaser.utils import get_working_dir
1616

1717

1818
def calculate_checksum(tar_filepath: str) -> str:
1919
"""Gets the checksum of a file."""
2020
logger = woodchips.get(LOGGER_NAME)
2121

2222
try:
23-
with open(Utils.get_working_dir(tar_filepath), "rb") as content:
23+
with open(get_working_dir(tar_filepath), "rb") as content:
2424
checksum = hashlib.sha256(content.read()).hexdigest()
2525
logger.debug(f'Checksum for {tar_filepath} generated successfully: {checksum}')
2626
except Exception as error:
@@ -35,7 +35,7 @@ def upload_checksum_file(latest_release: dict[str, Any]):
3535

3636
latest_release_id = latest_release['id']
3737

38-
with open(Utils.get_working_dir(CHECKSUM_FILE), 'rb') as filename:
38+
with open(get_working_dir(CHECKSUM_FILE), 'rb') as filename:
3939
checksum_file_content = filename.read()
4040

4141
upload_url = f'https://uploads.github.com/repos/{GITHUB_OWNER}/{GITHUB_REPO}/releases/{latest_release_id}/assets?name={CHECKSUM_FILE}' # noqa

homebrew_releaser/git.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
LOGGER_NAME,
99
TIMEOUT,
1010
)
11-
from homebrew_releaser.utils import Utils
11+
from homebrew_releaser.utils import get_working_dir
1212

1313

1414
def setup_git(commit_owner: str, commit_email: str, homebrew_owner: str, homebrew_tap: str):
@@ -27,10 +27,10 @@ def setup_git(commit_owner: str, commit_email: str, homebrew_owner: str, homebre
2727
'clone',
2828
'--depth=1',
2929
f'https://x-access-token:{GITHUB_TOKEN}@github.com/{homebrew_owner}/{homebrew_tap}.git',
30-
Utils.get_working_dir(homebrew_tap),
30+
get_working_dir(homebrew_tap),
3131
],
32-
['git', '-C', Utils.get_working_dir(homebrew_tap), 'config', 'user.name', f'"{commit_owner}"'],
33-
['git', '-C', Utils.get_working_dir(homebrew_tap), 'config', 'user.email', commit_email],
32+
['git', '-C', get_working_dir(homebrew_tap), 'config', 'user.name', f'"{commit_owner}"'],
33+
['git', '-C', get_working_dir(homebrew_tap), 'config', 'user.email', commit_email],
3434
]
3535

3636
for command in commands:
@@ -41,22 +41,22 @@ def setup_git(commit_owner: str, commit_email: str, homebrew_owner: str, homebre
4141

4242
def add_git(homebrew_tap: str):
4343
"""Adds assets to a git commit."""
44-
command = ['git', '-C', Utils.get_working_dir(homebrew_tap), 'add', '.']
44+
command = ['git', '-C', get_working_dir(homebrew_tap), 'add', '.']
4545
_run_git_subprocess(command, 'Assets added to git commit successfully.')
4646

4747

4848
def commit_git(homebrew_tap: str, repo_name: str, version: str):
4949
"""Commits assets to the Homebrew tap (repo)."""
5050
# fmt: off
51-
command = ['git', '-C', Utils.get_working_dir(homebrew_tap), 'commit', '-m', f'chore: brew formula update for {repo_name} {version}'] # noqa
51+
command = ['git', '-C', get_working_dir(homebrew_tap), 'commit', '-m', f'chore: brew formula update for {repo_name} {version}'] # noqa
5252
# fmt: on
5353
_run_git_subprocess(command, 'Assets committed successfully.')
5454

5555

5656
def push_git(homebrew_tap: str, homebrew_owner: str):
5757
"""Pushes assets to the remote Homebrew tap (repo)."""
5858
# fmt: off
59-
command = ['git', '-C', Utils.get_working_dir(homebrew_tap), 'push', f'https://x-access-token:{GITHUB_TOKEN}@github.com/{homebrew_owner}/{homebrew_tap}.git'] # noqa
59+
command = ['git', '-C', get_working_dir(homebrew_tap), 'push', f'https://x-access-token:{GITHUB_TOKEN}@github.com/{homebrew_owner}/{homebrew_tap}.git'] # noqa
6060
# fmt: on
6161
_run_git_subprocess(command, f'Assets pushed successfully to {homebrew_tap}.')
6262

homebrew_releaser/readme_updater.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
FORMULA_FOLDER,
1414
LOGGER_NAME,
1515
)
16-
from homebrew_releaser.utils import Utils
16+
from homebrew_releaser.utils import get_working_dir
1717

1818

1919
TABLE_START_TAG = '<!-- project_table_start -->'
@@ -39,7 +39,7 @@ def _format_formula_data(homebrew_tap: str) -> list[dict[str, Any]]:
3939
"""Retrieve the name, description, and homepage from each
4040
Ruby formula file in the homebrew tap repo.
4141
"""
42-
homebrew_tap_path = Utils.get_working_dir(os.path.join(homebrew_tap, FORMULA_FOLDER))
42+
homebrew_tap_path = get_working_dir(os.path.join(homebrew_tap, FORMULA_FOLDER))
4343
formulas = []
4444
files = os.listdir(homebrew_tap_path)
4545

@@ -123,7 +123,7 @@ def _retrieve_old_table(homebrew_tap: str) -> Tuple[str, bool]:
123123
old_table = ''
124124

125125
if readme:
126-
with open(Utils.get_working_dir(readme), 'r') as readme_contents:
126+
with open(get_working_dir(readme), 'r') as readme_contents:
127127
for line in readme_contents:
128128
normalized_line = line.strip().lower()
129129
if normalized_line == TABLE_START_TAG:
@@ -157,7 +157,7 @@ def _read_current_readme(homebrew_tap: str) -> str:
157157
file_content = ""
158158

159159
if readme:
160-
with open(Utils.get_working_dir(readme), 'r') as readme_contents:
160+
with open(get_working_dir(readme), 'r') as readme_contents:
161161
file_content = readme_contents.read()
162162
logger.debug(f'{readme} read successfully.')
163163

@@ -173,7 +173,7 @@ def _replace_table_contents(file_content: str, old_table: str, new_table: str, h
173173
readme = _does_readme_exist(homebrew_tap)
174174

175175
if readme:
176-
with open(Utils.get_working_dir(readme), 'w') as readme_contents:
176+
with open(get_working_dir(readme), 'w') as readme_contents:
177177
readme_contents.write(file_content.replace(old_table, new_table))
178178
logger.debug(f'{readme} table updated successfully.')
179179

@@ -186,7 +186,7 @@ def _does_readme_exist(homebrew_tap: str) -> Optional[str]:
186186
"""
187187
readme_to_open = None
188188
readme_filename = 'readme.md'
189-
tap_dir = Utils.get_working_dir(homebrew_tap)
189+
tap_dir = get_working_dir(homebrew_tap)
190190
files = os.listdir(tap_dir)
191191

192192
for filename in files:

homebrew_releaser/utils.py

Lines changed: 44 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -12,49 +12,47 @@
1212
)
1313

1414

15-
class Utils:
16-
@staticmethod
17-
def make_github_get_request(url: str, stream: Optional[bool] = False) -> requests.Response:
18-
"""Make an HTTP GET request."""
19-
logger = woodchips.get(LOGGER_NAME)
20-
21-
headers = GITHUB_HEADERS.copy()
22-
if stream:
23-
headers['Accept'] = 'application/octet-stream'
24-
25-
try:
26-
response = requests.get(
27-
url,
28-
headers=headers,
29-
allow_redirects=True, # We need to allow redirects to reach various GitHub resources
30-
stream=stream,
31-
timeout=TIMEOUT,
32-
)
33-
response.raise_for_status()
34-
logger.debug(f'HTTP GET request made successfully to {url}.')
35-
except Exception as error:
36-
raise SystemExit(error)
37-
38-
return response
39-
40-
@staticmethod
41-
def write_file(file_path: str, content: str | bytes, mode: str = 'w'):
42-
"""Writes content to a file."""
43-
logger = woodchips.get(LOGGER_NAME)
44-
45-
try:
46-
with open(Utils.get_working_dir(file_path), mode) as f:
47-
f.write(content)
48-
logger.debug(f'{file_path} written successfully.')
49-
except Exception as error:
50-
raise SystemExit(error)
51-
52-
@staticmethod
53-
def get_filename_from_path(path: str) -> str:
54-
"""Gets the last part of a path (the filename)."""
55-
return path.rsplit('/', 1)[1]
56-
57-
@staticmethod
58-
def get_working_dir(additional_path: str) -> str:
59-
"""Gets the working directory."""
60-
return os.path.join(WORKING_DIR, additional_path)
15+
def make_github_get_request(url: str, stream: Optional[bool] = False) -> requests.Response:
16+
"""Make an HTTP GET request."""
17+
logger = woodchips.get(LOGGER_NAME)
18+
19+
headers = GITHUB_HEADERS.copy()
20+
if stream:
21+
headers['Accept'] = 'application/octet-stream'
22+
23+
try:
24+
response = requests.get(
25+
url,
26+
headers=headers,
27+
allow_redirects=True, # We need to allow redirects to reach various GitHub resources
28+
stream=stream,
29+
timeout=TIMEOUT,
30+
)
31+
response.raise_for_status()
32+
logger.debug(f'HTTP GET request made successfully to {url}.')
33+
except Exception as error:
34+
raise SystemExit(error)
35+
36+
return response
37+
38+
39+
def write_file(file_path: str, content: str | bytes, mode: str = 'w'):
40+
"""Writes content to a file."""
41+
logger = woodchips.get(LOGGER_NAME)
42+
43+
try:
44+
with open(get_working_dir(file_path), mode) as f:
45+
f.write(content)
46+
logger.debug(f'{file_path} written successfully.')
47+
except Exception as error:
48+
raise SystemExit(error)
49+
50+
51+
def get_filename_from_path(path: str) -> str:
52+
"""Gets the last part of a path (the filename)."""
53+
return path.rsplit('/', 1)[1]
54+
55+
56+
def get_working_dir(additional_path: str) -> str:
57+
"""Gets the working directory."""
58+
return os.path.join(WORKING_DIR, additional_path)

test/unit/test_app.py

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,11 @@
1212
@patch('homebrew_releaser.app.add_git')
1313
@patch('homebrew_releaser.app.commit_git')
1414
@patch('homebrew_releaser.app.push_git')
15-
@patch('homebrew_releaser.utils.Utils.write_file')
15+
@patch('homebrew_releaser.app.write_file')
1616
@patch('homebrew_releaser.app.generate_formula_data')
1717
@patch('homebrew_releaser.app.calculate_checksum', return_value=('123', 'mock-repo'))
1818
@patch('homebrew_releaser.app.App.download_archive')
19-
@patch('homebrew_releaser.utils.Utils.make_github_get_request')
19+
@patch('homebrew_releaser.app.make_github_get_request')
2020
@patch('homebrew_releaser.app.App.check_required_env_variables')
2121
def test_run_github_action_skip_commit(
2222
mock_check_env_variables,
@@ -54,11 +54,11 @@ def test_run_github_action_skip_commit(
5454
@patch('homebrew_releaser.app.add_git')
5555
@patch('homebrew_releaser.app.commit_git')
5656
@patch('homebrew_releaser.app.push_git')
57-
@patch('homebrew_releaser.utils.Utils.write_file')
57+
@patch('homebrew_releaser.app.write_file')
5858
@patch('homebrew_releaser.app.generate_formula_data')
5959
@patch('homebrew_releaser.app.calculate_checksum', return_value=('123', 'mock-repo'))
6060
@patch('homebrew_releaser.app.App.download_archive')
61-
@patch('homebrew_releaser.utils.Utils.make_github_get_request')
61+
@patch('homebrew_releaser.app.make_github_get_request')
6262
@patch('homebrew_releaser.app.App.check_required_env_variables')
6363
def test_run_github_action(
6464
mock_check_env_variables,
@@ -99,11 +99,11 @@ def test_run_github_action(
9999
@patch('homebrew_releaser.app.add_git')
100100
@patch('homebrew_releaser.app.commit_git')
101101
@patch('homebrew_releaser.app.push_git')
102-
@patch('homebrew_releaser.utils.Utils.write_file')
102+
@patch('homebrew_releaser.app.write_file')
103103
@patch('homebrew_releaser.app.generate_formula_data')
104104
@patch('homebrew_releaser.app.calculate_checksum', return_value=('123', 'mock-repo'))
105105
@patch('homebrew_releaser.app.App.download_archive')
106-
@patch('homebrew_releaser.utils.Utils.make_github_get_request')
106+
@patch('homebrew_releaser.app.make_github_get_request')
107107
@patch('homebrew_releaser.app.App.check_required_env_variables')
108108
def test_run_github_action_update_readme(
109109
mock_check_env_variables,
@@ -145,11 +145,11 @@ def test_run_github_action_update_readme(
145145
@patch('homebrew_releaser.app.add_git')
146146
@patch('homebrew_releaser.app.commit_git')
147147
@patch('homebrew_releaser.app.push_git')
148-
@patch('homebrew_releaser.utils.Utils.write_file')
148+
@patch('homebrew_releaser.app.write_file')
149149
@patch('homebrew_releaser.app.generate_formula_data')
150150
@patch('homebrew_releaser.app.calculate_checksum', return_value=('123', 'mock-repo'))
151151
@patch('homebrew_releaser.app.App.download_archive')
152-
@patch('homebrew_releaser.utils.Utils.make_github_get_request')
152+
@patch('homebrew_releaser.app.make_github_get_request')
153153
@patch('homebrew_releaser.app.App.check_required_env_variables')
154154
@patch('homebrew_releaser.app.update_python_resources')
155155
@patch('homebrew_releaser.app.setup_homebrew_tap')
@@ -198,11 +198,11 @@ def test_run_github_action_update_python_resources(
198198
@patch('homebrew_releaser.app.add_git')
199199
@patch('homebrew_releaser.app.commit_git')
200200
@patch('homebrew_releaser.app.push_git')
201-
@patch('homebrew_releaser.utils.Utils.write_file')
201+
@patch('homebrew_releaser.app.write_file')
202202
@patch('homebrew_releaser.app.generate_formula_data')
203203
@patch('homebrew_releaser.app.calculate_checksum', return_value=('123', 'mock-repo'))
204204
@patch('homebrew_releaser.app.App.download_archive')
205-
@patch('homebrew_releaser.utils.Utils.make_github_get_request')
205+
@patch('homebrew_releaser.app.make_github_get_request')
206206
@patch('homebrew_releaser.app.App.check_required_env_variables')
207207
def test_run_github_action_target_matrix(
208208
mock_check_env_variables,
@@ -265,8 +265,8 @@ def test_check_required_env_variables_missing_env_variable(mock_system_exit):
265265
)
266266

267267

268-
@patch('homebrew_releaser.utils.Utils.write_file')
269-
@patch('homebrew_releaser.utils.Utils.make_github_get_request')
268+
@patch('homebrew_releaser.app.write_file')
269+
@patch('homebrew_releaser.app.make_github_get_request')
270270
def test_download_public_archive(mock_make_github_get_request, mock_write_file):
271271
url = 'https://github.com/repos/Justintime50/homebrew-releaser/archive/refs/tags/v0.1.0.tar.gz'
272272
App.download_archive(url, True)
@@ -275,8 +275,8 @@ def test_download_public_archive(mock_make_github_get_request, mock_write_file):
275275
mock_write_file.assert_called_once() # TODO: Assert `called_with` here instead
276276

277277

278-
@patch('homebrew_releaser.utils.Utils.write_file')
279-
@patch('homebrew_releaser.utils.Utils.make_github_get_request')
278+
@patch('homebrew_releaser.app.write_file')
279+
@patch('homebrew_releaser.app.make_github_get_request')
280280
def test_download_private_archive(mock_make_github_get_request, mock_write_file):
281281
url = 'https://api.github.com/repos/Justintime50/homebrew-releaser/tarball/v0.1.0'
282282
App.download_archive(url, False)

0 commit comments

Comments
 (0)