github.com/kcmvp/gob@v1.0.17/cmd/gbc/command/exec.go (about) 1 /* 2 Copyright © 2023 NAME HERE <EMAIL ADDRESS> 3 */ 4 package command 5 6 import ( 7 "bufio" 8 "errors" 9 "fmt" 10 "os" 11 "regexp" 12 "strings" 13 14 "github.com/fatih/color" 15 "github.com/kcmvp/gob/cmd/gbc/artifact" 16 "github.com/samber/lo" 17 "github.com/spf13/cobra" 18 ) 19 20 const pushDeleteHash = "0000000000000000000000000000000000000000" 21 22 // validateCommitMsg invoked by git commit-msg hook, an error returns when it fails to validate 23 // the commit message 24 var validateCommitMsg Execution = func(_ *cobra.Command, args ...string) error { 25 if len(args) < 2 { 26 return fmt.Errorf(color.RedString("please input commit message")) 27 } 28 input, _ := os.ReadFile(args[1]) 29 regex := regexp.MustCompile(`\r?\n`) 30 commitMsg := regex.ReplaceAllString(string(input), "") 31 pattern, _ := lo.Last(args) 32 regex = regexp.MustCompile(pattern) 33 if !regex.MatchString(commitMsg) { 34 return fmt.Errorf(color.RedString("commit message must follow %s", pattern)) 35 } 36 return nil 37 } 38 39 func execValidArgs() []string { 40 return lo.Map(artifact.CurProject().Executions(), func(exec artifact.Execution, _ int) string { 41 return exec.CmdKey 42 }) 43 } 44 45 func pushDelete(cmd string) bool { 46 if cmd == artifact.PrePush { 47 scanner := bufio.NewScanner(os.Stdin) 48 for scanner.Scan() { 49 line := scanner.Text() 50 if strings.Contains(line, pushDeleteHash) && strings.Contains(line, "delete") { 51 return true 52 } 53 } 54 } 55 return false 56 } 57 58 func do(execution artifact.Execution, cmd *cobra.Command, args ...string) error { 59 if execution.CmdKey == artifact.CommitMsg { 60 args = append(args, execution.Actions...) 61 return validateCommitMsg(nil, args...) 62 } 63 if pushDelete(execution.CmdKey) { 64 return nil 65 } 66 // process hook 67 for _, arg := range execution.Actions { 68 if err := execute(cmd, arg); err != nil { 69 return errors.New(color.RedString("failed to %s the project \n", arg)) 70 } 71 } 72 return nil 73 } 74 75 // execCmd represents the exec command 76 var execCmd = &cobra.Command{ 77 Use: "exec", 78 Short: "Execute any tools that have been setup", 79 Long: `Execute any tools that have been setup`, 80 Args: func(cmd *cobra.Command, args []string) error { 81 if err := cobra.MaximumNArgs(3)(cmd, args); err != nil { 82 return errors.New(color.RedString(err.Error())) 83 } 84 if err := cobra.MinimumNArgs(1)(cmd, args); err != nil { 85 return errors.New(color.RedString(err.Error())) 86 } 87 if !lo.Contains(execValidArgs(), args[0]) { 88 return errors.New(color.RedString("invalid arg %s", args[0])) 89 } 90 return nil 91 }, 92 RunE: func(cmd *cobra.Command, args []string) error { 93 execution, _ := lo.Find(artifact.CurProject().Executions(), func(exec artifact.Execution) bool { 94 return exec.CmdKey == args[0] 95 }) 96 return do(execution, cmd, args...) 97 }, 98 } 99 100 func init() { 101 rootCmd.AddCommand(execCmd) 102 }