Skip to content

Lotram/customizable allowed prefixes #678

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
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
11 changes: 9 additions & 2 deletions commitizen/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
import argparse
import logging
import sys
from pathlib import Path
from functools import partial
from pathlib import Path
from types import TracebackType

import argcomplete
Expand Down Expand Up @@ -307,6 +307,13 @@
"default": False,
"help": "allow empty commit messages, which typically abort a commit",
},
{
"name": ["--allowed-prefixes"],
"nargs": "*",
"help": "allowed commit message prefixes. "
"If the message starts by one of these prefixes, "
"the message won't be checked against the regex",
},
],
},
{
Expand Down Expand Up @@ -354,7 +361,7 @@


def commitizen_excepthook(
type, value, traceback, debug=False, no_raise: list[int] = None
type, value, traceback, debug=False, no_raise: list[int] | None = None
):
traceback = traceback if isinstance(traceback, TracebackType) else None
if not no_raise:
Expand Down
20 changes: 12 additions & 8 deletions commitizen/commands/check.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import os
import re
import sys
from typing import Any
from typing import Any, List

from commitizen import factory, git, out
from commitizen.config import BaseConfig
Expand Down Expand Up @@ -32,6 +32,15 @@ def __init__(self, config: BaseConfig, arguments: dict[str, Any], cwd=os.getcwd(
arguments.get("allow_abort", config.settings["allow_abort"])
)

# we need to distinguish between None and [], which is a valid value

allowed_prefixes = arguments.get("allowed_prefixes")
self.allowed_prefixes: List[str] = (
allowed_prefixes
if allowed_prefixes is not None
else config.settings["allowed_prefixes"]
)

self._valid_command_argument()

self.config: BaseConfig = config
Expand Down Expand Up @@ -134,12 +143,7 @@ def _filter_comments(msg: str) -> str:
def validate_commit_message(self, commit_msg: str, pattern: str) -> bool:
if not commit_msg:
return self.allow_abort
if (
commit_msg.startswith("Merge")
or commit_msg.startswith("Revert")
or commit_msg.startswith("Pull request")
or commit_msg.startswith("fixup!")
or commit_msg.startswith("squash!")
):

if any(map(commit_msg.startswith, self.allowed_prefixes)):
return True
return bool(re.match(pattern, commit_msg))
8 changes: 8 additions & 0 deletions commitizen/defaults.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ class Settings(TypedDict, total=False):
tag_format: str | None
bump_message: str | None
allow_abort: bool
allowed_prefixes: list[str]
changelog_file: str
changelog_incremental: bool
changelog_start_rev: str | None
Expand Down Expand Up @@ -73,6 +74,13 @@ class Settings(TypedDict, total=False):
"tag_format": None, # example v$version
"bump_message": None, # bumped v$current_version to $new_version
"allow_abort": False,
"allowed_prefixes": [
"Merge",
"Revert",
"Pull request",
"fixup!",
"squash!",
],
"changelog_file": "CHANGELOG.md",
"changelog_incremental": False,
"changelog_start_rev": None,
Expand Down
9 changes: 9 additions & 0 deletions docs/check.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,3 +64,12 @@ cz check --message MESSAGE --allow-abort

Empty commit messages typically instruct Git to abort a commit, so you can pass `--allow-abort` to
permit them. Since `git commit` accepts an `--allow-empty-message` flag (primarily for wrapper scripts), you may wish to disallow such commits in CI. `--allow-abort` may be used in conjunction with any of the other options.

### Allowed Prefixes

If the commit message starts by some specific prefixes, `cz check` returns `True` without checkign the regex.
By default, the the following prefixes are allowed: `Merge`, `Revert`, `Pull Request`, `fixup!` and `squash!`.

```bash
cz check --message MESSAGE --allowed-prefixes 'Merge' 'Revert' 'Custom Prefix'
```
7 changes: 7 additions & 0 deletions docs/config.md
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,12 @@ Default: `false`

Disallow empty commit messages, useful in ci. [Read more][allow_abort]

### `allowed_prefixes`

Type: `list`
Default: `[ "Merge", "Revert", "Pull request", "fixup!", "squash!"]`
Allow some prefixes and do not try to match the regex when checking the message [Read more][allowed_prefixes]

### `changelog_file`

Type: `str`
Expand Down Expand Up @@ -346,6 +352,7 @@ setup(
[version_type]: bump.md#version_type
[pre_bump_hooks]: bump.md#pre_bump_hooks
[post_bump_hooks]: bump.md#post_bump_hooks
[allowed_prefixes]: check.md#allowed-prefixes
[additional-features]: https://github.com/tmbo/questionary#additional-features
[customization]: customization.md
[shortcuts]: customization.md#shortcut-keys
Expand Down
33 changes: 33 additions & 0 deletions tests/commands/test_check_command.py
Original file line number Diff line number Diff line change
Expand Up @@ -312,6 +312,39 @@ def test_check_command_override_allow_abort_config(config, mocker: MockFixture):
error_mock.assert_called_once()


def test_check_command_with_allowed_prefixes_arg(config, mocker: MockFixture):
success_mock = mocker.patch("commitizen.out.success")
check_cmd = commands.Check(
config=config,
arguments={"message": "custom! test", "allowed_prefixes": ["custom!"]},
)

check_cmd()
success_mock.assert_called_once()


def test_check_command_with_allowed_prefixes_config(config, mocker: MockFixture):
success_mock = mocker.patch("commitizen.out.success")
config.settings["allowed_prefixes"] = ["custom!"]
check_cmd = commands.Check(config=config, arguments={"message": "custom! test"})

check_cmd()
success_mock.assert_called_once()


def test_check_command_override_allowed_prefixes_config(config, mocker: MockFixture):
error_mock = mocker.patch("commitizen.out.error")
config.settings["allow_abort"] = ["fixup!"]
check_cmd = commands.Check(
config=config,
arguments={"message": "fixup! test", "allowed_prefixes": ["custom!"]},
)

with pytest.raises(InvalidCommitMessageError):
check_cmd()
error_mock.assert_called_once()


def test_check_command_with_pipe_message(mocker: MockFixture, capsys):
testargs = ["cz", "check"]
mocker.patch.object(sys, "argv", testargs)
Expand Down
2 changes: 2 additions & 0 deletions tests/test_conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
"tag_format": None,
"bump_message": None,
"allow_abort": False,
"allowed_prefixes": ["Merge", "Revert", "Pull request", "fixup!", "squash!"],
"version_files": ["commitizen/__version__.py", "pyproject.toml"],
"style": [["pointer", "reverse"], ["question", "underline"]],
"changelog_file": "CHANGELOG.md",
Expand All @@ -70,6 +71,7 @@
"tag_format": None,
"bump_message": None,
"allow_abort": False,
"allowed_prefixes": ["Merge", "Revert", "Pull request", "fixup!", "squash!"],
"version_files": ["commitizen/__version__.py", "pyproject.toml"],
"style": [["pointer", "reverse"], ["question", "underline"]],
"changelog_file": "CHANGELOG.md",
Expand Down