diff --git a/cmd/check.go b/cmd/check.go index f1a67f6..49af742 100644 --- a/cmd/check.go +++ b/cmd/check.go @@ -7,6 +7,8 @@ import ( "regexp" "strings" + "github.com/charmbracelet/log" + "github.com/muandane/goji/pkg/config" "github.com/spf13/cobra" ) @@ -18,7 +20,10 @@ var checkCmd = &cobra.Command{ Run: func(cmd *cobra.Command, args []string) { var commitMessage string fromFile, _ := cmd.Flags().GetBool("from-file") - + config, err := config.ViperConfig() + if err != nil { + log.Fatalf("Error loading config file: %v", err) + } if fromFile { // Read commit message from file if len(os.Args) < 2 { @@ -38,14 +43,54 @@ var checkCmd = &cobra.Command{ commitMessage = strings.TrimSpace(string(output)) } + emojisToIgnore := make(map[string]string) + for _, t := range config.Types { + emojisToIgnore[t.Emoji] = "" + } + + for emoji, replacement := range emojisToIgnore { + commitMessage = strings.ReplaceAll(commitMessage, emoji, replacement) + } + // Define the regex pattern for a conventional commit message - re := regexp.MustCompile(`\A[\w\s]*?(feat|fix|docs|style|refactor|test|chore|build|ci|perf|improvement|package)(\([\w\s]*\))?[: ].+\z`) - if !re.MatchString(commitMessage) { - fmt.Printf("Error: Your commit message does not follow the conventional commit format. %s", commitMessage) - os.Exit(1) - } else { - fmt.Printf("Success: Your commit message follows the conventional commit format. %s", commitMessage) + parts := strings.SplitN(commitMessage, ":", 2) + if len(parts) != 2 { + fmt.Println("Error: Commit message does not follow the conventional commit format.") + return + } + var typeNames []string + for _, t := range config.Types { + typeNames = append(typeNames, t.Name) + } + typePattern := strings.Join(typeNames, "|") + // Validate the type and scope + typeScope := strings.Split(strings.TrimSpace(parts[0]), "(") + if len(typeScope) > 2 { + fmt.Println("Error: Commit message does not follow the conventional commit format.") + return + } + + // Validate the type + typeRegex := regexp.MustCompile(`^[\w\s]*?(` + typePattern + `)$`) + if !typeRegex.MatchString(typeScope[0]) { + fmt.Println("Error: Commit message type is invalid.") + return + } + + // Validate the scope (optional) + if len(typeScope) == 2 { + scope := strings.TrimSuffix(typeScope[1], ")") + if scope == "" { + fmt.Println("Error: Commit message scope is empty.") + return + } + } + description := strings.TrimSpace(parts[1]) + if description == "" { + fmt.Println("Error: Commit message description is empty.") + return } + fmt.Printf("Success: Your commit message follows the conventional commit format: \n%s", commitMessage) }, }