Skip to content

Commit 8a99fe9

Browse files
committed
chore: unfurl unecessary try/except blocks
1 parent f1d03df commit 8a99fe9

9 files changed

Lines changed: 55 additions & 76 deletions

File tree

CHANGELOG.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
# CHANGELOG
22

3-
## Next Release
3+
## v3.1.0 (2025-12-26)
44

5-
- Changes order of git push and checksum upload operations essentially making any checksum upload failures decoupled from the ability to actually release. Any failures with checksum upload will occur after formula update pushes
65
- Adds `skip_checksum` parameter which skips uploading the checksum file for all release assets to the latest release. Useful if you generate your own checksums or already had a checksum file since we cannot overwrite an existing checksum file without deleting the previous one
6+
- Changes order of git push and checksum upload operations essentially making any checksum upload failures decoupled from the ability to actually release. Any failures with checksum upload will occur after formula update pushes
77
- Creates formula folder if it doesn't exist yet
88
- Fixes the formula dir path (regression introduced in v3.0.1, closes #67)
99

homebrew_releaser/_version.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
__version__ = "3.0.1"
1+
__version__ = "3.1.0"

homebrew_releaser/checksum.py

Lines changed: 11 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -19,12 +19,9 @@ def calculate_checksum(tar_filepath: str) -> str:
1919
"""Gets the checksum of a file."""
2020
logger = woodchips.get(LOGGER_NAME)
2121

22-
try:
23-
with open(build_dir_path(tar_filepath), "rb") as content:
24-
checksum = hashlib.sha256(content.read()).hexdigest()
25-
logger.debug(f"Checksum for {tar_filepath} generated successfully: {checksum}")
26-
except Exception as error:
27-
raise SystemExit(error)
22+
with open(build_dir_path(tar_filepath), "rb") as content:
23+
checksum = hashlib.sha256(content.read()).hexdigest()
24+
logger.debug(f"Checksum for {tar_filepath} generated successfully: {checksum}")
2825

2926
return checksum
3027

@@ -42,14 +39,11 @@ def upload_checksum_file(latest_release: dict[str, Any]):
4239
headers = GITHUB_HEADERS.copy()
4340
headers["Content-Type"] = "text/plain"
4441

45-
try:
46-
response = requests.post(
47-
upload_url,
48-
headers=headers,
49-
data=checksum_file_content,
50-
timeout=TIMEOUT,
51-
)
52-
response.raise_for_status()
53-
logger.info(f"checksum.txt uploaded successfully to {GITHUB_REPO}.")
54-
except requests.exceptions.RequestException as error:
55-
raise SystemExit(error)
42+
response = requests.post(
43+
upload_url,
44+
headers=headers,
45+
data=checksum_file_content,
46+
timeout=TIMEOUT,
47+
)
48+
response.raise_for_status()
49+
logger.info(f"checksum.txt uploaded successfully to {GITHUB_REPO}.")

homebrew_releaser/formula.py

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -195,16 +195,6 @@ def install
195195
end
196196
"""
197197

198-
def match_indent_of(tag: str, text: str) -> str:
199-
pattern = r"(?m)^(?P<indent>\s*)\{\{\{\s*" + re.escape(tag) + r"\s*\}\}\}"
200-
matching_line = re.search(pattern, template)
201-
indent = matching_line and matching_line["indent"] or ""
202-
# Indent by the same amount as the template tag
203-
indented_text = textwrap.indent(text.strip(), indent)
204-
# Strip the indentation from the first line, because
205-
# the template will render it indented already
206-
return indented_text.lstrip()
207-
208198
target_darwin = True if TARGET_DARWIN_AMD64 or TARGET_DARWIN_ARM64 else False
209199
target_linux = True if TARGET_LINUX_AMD64 or TARGET_LINUX_ARM64 else False
210200

@@ -217,11 +207,13 @@ def match_indent_of(tag: str, text: str) -> str:
217207
"autogenerated_tar_checksum": autogenerated_tar_checksum,
218208
"license_type": license_type,
219209
"dependencies": dependencies_list,
220-
"install_instructions": match_indent_of("install_instructions", install),
221-
"test_instructions": match_indent_of("test_instructions", test) if test else None,
210+
"install_instructions": _match_indent_of(template, "install_instructions", install),
211+
"test_instructions": _match_indent_of(template, "test_instructions", test) if test else None,
222212
"download_strategy": download_strategy,
223213
"custom_require": custom_require,
224-
"formula_includes": match_indent_of("formula_includes", formula_includes) if formula_includes else None,
214+
"formula_includes": (
215+
_match_indent_of(template, "formula_includes", formula_includes) if formula_includes else None
216+
),
225217
"version": version,
226218
"darwin_amd64_url": darwin_amd64_url,
227219
"darwin_amd64_checksum": darwin_amd64_checksum,
@@ -254,6 +246,18 @@ def match_indent_of(tag: str, text: str) -> str:
254246
return rendered_template
255247

256248

249+
def _match_indent_of(template: str, tag: str, text: str) -> str:
250+
"""Matches the indentation of a template tag for proper formatting."""
251+
pattern = r"(?m)^(?P<indent>\s*)\{\{\{\s*" + re.escape(tag) + r"\s*\}\}\}"
252+
matching_line = re.search(pattern, template)
253+
indent = matching_line and matching_line["indent"] or ""
254+
# Indent by the same amount as the template tag
255+
indented_text = textwrap.indent(text.strip(), indent)
256+
# Strip the indentation from the first line, because
257+
# the template will render it indented already
258+
return indented_text.lstrip()
259+
260+
257261
def _generate_class_name(repo_name: str) -> str:
258262
"""Generates a Homebrew compatible formula class name.
259263

homebrew_releaser/git.py

Lines changed: 8 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -81,18 +81,11 @@ def _run_git_subprocess(command: list[str], debug_message: Optional[str] = None)
8181
"""Runs a git subprocess."""
8282
logger = woodchips.get(LOGGER_NAME)
8383

84-
try:
85-
subprocess.check_output( # nosec
86-
command,
87-
stderr=subprocess.STDOUT,
88-
text=True,
89-
timeout=TIMEOUT,
90-
)
91-
if debug_message:
92-
logger.debug(debug_message)
93-
except subprocess.CalledProcessError as error:
94-
logger.critical(error.output)
95-
raise
96-
except Exception as error:
97-
logger.critical(error)
98-
raise
84+
subprocess.check_output( # nosec
85+
command,
86+
stderr=subprocess.STDOUT,
87+
text=True,
88+
timeout=TIMEOUT,
89+
)
90+
if debug_message:
91+
logger.debug(debug_message)

homebrew_releaser/homebrew.py

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,6 @@ def update_python_resources(formula_dir: str, formula_filename: str) -> None:
2424
shell=True, # nosec
2525
)
2626
logger.info("Updated Python resources successfully.")
27-
except subprocess.TimeoutExpired:
28-
raise SystemExit("Timed out updating Python resources")
2927
except subprocess.CalledProcessError as e:
3028
error_output = e.output if hasattr(e, "output") else ""
3129

