Refactor action validation

Signed-off-by: Steven Kriegler <sk.bunsenbrenner@gmail.com>
This commit is contained in:
justusbunsi 2021-10-17 11:12:50 +02:00
parent 826204b667
commit 8a7e9f83fa
No known key found for this signature in database
GPG key ID: 82B29BF2507F9F8B
3 changed files with 33 additions and 7 deletions

View file

@ -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
}

View file

@ -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")
}

View file

@ -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]