Skip to content

Commit

Permalink
refactor(src/validator.go): Separating some validation logic.
Browse files Browse the repository at this point in the history
  • Loading branch information
plvhx committed Jul 15, 2022
1 parent 50eb1a0 commit 202db75
Showing 1 changed file with 107 additions and 0 deletions.
107 changes: 107 additions & 0 deletions src/validator.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,19 @@

package src

import (
"bytes"
"errors"
"fmt"
"io"
"io/fs"
"os"
"regexp"
"strings"

yaml "gopkg.in/yaml.v2"
)

var (
allowedHooks = []string{
"applypatch-msg",
Expand All @@ -20,6 +33,14 @@ var (
}
)

var (
fileModeMask = fs.FileMode(0x1ff)
gitCommitMsgFile = ".git/COMMIT_EDITMSG"
commitTypeConfigFile = ".polar-commitmsg-types.yaml"

commitMsgNotMatchErr = errors.New("Commit message not match.")
)

func Validate(name string) bool {
match := false

Expand All @@ -32,3 +53,89 @@ func Validate(name string) bool {

return match
}

func FetchSerializedCommitTypes() (string, error) {
finfo, err := os.Stat(commitTypeConfigFile)

if err != nil {
return "", err
}

f, err := os.OpenFile(commitTypeConfigFile, os.O_RDONLY, finfo.Mode()&fileModeMask)

if err != nil {
return "", err
}

buf := bytes.NewBuffer(nil)

io.Copy(buf, f)

if err := f.Close(); err != nil {
return "", err
}

types := make(map[string][]string, 0)

err = yaml.Unmarshal(buf.Bytes(), &types)

if err != nil {
return "", err
}

return strings.Join(types["types"], "|"), nil
}

func buildMatchingPattern(types string) (string, error) {
return fmt.Sprintf("^(?:%s)(?:\\(.*\\))(?:\\!)?(?:\\: )(.*)", types), nil
}

func FetchCommitMessage() ([]byte, error) {
buf := bytes.NewBuffer(nil)

finfo, err := os.Stat(gitCommitMsgFile)

if err != nil {
return nil, err
}

f, err := os.OpenFile(gitCommitMsgFile, os.O_RDONLY, finfo.Mode()&fileModeMask)

if err != nil {
return nil, err
}

io.Copy(buf, f)

if err := f.Close(); err != nil {
return nil, err
}

return buf.Bytes(), nil
}

func ValidateCommit(buf []byte) error {
types, err := FetchSerializedCommitTypes()

if err != nil {
return err
}

pat, err := buildMatchingPattern(types)

if err != nil {
return err
}

matched, err := regexp.Match(pat, buf)

if err != nil {
return err
}

if !matched {
return commitMsgNotMatchErr
}

return nil
}

0 comments on commit 202db75

Please sign in to comment.