@@ -47,8 +45,6 @@ def setup_homebrew_tap(homebrew_owner: str, homebrew_tap: str) -> None:
4745
shell=True, # nosec
4846
)
4947
logger.info("Set up Homebrew tap successfully.")
50-
except subprocess.TimeoutExpired:
51-
raise SystemExit("Timed out setting up Homebrew tap")
5248
except subprocess.CalledProcessError as e:
5349
error_output = e.output if hasattr(e, "output") else ""
5450

@@ -67,8 +63,6 @@ def get_homebrew_version() -> str:
6763
timeout=TIMEOUT,
6864
shell=True, # nosec
6965
)
70-
except subprocess.TimeoutExpired:
71-
raise SystemExit("Timed out getting Homebrew version")
7266
except subprocess.CalledProcessError as e:
7367
error_output = e.output if hasattr(e, "output") else ""
7468

homebrew_releaser/utils.py

Lines changed: 12 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -20,18 +20,15 @@ def make_github_get_request(url: str, stream: Optional[bool] = False) -> request
2020
if stream:
2121
headers["Accept"] = "application/octet-stream"
2222

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)
23+
response = requests.get(
24+
url,
25+
headers=headers,
26+
allow_redirects=True, # We need to allow redirects to reach various GitHub resources
27+
stream=stream,
28+
timeout=TIMEOUT,
29+
)
30+
response.raise_for_status()
31+
logger.debug(f"HTTP GET request made successfully to {url}.")
3532

3633
return response
3734

@@ -40,12 +37,9 @@ def write_file(file_path: str, content: str | bytes, mode: str = "w"):
4037
"""Writes content to a file."""
4138
logger = woodchips.get(LOGGER_NAME)
4239

43-
try:
44-
with open(build_dir_path(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)
40+
with open(build_dir_path(file_path), mode) as f:
41+
f.write(content)
42+
logger.debug(f"{file_path} written successfully.")
4943

5044

5145
def get_filename_from_path(path: str) -> str:

test/unit/test_checksum.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ def test_calculate_checksum():
2525
"subprocess.check_output", side_effect=subprocess.CalledProcessError(returncode=1, cmd="subprocess.check_output")
2626
)
2727
def test_calculate_checksum_process_error(mock_subprocess, mock_tar_filename):
28-
with pytest.raises(SystemExit):
28+
with pytest.raises(FileNotFoundError):
2929
calculate_checksum(mock_tar_filename)
3030

3131

@@ -46,7 +46,7 @@ def test_upload_checksum_file(mock_make_github_get_request, mock_post_request):
4646
def test_upload_checksum_file_error_on_upload(mock_make_github_get_request, mock_post_request):
4747
"""Tests that we exit on error to upload checksum.txt file."""
4848
with patch("builtins.open", mock_open()):
49-
with pytest.raises(SystemExit) as error:
49+
with pytest.raises(requests.exceptions.RequestException) as error:
5050
upload_checksum_file({"id": 1, "tag_name": "v1.0.0"})
5151

5252
mock_post_request.assert_called_once()

test/unit/test_utils.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ def test_make_github_get_request_stream(mock_request):
4949
@patch("requests.get", side_effect=requests.exceptions.RequestException("mock-error"))
5050
def test_make_github_get_request_exception(mock_request):
5151
url = "https://api.github.com/repos/Justintime50/homebrew-releaser"
52-
with pytest.raises(SystemExit) as error:
52+
with pytest.raises(requests.exceptions.RequestException) as error:
5353
make_github_get_request(url=url)
5454

5555
assert "mock-error" == str(error.value)
@@ -63,7 +63,7 @@ def test_write_file():
6363
def test_write_file_exception():
6464
with patch("builtins.open", mock_open()) as mock_open_file:
6565
mock_open_file.side_effect = Exception
66-
with pytest.raises(SystemExit):
66+
with pytest.raises(Exception):
6767
write_file("mock-file", "mock-content", mode="w")
6868

6969

0 commit comments

Comments
 (0)