From 6fdc3bbf439d5f0b1b37bb82169e06416c6a49fe Mon Sep 17 00:00:00 2001
From: Christoph Witzko <github@christophwitzko.com>
Date: Wed, 14 Feb 2024 17:21:08 +0100
Subject: [PATCH] feat: improve commit pattern regexp

---
 pkg/analyzer/commit_analyzer.go      |  2 +-
 pkg/analyzer/commit_analyzer_test.go | 66 ++++++++++++++++++++++++++++
 2 files changed, 67 insertions(+), 1 deletion(-)

diff --git a/pkg/analyzer/commit_analyzer.go b/pkg/analyzer/commit_analyzer.go
index 04a294b..76cecc5 100644
--- a/pkg/analyzer/commit_analyzer.go
+++ b/pkg/analyzer/commit_analyzer.go
@@ -9,7 +9,7 @@ import (
 
 var (
 	CAVERSION              = "dev"
-	commitPattern          = regexp.MustCompile(`^(\w*)(?:\((.*)\))?(\!)?\: (.*)$`)
+	commitPattern          = regexp.MustCompile(`^([^\s\(\!]+)(?:\(([^\)]*)\))?(\!)?\: (.*)$`)
 	breakingPattern        = regexp.MustCompile("BREAKING CHANGES?")
 	mentionedIssuesPattern = regexp.MustCompile(`#(\d+)`)
 	mentionedUsersPattern  = regexp.MustCompile(`(?i)@([a-z\d]([a-z\d]|-[a-z\d])+)`)
diff --git a/pkg/analyzer/commit_analyzer_test.go b/pkg/analyzer/commit_analyzer_test.go
index d08276f..14c356f 100644
--- a/pkg/analyzer/commit_analyzer_test.go
+++ b/pkg/analyzer/commit_analyzer_test.go
@@ -112,3 +112,69 @@ func TestDefaultAnalyzer(t *testing.T) {
 		})
 	}
 }
+
+func TestCommitPattern(t *testing.T) {
+	testCases := []struct {
+		rawMessage string
+		wanted     []string
+	}{
+		{
+			rawMessage: "feat: new feature",
+			wanted:     []string{"feat", "", "", "new feature"},
+		},
+		{
+			rawMessage: "feat!: new feature",
+			wanted:     []string{"feat", "", "!", "new feature"},
+		},
+		{
+			rawMessage: "feat(api): new feature",
+			wanted:     []string{"feat", "api", "", "new feature"},
+		},
+		{
+			rawMessage: "feat(api): a(b): c:",
+			wanted:     []string{"feat", "api", "", "a(b): c:"},
+		},
+		{
+			rawMessage: "feat(new cool-api): feature",
+			wanted:     []string{"feat", "new cool-api", "", "feature"},
+		},
+		{
+			rawMessage: "feat(😅): cool",
+			wanted:     []string{"feat", "😅", "", "cool"},
+		},
+		{
+			rawMessage: "this-is-also(valid): cool",
+			wanted:     []string{"this-is-also", "valid", "", "cool"},
+		},
+		{
+			rawMessage: "🚀(🦄): emojis!",
+			wanted:     []string{"🚀", "🦄", "", "emojis!"},
+		},
+		// invalid messages
+		{
+			rawMessage: "feat (new api): feature",
+			wanted:     nil,
+		},
+		{
+			rawMessage: "feat((x)): test",
+			wanted:     nil,
+		},
+		{
+			rawMessage: "feat:test",
+			wanted:     nil,
+		},
+	}
+	for _, tc := range testCases {
+		t.Run(fmt.Sprintf("CommitPattern: %s", tc.rawMessage), func(t *testing.T) {
+			rawMessageLines := strings.Split(tc.rawMessage, "\n")
+			found := commitPattern.FindAllStringSubmatch(rawMessageLines[0], -1)
+			if len(tc.wanted) == 0 {
+				require.Len(t, found, 0)
+				return
+			}
+			require.Len(t, found, 1)
+			require.Len(t, found[0], 5)
+			require.Equal(t, tc.wanted, found[0][1:])
+		})
+	}
+}
-- 
GitLab