Skip to content

Commit 7e61bc1

Browse files
authored
Refactor commit-lint.csx to improve message validation
1 parent 1b9ee65 commit 7e61bc1

1 file changed

Lines changed: 29 additions & 4 deletions

File tree

.husky/csxScripts/commit-lint.csx

Lines changed: 29 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,41 @@
11
using System.Text.RegularExpressions;
22

3-
private var pattern = @"^(?=.{1,90}$)(?:build|feat|ci|chore|docs|fix|perf|refactor|revert|style|test)(?:\(.+\))*(?::).{4,}(?:#\d+)*(?<![\.\s])$";
4-
private var msg = File.ReadAllLines(Args[0])[0];
3+
var pattern = @"^(?=.{1,90}$)(?:build|feat|ci|chore|docs|fix|perf|refactor|revert|style|test)(?:\(.+\))*(?::).{4,}(?:#\d+)*(?<![\.\s])$";
4+
var lines = File.ReadAllLines(Args[0]);
5+
var header = lines.Length > 0 ? lines[0] : string.Empty;
56

6-
if (Regex.IsMatch(msg, pattern))
7+
if (Regex.IsMatch(header, pattern))
78
return 0;
89

10+
var reason = GetFailureReason(header);
11+
912
Console.ForegroundColor = ConsoleColor.Red;
1013
Console.WriteLine("Invalid commit message");
1114
Console.ResetColor();
15+
Console.WriteLine($"Reason: {reason}");
1216
Console.WriteLine("e.g: 'feat(scope): subject' or 'fix: subject'");
1317
Console.ForegroundColor = ConsoleColor.Gray;
1418
Console.WriteLine("more info: https://www.conventionalcommits.org/en/v1.0.0/");
1519

16-
return 1;
20+
return 1;
21+
22+
static string GetFailureReason(string header)
23+
{
24+
if (string.IsNullOrWhiteSpace(header))
25+
return "The first line of the commit message is empty.";
26+
27+
if (header.Length > 90)
28+
return $"The first line is {header.Length} characters; max allowed is 90.";
29+
30+
if (Regex.IsMatch(header, @"[\.\s]$"))
31+
return "The subject must not end with a period or trailing whitespace.";
32+
33+
if (!Regex.IsMatch(header, @"^(?:build|feat|ci|chore|docs|fix|perf|refactor|revert|style|test)(?:\(.+\))*:"))
34+
return "Header must start with a valid type, optional scope, and colon (for example: feat(scope):).";
35+
36+
var colonIndex = header.IndexOf(':');
37+
if (colonIndex < 0 || header.Length - colonIndex - 1 < 4)
38+
return "Header must include at least 4 characters of subject text after the colon.";
39+
40+
return "Header does not match the conventional commit format expected by this repository.";
41+
}

0 commit comments

Comments
 (0)