Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 34 additions & 48 deletions commitizen/commands/init.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,9 +150,43 @@ def __call__(self) -> None:
tag_format = self._ask_tag_format(tag) # confirm & text
update_changelog_on_bump = self._ask_update_changelog_on_bump() # confirm
major_version_zero = self._ask_major_version_zero(version) # confirm
hook_types: list[str] | None = questionary.checkbox(
"What types of pre-commit hook you want to install? (Leave blank if you don't want to install)",
choices=[
questionary.Choice("commit-msg", checked=False),
questionary.Choice("pre-push", checked=False),
],
).unsafe_ask()
except KeyboardInterrupt:
raise InitFailedError("Stopped by user")

if hook_types:
config_data = self._get_config_data()
with smart_open(
self._PRE_COMMIT_CONFIG_PATH, "w", encoding=self.encoding
) as config_file:
yaml.safe_dump(config_data, stream=config_file)

if not self.project_info.is_pre_commit_installed:
raise InitFailedError(
"Failed to install pre-commit hook.\n"
"pre-commit is not installed in current environment."
)

cmd_str = "pre-commit install " + " ".join(
f"--hook-type {ty}" for ty in hook_types
)
c = cmd.run(cmd_str)
if c.return_code != 0:
raise InitFailedError(
"Failed to install pre-commit hook.\n"
f"Error running {cmd_str}."
"Outputs are attached below:\n"
f"stdout: {c.out}\n"
f"stderr: {c.err}"
)
out.write("commitizen pre-commit hook is now installed in your '.git'\n")

# Initialize configuration
if "toml" in config_path:
self.config = TomlConfig(data="", path=config_path)
Expand All @@ -161,20 +195,6 @@ def __call__(self) -> None:
elif "yaml" in config_path:
self.config = YAMLConfig(data="", path=config_path)

# Collect hook data
hook_types = questionary.checkbox(
"What types of pre-commit hook you want to install? (Leave blank if you don't want to install)",
choices=[
questionary.Choice("commit-msg", checked=False),
questionary.Choice("pre-push", checked=False),
],
).unsafe_ask()
if hook_types:
try:
self._install_pre_commit_hook(hook_types)
except InitFailedError as e:
raise InitFailedError(f"Failed to install pre-commit hook.\n{e}")

# Create and initialize config
self.config.init_empty_config_content()

Expand Down Expand Up @@ -321,26 +341,6 @@ def _ask_update_changelog_on_bump(self) -> bool:
).unsafe_ask()
return update_changelog_on_bump

def _exec_install_pre_commit_hook(self, hook_types: list[str]) -> None:
cmd_str = self._gen_pre_commit_cmd(hook_types)
c = cmd.run(cmd_str)
if c.return_code != 0:
err_msg = (
f"Error running {cmd_str}."
"Outputs are attached below:\n"
f"stdout: {c.out}\n"
f"stderr: {c.err}"
)
raise InitFailedError(err_msg)

def _gen_pre_commit_cmd(self, hook_types: list[str]) -> str:
"""Generate pre-commit command according to given hook types"""
if not hook_types:
raise ValueError("At least 1 hook type should be provided.")
return "pre-commit install " + " ".join(
f"--hook-type {ty}" for ty in hook_types
)

