diff --git a/commitizen/commands/check.py b/commitizen/commands/check.py index 2ce8ed4d6..3085af98d 100644 --- a/commitizen/commands/check.py +++ b/commitizen/commands/check.py @@ -98,8 +98,35 @@ def _get_commits(self): # Get commit messages from git log (--rev-range) return git.get_commits(end=self.rev_range) - def _filter_comments(self, msg: str) -> str: - lines = [line for line in msg.split("\n") if not line.startswith("#")] + @staticmethod + def _filter_comments(msg: str) -> str: + """Filter the commit message by removing comments. + + When using `git commit --verbose`, we exclude the diff that is going to + generated, like the following example: + + ```bash + ... + # ------------------------ >8 ------------------------ + # Do not modify or remove the line above. + # Everything below it will be ignored. + diff --git a/... b/... + ... + ``` + + Args: + msg: The commit message to filter. + + Returns: + The filtered commit message without comments. + """ + + lines = [] + for line in msg.split("\n"): + if "# ------------------------ >8 ------------------------" in line: + break + if not line.startswith("#"): + lines.append(line) return "\n".join(lines) def validate_commit_message(self, commit_msg: str, pattern: str) -> bool: diff --git a/tests/commands/test_check_command.py b/tests/commands/test_check_command.py index 71e7aed6d..a097b5cfb 100644 --- a/tests/commands/test_check_command.py +++ b/tests/commands/test_check_command.py @@ -349,3 +349,34 @@ def test_check_command_with_comment_in_messege_file(mocker, capsys): cli.main() out, _ = capsys.readouterr() assert "Commit validation: successful!" in out + + +def test_check_conventional_commit_succeed_with_git_diff(mocker, capsys): + commit_msg = ( + "feat: This is a test commit\n" + "# Please enter the commit message for your changes. Lines starting\n" + "# with '#' will be ignored, and an empty message aborts the commit.\n" + "#\n" + "# On branch ...\n" + "# Changes to be committed:\n" + "# modified: ...\n" + "#\n" + "# ------------------------ >8 ------------------------\n" + "# Do not modify or remove the line above.\n" + "# Everything below it will be ignored.\n" + "diff --git a/... b/...\n" + "index f1234c..1c5678 1234\n" + "--- a/...\n" + "+++ b/...\n" + "@@ -92,3 +92,4 @@ class Command(BaseCommand):\n" + '+ "this is a test"\n' + ) + testargs = ["cz", "check", "--commit-msg-file", "some_file"] + mocker.patch.object(sys, "argv", testargs) + mocker.patch( + "commitizen.commands.check.open", + mocker.mock_open(read_data=commit_msg), + ) + cli.main() + out, _ = capsys.readouterr() + assert "Commit validation: successful!" in out