From 53e1c9d2a789f6e7df22fc17314c8480651010a6 Mon Sep 17 00:00:00 2001 From: Daryl Bubune Date: Tue, 24 Nov 2026 22:52:25 -0400 Subject: [PATCH 1/5] refactor(bump): rename ambiguous variable c in Bump.__call__ The variable c held the git commit result and then the git tag result. Use commit_result and tag_result so each name tells what it holds. --- commitizen/commands/bump.py | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/commitizen/commands/bump.py b/commitizen/commands/bump.py index 3e92775e2..634ac2905 100644 --- a/commitizen/commands/bump.py +++ b/commitizen/commands/bump.py @@ -394,23 +394,23 @@ def __call__(self) -> None: # FIXME: check if any changes have been staged git.add(*updated_files) - c = git.commit(message, args=self._get_commit_args()) - if self.retry and c.return_code != 0 and self.changelog_flag: + commit_result = git.commit(message, args=self._get_commit_args()) + if self.retry and commit_result.return_code != 0 and self.changelog_flag: # Maybe pre-commit reformatted some files? Retry once - logger.debug("1st git.commit error: %s", c.err) + logger.debug("1st git.commit error: %s", commit_result.err) logger.info("1st commit attempt failed; retrying once") git.add(*updated_files) - c = git.commit(message, args=self._get_commit_args()) - if c.return_code != 0: - err = c.err.strip() or c.out + commit_result = git.commit(message, args=self._get_commit_args()) + if commit_result.return_code != 0: + err = commit_result.err.strip() or commit_result.out raise BumpCommitFailedError(f'2nd git.commit error: "{err}"') - for msg in (c.out, c.err): + for msg in (commit_result.out, commit_result.err): if msg: out_func = out.diagnostic if self.git_output_to_stderr else out.write out_func(msg) - c = git.tag( + tag_result = git.tag( new_tag_version, signed=any( ( @@ -428,8 +428,8 @@ def __call__(self) -> None: msg=self.bump_settings.get("annotated_tag_message", None), # TODO: also get from self.config.settings? ) - if c.return_code != 0: - raise BumpTagFailedError(c.err) + if tag_result.return_code != 0: + raise BumpTagFailedError(tag_result.err) if self.post_bump_hooks: hooks.run( From 69f73f62a2d6d1f6db151497194cc32eb75d6c26 Mon Sep 17 00:00:00 2001 From: Daryl Bubune Date: Tue, 24 Nov 2026 23:37:08 -0400 Subject: [PATCH 2/5] refactor(bump): name the tag signing and annotation conditions Move the two inline any() expressions out of the git.tag() call into should_sign_tag and should_annotate_tag. --- commitizen/commands/bump.py | 29 +++++++++++++++-------------- 1 file changed, 15 insertions(+), 14 deletions(-) diff --git a/commitizen/commands/bump.py b/commitizen/commands/bump.py index 634ac2905..4d7329d64 100644 --- a/commitizen/commands/bump.py +++ b/commitizen/commands/bump.py @@ -409,22 +409,23 @@ def __call__(self) -> None: if msg: out_func = out.diagnostic if self.git_output_to_stderr else out.write out_func(msg) - + should_sign_tag = any( + ( + self.bump_settings.get("gpg_sign"), + self.config.settings.get("gpg_sign"), + ) + ) + should_annotate_tag = any( + ( + self.bump_settings.get("annotated_tag"), + self.config.settings.get("annotated_tag"), + self.bump_settings.get("annotated_tag_message"), + ) + ) tag_result = git.tag( new_tag_version, - signed=any( - ( - self.bump_settings.get("gpg_sign"), - self.config.settings.get("gpg_sign"), - ) - ), - annotated=any( - ( - self.bump_settings.get("annotated_tag"), - self.config.settings.get("annotated_tag"), - self.bump_settings.get("annotated_tag_message"), - ) - ), + signed=should_sign_tag, + annotated=should_annotate_tag, msg=self.bump_settings.get("annotated_tag_message", None), # TODO: also get from self.config.settings? ) From cd8d79c2ed2911c67bb2127ae0fc06cd382c28dc Mon Sep 17 00:00:00 2001 From: Daryl Bubune Date: Tue, 24 Nov 2026 23:57:20 -0400 Subject: [PATCH 3/5] refactor(bump): extract bump eligibility and commit retry checks The "no increment and same tag" condition was written twice in __call__. Move it to _is_not_eligible_for_bump. Move the commit retry condition to _should_retry_commit. --- commitizen/commands/bump.py | 30 ++++++++++++++++++++++++++---- 1 file changed, 26 insertions(+), 4 deletions(-) diff --git a/commitizen/commands/bump.py b/commitizen/commands/bump.py index 4d7329d64..5fd344b13 100644 --- a/commitizen/commands/bump.py +++ b/commitizen/commands/bump.py @@ -6,7 +6,7 @@ import questionary -from commitizen import bump, factory, git, hooks, out +from commitizen import bump, cmd, factory, git, hooks, out from commitizen.changelog_formats import get_changelog_format from commitizen.commands.changelog import Changelog from commitizen.defaults import Settings @@ -289,7 +289,9 @@ def __call__(self) -> None: new_tag_version = rules.normalize_tag(new_version) if next_version_to_stdout: - if increment is None and new_tag_version == current_tag_version: + if self._is_not_eligible_for_bump( + increment, new_tag_version, current_tag_version + ): raise NoneIncrementExit( "[NO_COMMITS_TO_BUMP]\n" "The commits found are not eligible to be bumped" @@ -313,7 +315,9 @@ def __call__(self) -> None: else: out.write(information) - if increment is None and new_tag_version == current_tag_version: + if self._is_not_eligible_for_bump( + increment, new_tag_version, current_tag_version + ): raise NoneIncrementExit( "[NO_COMMITS_TO_BUMP]\nThe commits found are not eligible to be bumped" ) @@ -395,7 +399,7 @@ def __call__(self) -> None: # FIXME: check if any changes have been staged git.add(*updated_files) commit_result = git.commit(message, args=self._get_commit_args()) - if self.retry and commit_result.return_code != 0 and self.changelog_flag: + if self._should_retry_commit(commit_result): # Maybe pre-commit reformatted some files? Retry once logger.debug("1st git.commit error: %s", commit_result.err) logger.info("1st commit attempt failed; retrying once") @@ -452,6 +456,24 @@ def __call__(self) -> None: else: out.success("Done!") + @staticmethod + def _is_not_eligible_for_bump( + increment: Increment | None, + new_tag_version: str, + current_tag_version: str, + ) -> bool: + """No increment was detected and the tag would not change.""" + return increment is None and new_tag_version == current_tag_version + + def _should_retry_commit(self, commit_result: cmd.Command) -> bool: + """Retry once if the commit failed and a changelog was generated. + + A pre-commit hook may have reformatted the changelog, so a second + attempt can succeed. + """ + commit_failed = commit_result.return_code != 0 + return self.retry and commit_failed and self.changelog_flag + def _get_commit_args(self) -> list[str]: commit_args = ["-a"] if self.no_verify: From 690a41f960fab5e3b0434a5d2b31a964dfac9b79 Mon Sep 17 00:00:00 2001 From: Daryl Bubune Date: Wed, 25 Nov 2026 08:43:06 -0400 Subject: [PATCH 4/5] refactor(bump): extract changelog generation from Bump.__call__ Move the changelog block into _update_changelog to make __call__ shorter. No change in behavior. --- commitizen/commands/bump.py | 59 +++++++++++++++++++------------------ 1 file changed, 31 insertions(+), 28 deletions(-) diff --git a/commitizen/commands/bump.py b/commitizen/commands/bump.py index 5fd344b13..58ddf8822 100644 --- a/commitizen/commands/bump.py +++ b/commitizen/commands/bump.py @@ -326,34 +326,7 @@ def __call__(self) -> None: changelog_file_name = None dry_run = self.arguments["dry_run"] if self.changelog_flag: - changelog_args = { - "unreleased_version": new_tag_version, - "template": self.template, - "extras": self.extras, - "incremental": True, - "dry_run": dry_run, - # governs logic for merge_prerelease - "during_version_bump": self.arguments["prerelease"] is None, - } - if self.changelog_to_stdout: - try: - Changelog( - self.config, - {**changelog_args, "dry_run": True}, # type: ignore[typeddict-item] - )() - except DryRunExit: - pass - - changelog_cmd = Changelog( - self.config, - { - **changelog_args, # type: ignore[typeddict-item] - "file_name": self.file_name, - "allow_no_commit": bool(self.arguments["allow_no_commit"]), - }, - ) - changelog_cmd() - changelog_file_name = changelog_cmd.file_name + changelog_file_name = self._update_changelog(new_tag_version, dry_run) updated_files.append(changelog_file_name) # Do not perform operations over files or git. @@ -456,6 +429,36 @@ def __call__(self) -> None: else: out.success("Done!") + def _update_changelog(self, new_tag_version: str, dry_run: bool) -> str: + """Generate the changelog for the new version and return its file name.""" + changelog_args = { + "unreleased_version": new_tag_version, + "template": self.template, + "extras": self.extras, + "incremental": True, + "dry_run": dry_run, + # governs logic for merge_prerelease + "during_version_bump": self.arguments["prerelease"] is None, + } + if self.changelog_to_stdout: + try: + Changelog( + self.config, + {**changelog_args, "dry_run": True}, # type: ignore[typeddict-item] + )() + except DryRunExit: + pass + changelog_cmd = Changelog( + self.config, + { + **changelog_args, # type: ignore[typeddict-item] + "file_name": self.file_name, + "allow_no_commit": bool(self.arguments["allow_no_commit"]), + }, + ) + changelog_cmd() + return changelog_cmd.file_name + @staticmethod def _is_not_eligible_for_bump( increment: Increment | None, From 06e8ef16463425c23702c049b6e4d87d7255b05f Mon Sep 17 00:00:00 2001 From: Daryl Bubune Date: Wed, 25 Nov 2026 11:15:49 -0400 Subject: [PATCH 5/5] refactor(bump): extract GitReleasePublisher from Bump Bump decided what to release and also wrote it to git. Move the commit, retry and tag steps and their three settings into GitReleasePublisher. Add tests for retry and for commit and tag errors. --- commitizen/commands/bump.py | 97 ++++++++++++++++++++++------- tests/test_git_release_publisher.py | 76 ++++++++++++++++++++++ 2 files changed, 150 insertions(+), 23 deletions(-) create mode 100644 tests/test_git_release_publisher.py diff --git a/commitizen/commands/bump.py b/commitizen/commands/bump.py index 58ddf8822..839315891 100644 --- a/commitizen/commands/bump.py +++ b/commitizen/commands/bump.py @@ -99,10 +99,12 @@ def __init__(self, config: BaseConfig, arguments: BumpArgs) -> None: self.cz = factory.committer_factory(self.config) self.changelog_flag = arguments["changelog"] self.changelog_to_stdout = arguments["changelog_to_stdout"] - self.git_output_to_stderr = arguments["git_output_to_stderr"] - self.no_verify = arguments["no_verify"] self.check_consistency = arguments["check_consistency"] - self.retry = arguments["retry"] + self.git_publisher = GitReleasePublisher( + no_verify=arguments["no_verify"], + retry=arguments["retry"], + git_output_to_stderr=arguments["git_output_to_stderr"], + ) self.pre_bump_hooks = self.config.settings["pre_bump_hooks"] self.post_bump_hooks = self.config.settings["post_bump_hooks"] deprecated_version_type = arguments.get("version_type") @@ -370,22 +372,10 @@ def __call__(self) -> None: raise ExpectedExit() # FIXME: check if any changes have been staged - git.add(*updated_files) - commit_result = git.commit(message, args=self._get_commit_args()) - if self._should_retry_commit(commit_result): - # Maybe pre-commit reformatted some files? Retry once - logger.debug("1st git.commit error: %s", commit_result.err) - logger.info("1st commit attempt failed; retrying once") - git.add(*updated_files) - commit_result = git.commit(message, args=self._get_commit_args()) - if commit_result.return_code != 0: - err = commit_result.err.strip() or commit_result.out - raise BumpCommitFailedError(f'2nd git.commit error: "{err}"') + self.git_publisher.commit( + message, updated_files, changelog_was_updated=self.changelog_flag + ) - for msg in (commit_result.out, commit_result.err): - if msg: - out_func = out.diagnostic if self.git_output_to_stderr else out.write - out_func(msg) should_sign_tag = any( ( self.bump_settings.get("gpg_sign"), @@ -399,15 +389,13 @@ def __call__(self) -> None: self.bump_settings.get("annotated_tag_message"), ) ) - tag_result = git.tag( + self.git_publisher.tag( new_tag_version, signed=should_sign_tag, annotated=should_annotate_tag, msg=self.bump_settings.get("annotated_tag_message", None), # TODO: also get from self.config.settings? ) - if tag_result.return_code != 0: - raise BumpTagFailedError(tag_result.err) if self.post_bump_hooks: hooks.run( @@ -468,14 +456,77 @@ def _is_not_eligible_for_bump( """No increment was detected and the tag would not change.""" return increment is None and new_tag_version == current_tag_version - def _should_retry_commit(self, commit_result: cmd.Command) -> bool: + +class GitReleasePublisher: + """Commit the bumped files and create the release tag. + + Bump decides what to release. This class writes the release to git. + + Attributes: + no_verify: Skip the git hooks on commit. + retry: Retry a failed commit once when the changelog was updated. + git_output_to_stderr: Write the git output to stderr, not stdout. + + Example: + ```python + publisher = GitReleasePublisher(no_verify=False, retry=True, git_output_to_stderr=False) + publisher.commit("bump: 1.0.0 → 1.1.0", ["pyproject.toml"], changelog_was_updated=False) + publisher.tag("v1.1.0", signed=False, annotated=True, msg=None) + ``` + """ + + def __init__( + self, *, no_verify: bool, retry: bool, git_output_to_stderr: bool + ) -> None: + self.no_verify = no_verify + self.retry = retry + self.git_output_to_stderr = git_output_to_stderr + + def commit( + self, message: str, files: list[str], *, changelog_was_updated: bool + ) -> None: + """Stage the files and commit them. + + Raises: + BumpCommitFailedError: The commit failed. + """ + git.add(*files) + commit_result = git.commit(message, args=self._get_commit_args()) + if self._should_retry_commit(commit_result, changelog_was_updated): + # Maybe pre-commit reformatted some files? Retry once + logger.debug("1st git.commit error: %s", commit_result.err) + logger.info("1st commit attempt failed; retrying once") + git.add(*files) + commit_result = git.commit(message, args=self._get_commit_args()) + if commit_result.return_code != 0: + err = commit_result.err.strip() or commit_result.out + raise BumpCommitFailedError(f'2nd git.commit error: "{err}"') + + for msg in (commit_result.out, commit_result.err): + if msg: + out_func = out.diagnostic if self.git_output_to_stderr else out.write + out_func(msg) + + def tag(self, name: str, *, signed: bool, annotated: bool, msg: str | None) -> None: + """Create the release tag. + + Raises: + BumpTagFailedError: The tag could not be created. + """ + tag_result = git.tag(name, signed=signed, annotated=annotated, msg=msg) + if tag_result.return_code != 0: + raise BumpTagFailedError(tag_result.err) + + def _should_retry_commit( + self, commit_result: cmd.Command, changelog_was_updated: bool + ) -> bool: """Retry once if the commit failed and a changelog was generated. A pre-commit hook may have reformatted the changelog, so a second attempt can succeed. """ commit_failed = commit_result.return_code != 0 - return self.retry and commit_failed and self.changelog_flag + return self.retry and commit_failed and changelog_was_updated def _get_commit_args(self) -> list[str]: commit_args = ["-a"] diff --git a/tests/test_git_release_publisher.py b/tests/test_git_release_publisher.py new file mode 100644 index 000000000..6d814ac85 --- /dev/null +++ b/tests/test_git_release_publisher.py @@ -0,0 +1,76 @@ +import pytest +from pytest_mock import MockerFixture + +from commitizen import cmd +from commitizen.commands.bump import GitReleasePublisher +from commitizen.exceptions import BumpCommitFailedError, BumpTagFailedError + + +def _result(return_code: int) -> cmd.Command: + err = "error" if return_code else "" + return cmd.Command( + out="", err=err, stdout=b"", stderr=err.encode(), return_code=return_code + ) + + +def _publisher(*, retry: bool = False, no_verify: bool = False) -> GitReleasePublisher: + return GitReleasePublisher( + no_verify=no_verify, retry=retry, git_output_to_stderr=False + ) + + +def test_commit_retries_once_when_changelog_was_updated(mocker: MockerFixture): + """A pre-commit hook can reformat the changelog, so the second commit succeeds.""" + # Arrange + mocker.patch("commitizen.git.add") + commit_mock = mocker.patch( + "commitizen.git.commit", side_effect=[_result(1), _result(0)] + ) + + # Act + _publisher(retry=True).commit( + "bump: 1.0.0 → 1.1.0", ["CHANGELOG.md"], changelog_was_updated=True + ) + + # Assert + assert commit_mock.call_count == 2 + + +def test_commit_does_not_retry_without_changelog(mocker: MockerFixture): + # Arrange + mocker.patch("commitizen.git.add") + commit_mock = mocker.patch("commitizen.git.commit", return_value=_result(1)) + + # Act + with pytest.raises(BumpCommitFailedError): + _publisher(retry=True).commit( + "bump: 1.0.0 → 1.1.0", ["pyproject.toml"], changelog_was_updated=False + ) + + # Assert + assert commit_mock.call_count == 1 + + +def test_commit_passes_no_verify(mocker: MockerFixture): + # Arrange + mocker.patch("commitizen.git.add") + commit_mock = mocker.patch("commitizen.git.commit", return_value=_result(0)) + + # Act + _publisher(no_verify=True).commit( + "bump: 1.0.0 → 1.1.0", ["pyproject.toml"], changelog_was_updated=False + ) + + # Assert + commit_mock.assert_called_once_with( + "bump: 1.0.0 → 1.1.0", args=["-a", "--no-verify"] + ) + + +def test_tag_failure_raises(mocker: MockerFixture): + # Arrange + mocker.patch("commitizen.git.tag", return_value=_result(1)) + + # Act / Assert + with pytest.raises(BumpTagFailedError): + _publisher().tag("v1.1.0", signed=False, annotated=False, msg=None)