Skip to content

Commit 432431e

Browse files
kevin1kevin1kLee-W
authored andcommitted
refactor: check the length in Commit instead of Commitizen
1 parent 8884a1f commit 432431e

File tree

11 files changed

+59
-57
lines changed

11 files changed

+59
-57
lines changed

commitizen/commands/commit.py

+9-1
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
from commitizen.cz.utils import get_backup_file_path
1313
from commitizen.exceptions import (
1414
CommitError,
15+
CommitMessageLengthExceededError,
1516
CustomError,
1617
DryRunExit,
1718
NoAnswersError,
@@ -62,8 +63,15 @@ def prompt_commit_questions(self) -> str:
6263
if not answers:
6364
raise NoAnswersError()
6465

66+
message = cz.message(answers)
67+
message_len = len(message.partition("\n")[0])
6568
message_length_limit: int = self.arguments.get("message_length_limit", 0)
66-
return cz.message(answers, message_length_limit=message_length_limit)
69+
if message_length_limit > 0 and message_len > message_length_limit:
70+
raise CommitMessageLengthExceededError(
71+
f"Length of commit message exceeds limit ({message_len}/{message_length_limit})"
72+
)
73+
74+
return message
6775

6876
def __call__(self):
6977
dry_run: bool = self.arguments.get("dry_run")

commitizen/cz/base.py

+1-11
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@
99
from commitizen import git
1010
from commitizen.config.base_config import BaseConfig
1111
from commitizen.defaults import Questions
12-
from commitizen.exceptions import CommitMessageLengthExceededError
1312

1413

1514
class MessageBuilderHook(Protocol):
@@ -72,7 +71,7 @@ def questions(self) -> Questions:
7271
"""Questions regarding the commit message."""
7372

7473
@abstractmethod
75-
def message(self, answers: dict, message_length_limit: int) -> str:
74+
def message(self, answers: dict) -> str:
7675
"""Format your git message."""
7776

7877
@property
@@ -106,12 +105,3 @@ def process_commit(self, commit: str) -> str:
106105
If not overwritten, it returns the first line of commit.
107106
"""
108107
return commit.split("\n")[0]
109-
110-
def _check_message_length_limit(
111-
self, message: str, message_length_limit: int
112-
) -> None:
113-
message_len = len(message)
114-
if message_length_limit > 0 and message_len > message_length_limit:
115-
raise CommitMessageLengthExceededError(
116-
f"Length of commit message exceeds limit ({message_len}/{message_length_limit})"
117-
)

commitizen/cz/conventional_commits/conventional_commits.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -150,7 +150,7 @@ def questions(self) -> Questions:
150150
]
151151
return questions
152152

153-
def message(self, answers: dict, message_length_limit: int = 0) -> str:
153+
def message(self, answers: dict) -> str:
154154
prefix = answers["prefix"]
155155
scope = answers["scope"]
156156
subject = answers["subject"]
@@ -167,9 +167,9 @@ def message(self, answers: dict, message_length_limit: int = 0) -> str:
167167
if footer:
168168
footer = f"\n\n{footer}"
169169

170-
message = f"{prefix}{scope}: {subject}"
171-
self._check_message_length_limit(message, message_length_limit)
172-
return f"{message}{body}{footer}"
170+
message = f"{prefix}{scope}: {subject}{body}{footer}"
171+
172+
return message
173173

174174
def example(self) -> str:
175175
return (

commitizen/cz/customize/customize.py

+5-8
Original file line numberDiff line numberDiff line change
@@ -61,15 +61,12 @@ def __init__(self, config: BaseConfig):
6161
def questions(self) -> Questions:
6262
return self.custom_settings.get("questions", [{}])
6363

64-
def message(self, answers: dict, message_length_limit: int = 0) -> str:
64+
def message(self, answers: dict) -> str:
6565
message_template = Template(self.custom_settings.get("message_template", ""))
66-
message: str = (
67-
message_template.substitute(**answers) # type: ignore
68-
if getattr(Template, "substitute", None)
69-
else message_template.render(**answers)
70-
)
71-
self._check_message_length_limit(message, message_length_limit)
72-
return message
66+
if getattr(Template, "substitute", None):
67+
return message_template.substitute(**answers) # type: ignore
68+
else:
69+
return message_template.render(**answers)
7370

7471
def example(self) -> str | None:
7572
return self.custom_settings.get("example")

commitizen/cz/jira/jira.py

+2-4
Original file line numberDiff line numberDiff line change
@@ -44,8 +44,8 @@ def questions(self) -> Questions:
4444
]
4545
return questions
4646

47-
def message(self, answers: dict, message_length_limit: int = 0) -> str:
48-
message = " ".join(
47+
def message(self, answers: dict) -> str:
48+
return " ".join(
4949
filter(
5050
bool,
5151
[
@@ -57,8 +57,6 @@ def message(self, answers: dict, message_length_limit: int = 0) -> str:
5757
],
5858
)
5959
)
60-
self._check_message_length_limit(message, message_length_limit)
61-
return message
6260

6361
def example(self) -> str:
6462
return (

commitizen/exceptions.py

+1
Original file line numberDiff line numberDiff line change
@@ -206,3 +206,4 @@ class ConfigFileIsEmpty(CommitizenException):
206206

207207
class CommitMessageLengthExceededError(CommitizenException):
208208
exit_code = ExitCode.COMMIT_MESSAGE_LENGTH_LIMIT_EXCEEDED
209+
message = "Length of commit message exceeds the given limit."

docs/commit.md

+3-2
Original file line numberDiff line numberDiff line change
@@ -44,5 +44,6 @@ An exception would be raised when the message length exceeds the limit.
4444
For example, `cz commit -l 72` will limit the length of commit messages to 72 characters.
4545
By default the limit is set to 0, which means no limit on the length.
4646

47-
Note that for `ConventionalCommitsCz`, the limit applies only from the prefix to the subject.
48-
In other words, everything after the first line (the body and the footer) are not counted in the length.
47+
Note that the limit applies only to the first line of message.
48+
Specifically, for `ConventionalCommitsCz` the length only counts from the type of change to the subject,
49+
while the body and the footer are not counted.

docs/customization.md

+2-4
Original file line numberDiff line numberDiff line change
@@ -227,11 +227,9 @@ class JiraCz(BaseCommitizen):
227227
]
228228
return questions
229229
230-
def message(self, answers: dict, message_length_limit: int = 0) -> str:
230+
def message(self, answers: dict) -> str:
231231
"""Generate the message with the given answers."""
232-
message = "{0} (#{1})".format(answers["title"], answers["issue"])
233-
self._check_message_length_limit(message, message_length_limit)
234-
return message
232+
return "{0} (#{1})".format(answers["title"], answers["issue"])
235233
236234
def example(self) -> str:
237235
"""Provide an example to help understand the style (OPTIONAL)

tests/commands/test_commit_command.py

+27
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
from commitizen.cz.utils import get_backup_file_path
1010
from commitizen.exceptions import (
1111
CommitError,
12+
CommitMessageLengthExceededError,
1213
CustomError,
1314
DryRunExit,
1415
NoAnswersError,
@@ -379,3 +380,29 @@ def test_commit_command_with_extra_args(config, mocker: MockFixture):
379380
commands.Commit(config, {"extra_cli_args": "-- -extra-args1 -extra-arg2"})()
380381
commit_mock.assert_called_once_with(ANY, args="-- -extra-args1 -extra-arg2")
381382
success_mock.assert_called_once()
383+
384+
385+
@pytest.mark.usefixtures("staging_is_clean")
386+
def test_commit_command_with_message_length_limit(config, mocker: MockFixture):
387+
prompt_mock = mocker.patch("questionary.prompt")
388+
prefix = "feat"
389+
subject = "random subject"
390+
message_length = len(prefix) + len(": ") + len(subject)
391+
prompt_mock.return_value = {
392+
"prefix": prefix,
393+
"subject": subject,
394+
"scope": "",
395+
"is_breaking_change": False,
396+
"body": "random body",
397+
"footer": "random footer",
398+
}
399+
400+
commit_mock = mocker.patch("commitizen.git.commit")
401+
commit_mock.return_value = cmd.Command("success", "", b"", b"", 0)
402+
success_mock = mocker.patch("commitizen.out.success")
403+
404+
commands.Commit(config, {"message_length_limit": message_length})()
405+
success_mock.assert_called_once()
406+
407+
with pytest.raises(CommitMessageLengthExceededError):
408+
commands.Commit(config, {"message_length_limit": message_length - 1})()

tests/conftest.py

+3-5
Original file line numberDiff line numberDiff line change
@@ -204,12 +204,10 @@ def questions(self) -> list:
204204
},
205205
]
206206

