feat: use regex pattern to valid message

This commit is contained in:
Changliang Wu 2023-04-13 11:59:57 +08:00
parent 679da979e4
commit d56babc5d1
No known key found for this signature in database
GPG key ID: 45D7CA7699EDE780
2 changed files with 9 additions and 35 deletions

View file

@ -7,10 +7,14 @@ test("should be able to correctly validate the commit message", () => {
expect(isValidCommitMessage("fix: menu must open on shortcut press")).toBe(true);
expect(isValidCommitMessage("something: should not work")).toBe(false);
expect(isValidCommitMessage("fixes something")).toBe(false);
expect(isValidCommitMessage("🚧 fix: menu must open on shortcut press")).toBe(true);
expect(isValidCommitMessage("🚧 fix: menu must open on shortcut press")).toBe(false);
expect(isValidCommitMessage("fix(menus): menu must open on shortcut press")).toBe(true);
expect(isValidCommitMessage("🚧 fix(menus): menu must open on shortcut press")).toBe(true);
expect(isValidCommitMessage("🚧 fix(menus): menu must open on shortcut press")).toBe(false);
expect(isValidCommitMessage("🚧 fixing something")).toBe(false);
expect(isValidCommitMessage("🚧 something: should not work")).toBe(false);
expect(isValidCommitMessage("chorz: 123")).toBe(false);
expect(isValidCommitMessage("(chorz:) 123")).toBe(false);
expect(isValidCommitMessage("fix: test 🐛 with icon")).toBe(true);
expect(isValidCommitMessage("fix: test 🐛 with icon")).toBe(false);
expect(isValidCommitMessage("fix: 🐛 test with icon")).toBe(true);
});

View file

@ -1,42 +1,12 @@
const DEFAULT_COMMIT_TYPES = [
"feat",
"fix",
"docs",
"style",
"refactor",
"test",
"build",
"perf",
"ci",
"chore",
"revert",
"merge",
"wip",
];
const isValidCommitMessage = (message, availableTypes = DEFAULT_COMMIT_TYPES): boolean => {
const isValidCommitMessage = (message): boolean => {
// Exceptions.
// This is a message that's auto-generated by git. Can't do much about it unfortunately. Let's allow it.
if (message.startsWith("Merge ") || message.startsWith("Revert ")) {
return true;
}
// Commit message doesn't fall into the exceptions group. Let's do the validation.
let [possiblyValidCommitType] = message.split(":");
possiblyValidCommitType = possiblyValidCommitType.toLowerCase();
// Let's remove scope if present.
if (possiblyValidCommitType.match(/\(\S*?\)/)) {
possiblyValidCommitType = possiblyValidCommitType.replace(/\(\S*?\)/, "");
}
possiblyValidCommitType = possiblyValidCommitType
.replace(/\s/g, "") // Remove all whitespace
.replace(/\!/g, "") // Remove bang for notify breaking change
.replace(/()/g, "") // Remove all whitespace
.replace(/[^a-z]/g, ""); // Only leave [a-z] characters.
return availableTypes.includes(possiblyValidCommitType);
let pattern = /^(build|chore|ci|docs|feat|fix|perf|refactor|revert|style|test){1}(\([\w\-\.]+\))?(!)?: \S+([\s\S]*)/
return pattern.test(message)
};
export default isValidCommitMessage;