JOJ3/pkg/healthcheck/commit.go

84 lines
2.1 KiB
Go

package healthcheck
import (
"log/slog"
"strings"
"unicode"
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/plumbing/object"
)
// nonAsciiMsg checks for non-ASCII characters in the commit message.
// If the message starts with "Merge pull request", it skips the non-ASCII characters check.
// Otherwise, it iterates over each character in the message and checks if it is a non-ASCII character.
// If a non-ASCII character is found, it returns an error indicating not to use non-ASCII characters in commit messages.
// Otherwise, it returns nil indicating that the commit message is valid.
func NonAsciiMsg(root string) (jsonOut CheckStage) {
jsonOut = CheckStage{
Name: "NonAsciiMsg",
StdOut: "Checking for non-ASCII characters in commit message: ",
ExitCode: 0,
StdErr: "",
}
// cmd := exec.Command("git", "log", "--encoding=UTF-8", "--format=%B")
repo, err := git.PlainOpen(root)
if err != nil {
jsonOut.StdOut += "Failed"
jsonOut.ExitCode = 1
slog.Error("openning git repo", "err", err)
return jsonOut
}
ref, err := repo.Head()
if err != nil {
jsonOut.StdOut += "Failed"
jsonOut.ExitCode = 1
slog.Error("getting reference", "err", err)
return jsonOut
}
commits, err := repo.Log(&git.LogOptions{From: ref.Hash()})
if err != nil {
jsonOut.StdOut += "Failed"
jsonOut.ExitCode = 1
slog.Error("getting commits", "err", err)
return jsonOut
}
var msgs []string
err = commits.ForEach(func(c *object.Commit) error {
msgs = append(msgs, c.Message)
return nil
})
if err != nil {
jsonOut.StdOut += "Failed"
jsonOut.ExitCode = 1
slog.Error("converting log to string", "err", err)
return jsonOut
}
var nonAsciiMsgs []string
for _, msg := range msgs {
if msg == "" {
continue
}
if strings.HasPrefix(msg, "Merge pull request") {
continue
}
for _, c := range msg {
if c > unicode.MaxASCII {
nonAsciiMsgs = append(nonAsciiMsgs, msg)
}
}
}
if len(nonAsciiMsgs) > 0 {
jsonOut.StdOut += "Failed"
jsonOut.ExitCode = 105
jsonOut.StdErr = "Non-ASCII characters in commit messages:\n" + strings.Join(nonAsciiMsgs, "\n")
return jsonOut
}
jsonOut.StdOut += "OK"
return jsonOut
}