diff --git a/commitizen/commands/check.py b/commitizen/commands/check.py index 33fd08a7d0..3c06c97647 100644 --- a/commitizen/commands/check.py +++ b/commitizen/commands/check.py @@ -81,15 +81,23 @@ def _get_commits(self): # Get commit message from file (--commit-msg-file) if self.commit_msg_file: with open(self.commit_msg_file, "r", encoding="utf-8") as commit_file: - commit_title = commit_file.readline() - commit_body = commit_file.read() + msg = commit_file.read() + msg = self._filter_comments(msg) + msg = msg.lstrip("\n") + commit_title = msg.split("\n")[0] + commit_body = "\n".join(msg.split("\n")[1:]) return [git.GitCommit(rev="", title=commit_title, body=commit_body)] elif self.commit_msg: + self.commit_msg = self._filter_comments(self.commit_msg) return [git.GitCommit(rev="", title="", body=self.commit_msg)] # 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("#")] + return "\n".join(lines) + @staticmethod def validate_commit_message(commit_msg: str, pattern: str) -> bool: if commit_msg.startswith("Merge") or commit_msg.startswith("Revert"): diff --git a/docs/check.md b/docs/check.md index 9150f608de..e1f0344e16 100644 --- a/docs/check.md +++ b/docs/check.md @@ -1,8 +1,9 @@ # Check ## About -This feature checks whether the commit message follows the given committing rules. -If you want to setup an automatic check before every git commit, please refer to +This feature checks whether the commit message follows the given committing rules. And comment in git message will be ignored. + +If you want to setup an automatic check before every git commit, please refer to [Automatically check message before commit](auto_check.md). ## Usage diff --git a/tests/commands/test_check_command.py b/tests/commands/test_check_command.py index 7377a8a388..26db697b50 100644 --- a/tests/commands/test_check_command.py +++ b/tests/commands/test_check_command.py @@ -275,3 +275,23 @@ def test_check_command_with_pipe_message_and_failed(mocker): with pytest.raises(InvalidCommitMessageError) as excinfo: cli.main() assert "commit validation: failed!" in str(excinfo.value) + + +def test_check_command_with_comment_in_messege_file(mocker, capsys): + 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="# : (If applied, this commit will...) \n" + "# |<---- Try to Limit to a Max of 50 char ---->|\n" + "ci: add commitizen pre-commit hook\n" + "\n" + "# Explain why this change is being made\n" + "# |<---- Try To Limit Each Line to a Max Of 72 Char ---->|\n" + "This pre-commit hook will check our commits automatically." + ), + ) + cli.main() + out, _ = capsys.readouterr() + assert "Commit validation: successful!" in out