diff --git a/internal/actions/actions.go b/internal/actions/actions.go index 28ec2f5..166098d 100644 --- a/internal/actions/actions.go +++ b/internal/actions/actions.go @@ -1,8 +1,22 @@ package actions +import "strings" + type BotAction string const ( ActionReview BotAction = "/sq-bot review" ActionPrefix string = "/sq-bot" ) + +func IsValidBotComment(c string) bool { + if !strings.HasPrefix(c, ActionPrefix) { + return false + } + + if c != string(ActionReview) { + return false + } + + return true +} diff --git a/internal/actions/actions_test.go b/internal/actions/actions_test.go new file mode 100644 index 0000000..14e13c7 --- /dev/null +++ b/internal/actions/actions_test.go @@ -0,0 +1,17 @@ +package actions + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestIsValidBotCommentForInvalidComment(t *testing.T) { + assert.False(t, IsValidBotComment(""), "Undetected missing action prefix") + assert.False(t, IsValidBotComment("/sq-bot invalid-command"), "Undetected invalid bot command") + assert.False(t, IsValidBotComment("Some context with /sq-bot review within"), "Incorrect bot prefix detected inside random comment") +} + +func TestIsValidBotCommentForValidComment(t *testing.T) { + assert.True(t, IsValidBotComment("/sq-bot review"), "Correct bot comment not recognized") +} diff --git a/internal/webhooks/gitea/comment.go b/internal/webhooks/gitea/comment.go index 5cbe899..4daf6c9 100644 --- a/internal/webhooks/gitea/comment.go +++ b/internal/webhooks/gitea/comment.go @@ -4,7 +4,6 @@ import ( "encoding/json" "fmt" "log" - "strings" "gitea-sonarqube-pr-bot/internal/actions" giteaSdk "gitea-sonarqube-pr-bot/internal/clients/gitea" @@ -55,12 +54,8 @@ func (w *CommentWebhook) Validate() error { return fmt.Errorf("ignore hook for action others than created") } - if !strings.HasPrefix(w.Comment.Body, actions.ActionPrefix) { - return fmt.Errorf("ignore hook for non-bot action comment") - } - - if w.Comment.Body != string(actions.ActionReview) { - return fmt.Errorf("ignore hook for unknown bot action") + if !actions.IsValidBotComment(w.Comment.Body) { + return fmt.Errorf("ignore hook for non-bot action comment or unknown action") } w.ConfiguredProject = settings.Projects[pIdx]