Skip to content

Commit 64d0da9

Browse files
fix(changelog): report an unwritable changelog file
`cz changelog --file path/to/CHANGELOG.md` crashed with a traceback when the file could not be written, for example when the parent directory does not exist: $ cz changelog --file /nope/CHANGELOG.md Traceback (most recent call last): File "commitizen/commands/changelog.py", line 166, in _write_changelog with smart_open( File "commitizen/git.py", line 206, in smart_open return open(name, mode, encoding=encoding) FileNotFoundError: [Errno 2] No such file or directory: '/nope/CHANGELOG.md' Every other command reports such a problem with a dedicated exception and exit code. This change adds `UnableToWriteChangelog` with the new `ExitCode.CHANGELOG_WRITE_FAILED` (33) and raises it from `_write_changelog`: $ cz changelog --file /nope/CHANGELOG.md Unable to write the changelog file '/nope/CHANGELOG.md': [Errno 2] No such file or directory: '/nope/CHANGELOG.md' $ echo $? 33 Unchanged: a writable `--file` path writes the changelog, `--dry-run` does not touch the filesystem, and the in-place `CHANGELOG.md` flow keeps working. Tests: `test_changelog_unwritable_file` in `tests/commands/test_changelog_command.py` covers the case (fails with the traceback before the change). Assisted By: AI
1 parent 4db7478 commit 64d0da9

3 files changed

Lines changed: 50 additions & 3 deletions

File tree

‎commitizen/commands/changelog.py‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
NoRevisionError,
1616
NotAGitProjectError,
1717
NotAllowed,
18+
UnableToWriteChangelog,
1819
)
1920
from commitizen.git import GitTag, smart_open
2021
from commitizen.tags import TagRules
@@ -163,9 +164,16 @@ def _find_incremental_rev(self, latest_version: str, tags: Iterable[GitTag]) ->
163164
def _write_changelog(
164165
self, changelog_out: str, lines: list[str], changelog_meta: changelog.Metadata
165166
) -> None:
166-
with smart_open(
167-
self.file_name, "w", encoding=self.config.settings["encoding"]
168-
) as changelog_file:
167+
try:
168+
changelog_handle = smart_open(
169+
self.file_name, "w", encoding=self.config.settings["encoding"]
170+
)
171+
except OSError as error:
172+
raise UnableToWriteChangelog(
173+
f"Unable to write the changelog file '{self.file_name}': {error}"
174+
) from error
175+
176+
with changelog_handle as changelog_file:
169177
partial_changelog: str | None = None
170178
if self.incremental:
171179
new_lines = changelog.incremental_build(

‎commitizen/exceptions.py‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ class ExitCode(IntEnum):
4040
CONFIG_FILE_NOT_FOUND = 30
4141
CONFIG_FILE_IS_EMPTY = 31
4242
COMMIT_MESSAGE_LENGTH_LIMIT_EXCEEDED = 32
43+
CHANGELOG_WRITE_FAILED = 33
4344

4445
@classmethod
4546
def from_str(cls, value: str) -> ExitCode:
@@ -226,6 +227,12 @@ class GitCommandError(CommitizenException):
226227
exit_code = ExitCode.GIT_COMMAND_ERROR
227228

228229

230+
class UnableToWriteChangelog(CommitizenException):
231+
"""The changelog file could not be written"""
232+
233+
exit_code = ExitCode.CHANGELOG_WRITE_FAILED
234+
235+
229236
class InvalidManualVersion(CommitizenException):
230237
"""Manually provided version is invalid"""
231238

‎tests/commands/test_changelog_command.py‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
from typing import TYPE_CHECKING
77

88
import pytest
9+
from unittest.mock import Mock
910
from jinja2 import FileSystemLoader
1011

1112
from commitizen import git
@@ -18,6 +19,7 @@
1819
NoRevisionError,
1920
NotAGitProjectError,
2021
NotAllowed,
22+
UnableToWriteChangelog,
2123
)
2224

2325
if TYPE_CHECKING:
@@ -183,6 +185,36 @@ def test_changelog_replacing_unreleased_using_incremental(
183185

184186
@pytest.mark.usefixtures("tmp_commitizen_project")
185187
@pytest.mark.freeze_time("2022-08-14")
188+
@pytest.mark.usefixtures("in_repo_root")
189+
def test_changelog_unwritable_file(tmp_path: Path):
190+
blocker = tmp_path / "blocker"
191+
blocker.write_text("not a directory", encoding="utf-8")
192+
193+
mock_config = Mock()
194+
mock_path = Mock(spec=Path)
195+
mock_path.parent = tmp_path
196+
mock_config.path = mock_path
197+
mock_config.settings = {
198+
"name": "cz_conventional_commits",
199+
"changelog_file": "CHANGELOG.md",
200+
"encoding": "utf-8",
201+
"tag_format": "$version",
202+
"legacy_tag_formats": [],
203+
"ignored_tag_formats": [],
204+
"incremental": False,
205+
"changelog_merge_prerelease": False,
206+
}
207+
changelog = Changelog(
208+
mock_config,
209+
{"file_name": str(blocker / "CHANGELOG.md"), "unreleased_version": "1.0.1"},
210+
)
211+
212+
with pytest.raises(UnableToWriteChangelog) as error:
213+
changelog._write_changelog("changelog body", [], Mock())
214+
215+
assert "Unable to write the changelog file" in str(error.value)
216+
217+
186218
def test_changelog_is_persisted_using_incremental(
187219
changelog_path: Path,
188220
file_regression: FileRegressionFixture,

0 commit comments

Comments
 (0)