207-
def message(self, answers: dict, message_length_limit: int = 0) -> str:
207+
def message(self, answers: dict) -> str:
208208
prefix = answers["prefix"]
209209
subject = answers.get("subject", "default message").trim()
210-
message = f"{prefix}: {subject}"
211-
self._check_message_length_limit(message, message_length_limit)
212-
return message
210+
return f"{prefix}: {subject}"
213211

214212

215213
@pytest.fixture()
@@ -222,7 +220,7 @@ class MockPlugin(BaseCommitizen):
222220
def questions(self) -> defaults.Questions:
223221
return []
224222

225-
def message(self, answers: dict, message_length_limit: int = 0) -> str:
223+
def message(self, answers: dict) -> str:
226224
return ""
227225

228226

tests/test_cz_base.py

+2-18
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,14 @@
11
import pytest
22

33
from commitizen.cz.base import BaseCommitizen
4-
from commitizen.exceptions import CommitMessageLengthExceededError
54

65

76
class DummyCz(BaseCommitizen):
87
def questions(self):
98
return [{"type": "input", "name": "commit", "message": "Initial commit:\n"}]
109

11-
def message(self, answers: dict, message_length_limit: int = 0):
12-
message = answers["commit"]
13-
self._check_message_length_limit(message, message_length_limit)
14-
return message
10+
def message(self, answers: dict):
11+
return answers["commit"]
1512

1613

1714
def test_base_raises_error(config):
@@ -51,16 +48,3 @@ def test_process_commit(config):
5148
cz = DummyCz(config)
5249
message = cz.process_commit("test(test_scope): this is test msg")
5350
assert message == "test(test_scope): this is test msg"
54-
55-
56-
def test_message_length_limit(config):
57-
cz = DummyCz(config)
58-
commit_message = "123456789"
59-
message_length = len(commit_message)
60-
assert cz.message({"commit": commit_message}) == commit_message
61-
assert (
62-
cz.message({"commit": commit_message}, message_length_limit=message_length)
63-
== commit_message
64-
)
65-
with pytest.raises(CommitMessageLengthExceededError):
66-
cz.message({"commit": commit_message}, message_length_limit=message_length - 1)

0 commit comments

Comments
 (0)