Skip to content

Commit 935be91

Browse files
BogayLee-W
authored andcommitted
refactor(init): _install_pre_commit_hook raise error when failed
instead of returning a `False` value.
1 parent 2da0f39 commit 935be91

File tree

2 files changed

+28
-22
lines changed

2 files changed

+28
-22
lines changed

commitizen/commands/init.py

Lines changed: 25 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -50,10 +50,10 @@ def __call__(self):
5050
],
5151
).ask()
5252
if hook_types:
53-
if not self._install_pre_commit_hook(hook_types):
54-
raise InitFailedError(
55-
"Installation failed. See error outputs for more information."
56-
)
53+
try:
54+
self._install_pre_commit_hook(hook_types)
55+
except InitFailedError as e:
56+
raise InitFailedError(f"Failed to install pre-commit hook.\n{e}")
5757

5858
out.write("You can bump the version and create changelog running:\n")
5959
out.info("cz bump --changelog")
@@ -120,24 +120,32 @@ def _ask_tag_format(self, latest_tag) -> str:
120120
tag_format = "$version"
121121
return tag_format
122122

123-
def _search_pre_commit(self):
123+
def _search_pre_commit(self) -> bool:
124+
"""Check whether pre-commit is installed"""
124125
return shutil.which("pre-commit") is not None
125126

126127
def _exec_install_pre_commit_hook(self, hook_types: List[str]):
128+
cmd_str = self._gen_pre_commit_cmd(hook_types)
129+
c = cmd.run(cmd_str)
130+
if c.return_code != 0:
131+
err_msg = (
132+
f"Error running {cmd_str}."
133+
"Outputs are attached below:\n"
134+
f"stdout: {c.out}\n"
135+
f"stderr: {c.err}"
136+
)
137+
raise InitFailedError(err_msg)
138+
139+
def _gen_pre_commit_cmd(self, hook_types: List[str]) -> str:
140+
"""Generate pre-commit command according to given hook types"""
127141
if not hook_types:
128142
raise ValueError("At least 1 hook type should be provided.")
129143
cmd_str = "pre-commit install " + "".join(
130144
f"--hook-type {ty}" for ty in hook_types
131145
)
132-
c = cmd.run(cmd_str)
133-
if c.return_code != 0:
134-
out.error(f"Error running {cmd_str}. Outputs are attached below:")
135-
out.error(f"stdout: {c.out}")
136-
out.error(f"stderr: {c.err}")
137-
return False
138-
return True
146+
return cmd_str
139147

140-
def _install_pre_commit_hook(self, hook_types: Optional[List[str]] = None) -> bool:
148+
def _install_pre_commit_hook(self, hook_types: Optional[List[str]] = None):
141149
pre_commit_config_filename = ".pre-commit-config.yaml"
142150
cz_hook_config = {
143151
"repo": "https://github.com/commitizen-tools/commitizen",
@@ -173,16 +181,13 @@ def _install_pre_commit_hook(self, hook_types: Optional[List[str]] = None) -> bo
173181
yaml.safe_dump(config_data, stream=config_file)
174182

175183
if not self._search_pre_commit():
176-
out.error("pre-commit is not installed in current environement.")
177-
return False
178-
184+
raise InitFailedError(
185+
"pre-commit is not installed in current environement."
186+
)
179187
if hook_types is None:
180188
hook_types = ["commit-msg", "pre-push"]
181-
if not self._exec_install_pre_commit_hook(hook_types):
182-
return False
183-
189+
self._exec_install_pre_commit_hook(hook_types)
184190
out.write("commitizen pre-commit hook is now installed in your '.git'\n")
185-
return True
186191

187192
def _update_config_file(self, values: Dict[str, Any]):
188193
for key, value in values.items():

tests/commands/test_init_command.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -106,9 +106,10 @@ def pre_commit_installed(mocker: MockFixture):
106106
"commitizen.commands.init.Init._search_pre_commit",
107107
return_value=True,
108108
)
109+
# And installation success (i.e. no exception raised)
109110
mocker.patch(
110111
"commitizen.commands.init.Init._exec_install_pre_commit_hook",
111-
return_value=True,
112+
return_value=None,
112113
)
113114

114115

@@ -223,7 +224,7 @@ def test_pre_commit_exec_failed(
223224
# But pre-commit installation will fail
224225
mocker.patch(
225226
"commitizen.commands.init.Init._exec_install_pre_commit_hook",
226-
return_value=False,
227+
side_effect=InitFailedError("Mock init failed error."),
227228
)
228229
with tmpdir.as_cwd():
229230
with pytest.raises(InitFailedError):

0 commit comments

Comments
 (0)