Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 6ab2204

Browse files
committed
feat(bump): let it respect pre-commit reformats when bumping
Fix #502. Just add `--retry` to `cz bump` and it will attempt to commit twice if the 1st commit fails. Useful if your 1st commit runs a formatter that can for example change the contents of CHANGELOG.md.
1 parent 66c6320 commit 6ab2204

File tree

3 files changed

+67
-3
lines changed

3 files changed

+67
-3
lines changed

‎commitizen/cli.py‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,12 @@
165165
"default": False,
166166
"help": "Output changelog to the stdout",
167167
},
168+
{
169+
"name": ["--retry"],
170+
"action": "store_true",
171+
"default": False,
172+
"help": "retry commit if it fails the 1st time",
173+
},
168174
],
169175
},
170176
{

‎commitizen/commands/bump.py‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
from logging import getLogger
12
from typing import List, Optional
23

34
import questionary
@@ -18,6 +19,8 @@
1819
NoVersionSpecifiedError,
1920
)
2021

22+
logger = getLogger("commitizen")
23+
2124

2225
class Bump:
2326
"""Show prompt for the user to create a guided commit."""
@@ -49,6 +52,7 @@ def __init__(self, config: BaseConfig, arguments: dict):
4952
self.changelog_to_stdout = arguments["changelog_to_stdout"]
5053
self.no_verify = arguments["no_verify"]
5154
self.check_consistency = arguments["check_consistency"]
55+
self.retry = arguments["retry"]
5256

5357
def is_initial_tag(self, current_tag_version: str, is_yes: bool = False) -> bool:
5458
"""Check if reading the whole git tree up to HEAD is needed."""
@@ -209,16 +213,22 @@ def __call__(self): # noqa: C901
209213
},
210214
)
211215
changelog_cmd()
212-
c = cmd.run(f"git add {changelog_cmd.file_name}")
216+
c = cmd.run(f"git add {changelog_cmd.file_name}{' '.join(version_files)}")
213217

214218
self.config.set_key("version", str(new_version))
215219

216220
if is_files_only:
217221
raise ExpectedExit()
218222

219223
c = git.commit(message, args=self._get_commit_args())
224+
if self.retry and c.return_code != 0 and self.changelog:
225+
# Maybe pre-commit reformatted some files? Retry once
226+
logger.debug("1st git.commit error: %s", c.err)
227+
logger.info("1st commit attempt failed; retrying once")
228+
cmd.run(f"git add {changelog_cmd.file_name} {' '.join(version_files)}")
229+
c = git.commit(message, args=self._get_commit_args())
220230
if c.return_code != 0:
221-
raise BumpCommitFailedError(f'git.commit error: "{c.err.strip()}"')
231+
raise BumpCommitFailedError(f'2nd git.commit error: "{c.err.strip()}"')
222232
c = git.tag(
223233
new_tag_version,
224234
annotated=self.bump_settings.get("annotated_tag", False)

‎tests/test_bump_create_commit_message.py‎

Lines changed: 49 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,11 @@
1+
import sys
2+
from pathlib import Path
3+
from textwrap import dedent
4+
15
import pytest
26
from packaging.version import Version
37

4-
from commitizen import bump
8+
from commitizen import bump, cli, cmd
59

610
conversion = [
711
(
@@ -20,3 +24,47 @@ def test_create_tag(test_input, expected):
2024
Version(current_version), Version(new_version), message_template
2125
)
2226
assert new_tag == expected
27+
28+
29+
@pytest.mark.parametrize("retry", (True, False))
30+
def test_bump_pre_commit_changelog(tmp_commitizen_project, mocker, freezer, retry):
31+
freezer.move_to("2022年04月01日")
32+
testargs = ["cz", "bump", "--changelog", "--yes"]
33+
if retry:
34+
testargs.append("--retry")
35+
else:
36+
pytest.xfail("it will fail because pre-commit will reformat CHANGELOG.md")
37+
mocker.patch.object(sys, "argv", testargs)
38+
with tmp_commitizen_project.as_cwd():
39+
# Configure prettier as a pre-commit hook
40+
Path(".pre-commit-config.yaml").write_text(
41+
"""
42+
repos:
43+
- repo: https://github.com/pre-commit/mirrors-prettier
44+
rev: v2.6.2
45+
hooks:
46+
- id: prettier
47+
stages: [commit]
48+
"""
49+
)
50+
# Prettier inherits editorconfig
51+
Path(".editorconfig").write_text(
52+
"""
53+
[*]
54+
indent_size = 4
55+
"""
56+
)
57+
cmd.run("git add -A")
58+
cmd.run("git commit -m 'fix: _test'")
59+
cmd.run("pre-commit install")
60+
cli.main()
61+
# Pre-commit fixed last line adding extra indent and "\" char
62+
assert Path("CHANGELOG.md").read_text() == dedent(
63+
"""\
64+
## 0.1.1 (2022年04月01日)
65+
66+
### Fix
67+
68+
- \\_test
69+
"""
70+
)

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /