diff --git a/commitizen/commands/bump.py b/commitizen/commands/bump.py index 3e92775e2..839315891 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 @@ -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") @@ -289,7 +291,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 +317,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" ) @@ -322,34 +328,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. @@ -393,43 +372,30 @@ def __call__(self) -> None: raise ExpectedExit() # 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: - # Maybe pre-commit reformatted some files? Retry once - logger.debug("1st git.commit error: %s", c.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 - raise BumpCommitFailedError(f'2nd git.commit error: "{err}"') - - for msg in (c.out, c.err): - if msg: - out_func = out.diagnostic if self.git_output_to_stderr else out.write - out_func(msg) + self.git_publisher.commit( + message, updated_files, changelog_was_updated=self.changelog_flag + ) - c = git.tag( + 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"), + ) + ) + self.git_publisher.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? ) - if c.return_code != 0: - raise BumpTagFailedError(c.err) if self.post_bump_hooks: hooks.run( @@ -451,6 +417,117 @@ 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, + 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 + + +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 changelog_was_updated + def _get_commit_args(self) -> list[str]: commit_args = ["-a"] if self.no_verify: 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)