def _get_config_data(self) -> dict[str, Any]:
CZ_HOOK_CONFIG = {
"repo": "https://github.com/commitizen-tools/commitizen",
Expand Down Expand Up @@ -369,17 +369,3 @@ def _get_config_data(self) -> dict[str, Any]:
else:
repos.append(CZ_HOOK_CONFIG)
return config_data

def _install_pre_commit_hook(self, hook_types: list[str] | None = None) -> None:
config_data = self._get_config_data()
with smart_open(
self._PRE_COMMIT_CONFIG_PATH, "w", encoding=self.encoding
) as config_file:
yaml.safe_dump(config_data, stream=config_file)

if not self.project_info.is_pre_commit_installed:
raise InitFailedError("pre-commit is not installed in current environment.")
if hook_types is None:
hook_types = ["commit-msg", "pre-push"]
self._exec_install_pre_commit_hook(hook_types)
out.write("commitizen pre-commit hook is now installed in your '.git'\n")
18 changes: 9 additions & 9 deletions commitizen/cz/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from typing import Any, Callable, Protocol

from jinja2 import BaseLoader, PackageLoader
from prompt_toolkit.styles import Style, merge_styles
from prompt_toolkit.styles import Style

from commitizen import git
from commitizen.config.base_config import BaseConfig
Expand Down Expand Up @@ -77,25 +77,25 @@ def message(self, answers: Mapping[str, Any]) -> str:

@property
def style(self) -> Style:
return merge_styles(
return Style(
[
Style(BaseCommitizen.default_style_config),
Style(self.config.settings["style"]),
*BaseCommitizen.default_style_config,
*self.config.settings["style"],
]
) # type: ignore[return-value]
)

@abstractmethod
def example(self) -> str:
"""Example of the commit message."""
raise NotImplementedError("Not Implemented yet")

@abstractmethod
def schema(self) -> str:
"""Schema definition of the commit message."""
raise NotImplementedError("Not Implemented yet")

@abstractmethod
def schema_pattern(self) -> str:
"""Regex matching the schema used for message validation."""
raise NotImplementedError("Not Implemented yet")

@abstractmethod
def info(self) -> str:
"""Information about the standardized commit message."""
raise NotImplementedError("Not Implemented yet")
1 change: 1 addition & 0 deletions commitizen/defaults.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ class Settings(TypedDict, total=False):
"Pull request",
"fixup!",
"squash!",
"amend!",
],
"changelog_file": "CHANGELOG.md",
"changelog_format": None, # default guessed from changelog_file
Expand Down
2 changes: 1 addition & 1 deletion commitizen/providers/uv_provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

class UvProvider(TomlProvider):
"""
uv.lock and pyproject.tom version management
uv.lock and pyproject.toml version management
"""

filename = "pyproject.toml"
Expand Down
8 changes: 8 additions & 0 deletions tests/commands/test_check_command.py
Original file line number Diff line number Diff line change
Expand Up @@ -452,3 +452,11 @@ def test_check_command_with_message_length_limit_exceeded(config, mocker: MockFi
with pytest.raises(InvalidCommitMessageError):
check_cmd()
error_mock.assert_called_once()


def test_check_command_with_amend_prefix_default(config, mocker: MockFixture):
success_mock = mocker.patch("commitizen.out.success")
check_cmd = commands.Check(config=config, arguments={"message": "amend! test"})

check_cmd()
success_mock.assert_called_once()
29 changes: 3 additions & 26 deletions tests/commands/test_init_command.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import yaml
from pytest_mock import MockFixture

from commitizen import cli, commands
from commitizen import cli, cmd, commands
from commitizen.__version__ import __version__
from commitizen.config.base_config import BaseConfig
from commitizen.exceptions import InitFailedError, NoAnswersError
Expand Down Expand Up @@ -117,12 +117,6 @@ def test_init_without_choosing_tag(config: BaseConfig, mocker: MockFixture, tmpd
commands.Init(config)()


def test_executed_pre_commit_command(config: BaseConfig):
init = commands.Init(config)
expected_cmd = "pre-commit install --hook-type commit-msg --hook-type pre-push"
assert init._gen_pre_commit_cmd(["commit-msg", "pre-push"]) == expected_cmd


@pytest.fixture(scope="function")
def pre_commit_installed(mocker: MockFixture):
# Assume the `pre-commit` is installed
Expand All @@ -132,8 +126,8 @@ def pre_commit_installed(mocker: MockFixture):
)
# And installation success (i.e. no exception raised)
mocker.patch(
"commitizen.commands.init.Init._exec_install_pre_commit_hook",
return_value=None,
"commitizen.cmd.run",
return_value=cmd.Command("0.0.1", "", b"", b"", 0),
)


Expand Down Expand Up @@ -244,23 +238,6 @@ def test_pre_commit_not_installed(
with pytest.raises(InitFailedError):
commands.Init(config)()

def test_pre_commit_exec_failed(
_, mocker: MockFixture, config: BaseConfig, default_choice: str, tmpdir
):
# Assume `pre-commit` is installed
mocker.patch(
"commitizen.commands.init.ProjectInfo.is_pre_commit_installed",
return_value=True,
)
# But pre-commit installation will fail
mocker.patch(
"commitizen.commands.init.Init._exec_install_pre_commit_hook",
side_effect=InitFailedError("Mock init failed error."),
)
with tmpdir.as_cwd():
with pytest.raises(InitFailedError):
commands.Init(config)()


class TestAskTagFormat:
def test_confirm_v_tag_format(self, mocker: MockFixture, config: BaseConfig):
Expand Down
24 changes: 24 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,18 @@ def message(self, answers: Mapping) -> str:
subject = answers.get("subject", "default message").trim()
return f"{prefix}: {subject}"

def example(self) -> str:
return ""

def schema(self) -> str:
return ""

def schema_pattern(self) -> str:
return ""

def info(self) -> str:
return ""


@pytest.fixture()
def use_cz_semver(mocker):
Expand All @@ -229,6 +241,18 @@ def questions(self) -> list[CzQuestion]:
def message(self, answers: Mapping) -> str:
return ""

def example(self) -> str:
return ""

def schema(self) -> str:
return ""

def schema_pattern(self) -> str:
return ""

def info(self) -> str:
return ""


@pytest.fixture
def mock_plugin(mocker: MockerFixture, config: BaseConfig) -> BaseCommitizen:
Expand Down
18 changes: 16 additions & 2 deletions tests/test_conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,14 @@
"bump_message": None,
"retry_after_failure": False,
"allow_abort": False,
"allowed_prefixes": ["Merge", "Revert", "Pull request", "fixup!", "squash!"],
"allowed_prefixes": [
"Merge",
"Revert",
"Pull request",
"fixup!",
"squash!",
"amend!",
],
"version_files": ["commitizen/__version__.py", "pyproject.toml"],
"style": [["pointer", "reverse"], ["question", "underline"]],
"changelog_file": "CHANGELOG.md",
Expand Down Expand Up @@ -108,7 +115,14 @@
"bump_message": None,
"retry_after_failure": False,
"allow_abort": False,
"allowed_prefixes": ["Merge", "Revert", "Pull request", "fixup!", "squash!"],
"allowed_prefixes": [
"Merge",
"Revert",
"Pull request",
"fixup!",
"squash!",
"amend!",
],
"version_files": ["commitizen/__version__.py", "pyproject.toml"],
"style": [["pointer", "reverse"], ["question", "underline"]],
"changelog_file": "CHANGELOG.md",
Expand Down
46 changes: 0 additions & 46 deletions tests/test_cz_base.py

This file was deleted.

15 changes: 4 additions & 11 deletions tests/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@

import sys
import time
import uuid
from pathlib import Path

import pytest
from deprecated import deprecated
Expand All @@ -28,17 +26,12 @@ def __init__(self, out=None, err=None, return_code=0):
self.return_code = return_code


def create_file_and_commit(
message: str, filename: str | None = None, committer_date: str | None = None
):
if not filename:
filename = str(uuid.uuid4())

Path(filename).touch()
c = cmd.run("git add .")
# TODO: rename this function when the tests are stable (nobody is changing it)
def create_file_and_commit(message: str, committer_date: str | None = None):
c = cmd.run("git add .") # prevent untracked files errors
if c.return_code != 0:
raise exceptions.CommitError(c.err)
c = git.commit(message, committer_date=committer_date)
c = git.commit(message, "--allow-empty", committer_date)
if c.return_code != 0:
raise exceptions.CommitError(c.err)

Expand Down
Loading