From f99ad5eae4744fe17aed5a1e0fba9c780971a8fd Mon Sep 17 00:00:00 2001 From: Boming Zhang Date: Fri, 28 Mar 2025 05:01:07 -0400 Subject: [PATCH] style: more linters --- .golangci.yaml | 30 ++++++++++++++++++++------ cmd/joj3/env/env.go | 2 +- cmd/joj3/log.go | 14 ++++++------ cmd/joj3/main_test.go | 15 +------------ cmd/joj3/stage.go | 8 +++---- internal/executor/dummy/executor.go | 2 +- internal/executor/local/executor.go | 2 +- internal/executor/sandbox/convert.go | 6 +++--- internal/parser/clangtidy/convert.go | 6 +++--- internal/parser/clangtidy/formatter.go | 10 ++++----- internal/parser/clangtidy/parser.go | 2 +- internal/parser/clangtidy/score.go | 4 ++-- internal/parser/cppcheck/parser.go | 15 +++---------- internal/parser/cppcheck/score.go | 8 +++---- internal/parser/cpplint/parser.go | 4 ++-- internal/parser/debug/parser.go | 2 +- internal/parser/diff/parser.go | 2 +- internal/parser/dummy/parser.go | 2 +- internal/parser/healthcheck/parser.go | 2 +- internal/parser/keyword/parser.go | 4 ++-- internal/parser/log/parser.go | 2 +- internal/parser/resultdetail/parser.go | 2 +- internal/parser/resultstatus/parser.go | 2 +- internal/parser/sample/parser.go | 2 +- internal/parser/tierscore/parser.go | 2 +- internal/stage/run.go | 8 +++---- internal/stage/status.go | 4 ++-- pkg/healthcheck/all.go | 6 +++--- pkg/healthcheck/commit.go | 4 ++-- pkg/healthcheck/meta.go | 2 +- pkg/healthcheck/nonascii.go | 20 ++++++++--------- 31 files changed, 94 insertions(+), 100 deletions(-) diff --git a/.golangci.yaml b/.golangci.yaml index 1f67b1b..d55bac5 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -1,12 +1,28 @@ linters: enable: - - gosec + - bidichk + - dupl + - errcheck - gocritic - - gofumpt - gofmt + - gofumpt - goimports -issues: - exclude-rules: - - linters: - - gosec - text: G601 # false positive since go 1.22 + - gosec + - gosimple + - govet + - ineffassign + - nakedret + - nolintlint + - prealloc + - staticcheck + - stylecheck + - testifylint + - typecheck + - unconvert + - unused + - unparam + - usetesting + - wastedassign +linters-settings: + stylecheck: + checks: ["all", "-ST1005"] diff --git a/cmd/joj3/env/env.go b/cmd/joj3/env/env.go index 4535751..9c7e700 100644 --- a/cmd/joj3/env/env.go +++ b/cmd/joj3/env/env.go @@ -42,7 +42,7 @@ func init() { low := timestamp & 0xFFFFFFFF combined := high ^ low combined ^= int64(pid) - combined ^= int64(timestamp >> 16) + combined ^= timestamp >> 16 combined ^= (combined >> 8) combined ^= (combined << 16) Attr.RunID = fmt.Sprintf("%08X", combined&0xFFFFFFFF) diff --git a/cmd/joj3/log.go b/cmd/joj3/log.go index 387ac9c..8fef68a 100644 --- a/cmd/joj3/log.go +++ b/cmd/joj3/log.go @@ -66,12 +66,12 @@ func newSlogAttrs(csvPath string) (attrs []slog.Attr) { } // if csvPath is empty, just return if csvPath == "" { - return + return attrs } file, err := os.Open(csvPath) if err != nil { slog.Error("open csv", "error", err) - return + return attrs } defer file.Close() reader := csv.NewReader(file) @@ -82,7 +82,7 @@ func newSlogAttrs(csvPath string) (attrs []slog.Attr) { } if err != nil { slog.Error("read csv", "error", err) - return + return attrs } if len(row) < 3 { continue @@ -103,7 +103,7 @@ func newSlogAttrs(csvPath string) (attrs []slog.Attr) { } } } - return + return attrs } func setupSlog(conf *conf.Conf) error { @@ -121,14 +121,14 @@ func setupSlog(conf *conf.Conf) error { &slog.HandlerOptions{Level: slog.LevelDebug}) handlers = append(handlers, debugTextHandler.WithAttrs(attrs)) // Json file handler for debug logs - debugJsonFile, err := os.OpenFile(logPath+".ndjson", + debugJSONFile, err := os.OpenFile(logPath+".ndjson", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o640) if err != nil { return err } - debugJsonHandler := slog.NewJSONHandler(debugJsonFile, + debugJSONHandler := slog.NewJSONHandler(debugJSONFile, &slog.HandlerOptions{Level: slog.LevelDebug}) - handlers = append(handlers, debugJsonHandler.WithAttrs(attrs)) + handlers = append(handlers, debugJSONHandler.WithAttrs(attrs)) } stderrLogLevel := slog.LevelInfo if runningTest { diff --git a/cmd/joj3/main_test.go b/cmd/joj3/main_test.go index c0a2e7f..edf1767 100644 --- a/cmd/joj3/main_test.go +++ b/cmd/joj3/main_test.go @@ -88,20 +88,7 @@ func TestRun(t *testing.T) { } for _, tt := range tests { t.Run(tt, func(t *testing.T) { - origDir, err := os.Getwd() - if err != nil { - t.Fatal(err) - } - err = os.Chdir(fmt.Sprintf("%s%s", root, tt)) - if err != nil { - t.Fatal(err) - } - defer func() { - err := os.Chdir(origDir) - if err != nil { - t.Fatal(err) - } - }() + t.Chdir(fmt.Sprintf("%s%s", root, tt)) os.Args = []string{"./joj3"} outputFile := "joj3_result.json" defer os.Remove(outputFile) diff --git a/cmd/joj3/stage.go b/cmd/joj3/stage.go index 1357f04..bf6560f 100644 --- a/cmd/joj3/stage.go +++ b/cmd/joj3/stage.go @@ -149,19 +149,19 @@ func runStages( if err != nil { slog.Error("generate preStages", "error", err) stageResults, forceQuitStageName = newErrorStageResults(err) - return + return stageResults, forceQuitStageName, err } stages, err := generateStages(conf.Stage.Stages, groups) if err != nil { slog.Error("generate stages", "error", err) stageResults, forceQuitStageName = newErrorStageResults(err) - return + return stageResults, forceQuitStageName, err } postStages, err := generateStages(conf.Stage.PostStages, groups) if err != nil { slog.Error("generate postStages", "error", err) stageResults, forceQuitStageName = newErrorStageResults(err) - return + return stageResults, forceQuitStageName, err } defer stage.Cleanup() // ignore force quit in preStages & postStages @@ -194,5 +194,5 @@ func runStages( if err != nil { slog.Error("run postStages", "error", err) } - return + return stageResults, forceQuitStageName, err } diff --git a/internal/executor/dummy/executor.go b/internal/executor/dummy/executor.go index e8aa3a4..a31c348 100644 --- a/internal/executor/dummy/executor.go +++ b/internal/executor/dummy/executor.go @@ -3,7 +3,7 @@ package dummy import "github.com/joint-online-judge/JOJ3/internal/stage" func (e *Dummy) Run(cmds []stage.Cmd) ([]stage.ExecutorResult, error) { - var res []stage.ExecutorResult + res := make([]stage.ExecutorResult, 0, len(cmds)) for range cmds { res = append(res, stage.ExecutorResult{ Status: stage.StatusAccepted, diff --git a/internal/executor/local/executor.go b/internal/executor/local/executor.go index 565c0be..667e8ce 100644 --- a/internal/executor/local/executor.go +++ b/internal/executor/local/executor.go @@ -113,7 +113,7 @@ func ToRlimit(cmd stage.Cmd) ([]syscall.Rlimit, []int, error) { if err := syscall.Getrlimit(syscall.RLIMIT_CPU, ¤t); err != nil { return nil, nil, fmt.Errorf("getrlimit RLIMIT_CPU failed: %w", err) } - userTimeLimit := min((uint64(cmd.CPULimit)+1e9-1)/1e9, current.Max) // ns to s + userTimeLimit := min((cmd.CPULimit+1e9-1)/1e9, current.Max) // ns to s rlimits = append(rlimits, syscall.Rlimit{ Cur: userTimeLimit, Max: current.Max, diff --git a/internal/executor/sandbox/convert.go b/internal/executor/sandbox/convert.go index bd99031..51fc45f 100644 --- a/internal/executor/sandbox/convert.go +++ b/internal/executor/sandbox/convert.go @@ -12,7 +12,7 @@ import ( // copied from https://github.com/criyle/go-judge/blob/master/cmd/go-judge-shell/grpc.go func convertPBCmd(cmd []stage.Cmd) []*pb.Request_CmdType { - var ret []*pb.Request_CmdType + ret := make([]*pb.Request_CmdType, 0, len(cmd)) for _, c := range cmd { ret = append(ret, &pb.Request_CmdType{ Args: c.Args, @@ -140,7 +140,7 @@ func convertPBFile(i stage.CmdFile) *pb.Request_File { } func convertPBResult(res []*pb.Response_Result) []stage.ExecutorResult { - var ret []stage.ExecutorResult + ret := make([]stage.ExecutorResult, 0, len(res)) for _, r := range res { ret = append(ret, stage.ExecutorResult{ Status: stage.Status(r.Status), @@ -167,7 +167,7 @@ func convertFiles(buf map[string][]byte) map[string]string { } func convertPBFileError(fe []*pb.Response_FileError) []stage.FileError { - var ret []stage.FileError + ret := make([]stage.FileError, 0, len(fe)) for _, v := range fe { ret = append(ret, stage.FileError{ Name: v.Name, diff --git a/internal/parser/clangtidy/convert.go b/internal/parser/clangtidy/convert.go index 727a557..a5fc319 100644 --- a/internal/parser/clangtidy/convert.go +++ b/internal/parser/clangtidy/convert.go @@ -131,12 +131,12 @@ func convertPathsToRelative(messages *[]ClangMessage, conf Conf) { func parseLines(lines []string, conf Conf) []ClangMessage { messages := make([]ClangMessage, 0) for _, line := range lines { - if isIgnored(string(line)) { + if isIgnored(line) { continue } - message := parseMessage(string(line)) + message := parseMessage(line) if message.level == UNKNOWN && len(messages) > 0 { - messages[len(messages)-1].detailsLines = append(messages[len(messages)-1].detailsLines, string(line)) + messages[len(messages)-1].detailsLines = append(messages[len(messages)-1].detailsLines, line) } else if message.level != UNKNOWN { messages = append(messages, message) } diff --git a/internal/parser/clangtidy/formatter.go b/internal/parser/clangtidy/formatter.go index 46b6225..0d1a81f 100644 --- a/internal/parser/clangtidy/formatter.go +++ b/internal/parser/clangtidy/formatter.go @@ -6,7 +6,7 @@ import ( ) // Referenced from https://github.com/yuriisk/clang-tidy-converter/blob/master/clang_tidy_converter/parser/clang_tidy_parser.py -type JsonMessage struct { +type JSONMessage struct { Type string `json:"type"` CheckName string `json:"checkname"` Description string `json:"description"` @@ -17,16 +17,16 @@ type JsonMessage struct { Severity string `json:"severity"` } -func format(messages []ClangMessage) []JsonMessage { - formattedMessages := make([]JsonMessage, len(messages)) +func format(messages []ClangMessage) []JSONMessage { + formattedMessages := make([]JSONMessage, len(messages)) for i, message := range messages { formattedMessages[i] = formatMessage(message) } return formattedMessages } -func formatMessage(message ClangMessage) JsonMessage { - result := JsonMessage{ +func formatMessage(message ClangMessage) JSONMessage { + result := JSONMessage{ Type: "issue", CheckName: message.diagnosticName, Description: message.message, diff --git a/internal/parser/clangtidy/parser.go b/internal/parser/clangtidy/parser.go index dcd08d4..990a6ed 100644 --- a/internal/parser/clangtidy/parser.go +++ b/internal/parser/clangtidy/parser.go @@ -26,7 +26,7 @@ func (p *ClangTidy) Run(results []stage.ExecutorResult, confAny any) ( if err != nil { return nil, true, err } - var res []stage.ParserResult + res := make([]stage.ParserResult, 0, len(results)) forceQuit := false for _, result := range results { parseRes := p.parse(result, *conf) diff --git a/internal/parser/clangtidy/score.go b/internal/parser/clangtidy/score.go index 17516fc..6414a80 100644 --- a/internal/parser/clangtidy/score.go +++ b/internal/parser/clangtidy/score.go @@ -6,7 +6,7 @@ import ( "strings" ) -func getResult(jsonMessages []JsonMessage, conf Conf) (int, string) { +func getResult(jsonMessages []JSONMessage, conf Conf) (int, string) { score := conf.Score comment := "### Test results summary\n\n" matchCount := make(map[string]int) @@ -29,7 +29,7 @@ func getResult(jsonMessages []JsonMessage, conf Conf) (int, string) { Count int ScoreChange int } - var results []Result + results := make([]Result, 0, len(matchCount)) for keyword, count := range matchCount { results = append(results, Result{ Keyword: keyword, diff --git a/internal/parser/cppcheck/parser.go b/internal/parser/cppcheck/parser.go index b1560d7..f868b84 100644 --- a/internal/parser/cppcheck/parser.go +++ b/internal/parser/cppcheck/parser.go @@ -14,7 +14,7 @@ type Record struct { Column int `json:"column"` Severity string `json:"severity"` Message string `json:"message"` - Id string `json:"id"` + ID string `json:"id"` } func (*CppCheck) parse(executorResult stage.ExecutorResult, conf Conf) stage.ParserResult { @@ -39,16 +39,7 @@ func (*CppCheck) parse(executorResult stage.ExecutorResult, conf Conf) stage.Par } records = append(records, record) } - comment, score, err := getResult(records, conf) - if err != nil { - return stage.ParserResult{ - Score: 0, - Comment: fmt.Sprintf( - "Unexpected parser error: %s.", - err, - ), - } - } + comment, score := getResult(records, conf) return stage.ParserResult{ Score: score, @@ -63,7 +54,7 @@ func (p *CppCheck) Run(results []stage.ExecutorResult, confAny any) ( if err != nil { return nil, true, err } - var res []stage.ParserResult + res := make([]stage.ParserResult, 0, len(results)) forceQuit := false for _, result := range results { parseRes := p.parse(result, *conf) diff --git a/internal/parser/cppcheck/score.go b/internal/parser/cppcheck/score.go index 07cb010..92319b3 100644 --- a/internal/parser/cppcheck/score.go +++ b/internal/parser/cppcheck/score.go @@ -19,7 +19,7 @@ const ( UNKNOWN ) -func getResult(records []Record, conf Conf) (string, int, error) { +func getResult(records []Record, conf Conf) (string, int) { score := conf.Score comment := "### Test results summary\n\n" matchCount := make(map[string]int) @@ -27,7 +27,7 @@ func getResult(records []Record, conf Conf) (string, int, error) { for _, record := range records { for _, match := range conf.Matches { for _, keyword := range match.Keywords { - if strings.Contains(record.Id, keyword) || + if strings.Contains(record.ID, keyword) || strings.Contains(record.Severity, keyword) { matchCount[keyword] += 1 scoreChange[keyword] += -match.Score @@ -41,7 +41,7 @@ func getResult(records []Record, conf Conf) (string, int, error) { Count int ScoreChange int } - var results []Result + results := make([]Result, 0, len(matchCount)) for keyword, count := range matchCount { results = append(results, Result{ Keyword: keyword, @@ -62,5 +62,5 @@ func getResult(records []Record, conf Conf) (string, int, error) { comment += fmt.Sprintf("%d. `%s`: %d occurrence(s), %d point(s)\n", i+1, result.Keyword, result.Count, result.ScoreChange) } - return comment, score, nil + return comment, score } diff --git a/internal/parser/cpplint/parser.go b/internal/parser/cpplint/parser.go index 939519a..55bc872 100644 --- a/internal/parser/cpplint/parser.go +++ b/internal/parser/cpplint/parser.go @@ -45,7 +45,7 @@ func (*Cpplint) parse(executorResult stage.ExecutorResult, conf Conf) stage.Pars Count int ScoreChange int } - var results []Result + results := make([]Result, 0, len(matchCount)) for keyword, count := range matchCount { results = append(results, Result{ Keyword: keyword, @@ -79,7 +79,7 @@ func (p *Cpplint) Run(results []stage.ExecutorResult, confAny any) ( if err != nil { return nil, true, err } - var res []stage.ParserResult + res := make([]stage.ParserResult, 0, len(results)) forceQuit := false for _, result := range results { parseRes := p.parse(result, *conf) diff --git a/internal/parser/debug/parser.go b/internal/parser/debug/parser.go index aec0685..e7fdcd8 100644 --- a/internal/parser/debug/parser.go +++ b/internal/parser/debug/parser.go @@ -25,7 +25,7 @@ func (p *Debug) Run(results []stage.ExecutorResult, confAny any) ( if err != nil { return nil, true, err } - var res []stage.ParserResult + res := make([]stage.ParserResult, 0, len(results)) for _, result := range results { res = append(res, p.parse(result, *conf)) } diff --git a/internal/parser/diff/parser.go b/internal/parser/diff/parser.go index 8d7d6d1..d2cb5f9 100644 --- a/internal/parser/diff/parser.go +++ b/internal/parser/diff/parser.go @@ -20,7 +20,7 @@ func (*Diff) Run(results []stage.ExecutorResult, confAny any) ( return nil, true, fmt.Errorf("cases number not match") } - var res []stage.ParserResult + res := make([]stage.ParserResult, 0, len(conf.Cases)) forceQuit := false for i, caseConf := range conf.Cases { result := results[i] diff --git a/internal/parser/dummy/parser.go b/internal/parser/dummy/parser.go index cb33e1f..363f160 100644 --- a/internal/parser/dummy/parser.go +++ b/internal/parser/dummy/parser.go @@ -11,7 +11,7 @@ func (*Dummy) Run(results []stage.ExecutorResult, confAny any) ( if err != nil { return nil, true, err } - var res []stage.ParserResult + res := make([]stage.ParserResult, 0, len(results)) for range results { res = append(res, stage.ParserResult{Score: conf.Score, Comment: conf.Comment}) } diff --git a/internal/parser/healthcheck/parser.go b/internal/parser/healthcheck/parser.go index e2ee7fc..464e06a 100644 --- a/internal/parser/healthcheck/parser.go +++ b/internal/parser/healthcheck/parser.go @@ -49,7 +49,7 @@ func (p *Healthcheck) Run(results []stage.ExecutorResult, confAny any) ( if err != nil { return nil, true, err } - var res []stage.ParserResult + res := make([]stage.ParserResult, 0, len(results)) forceQuit := false for _, result := range results { parserResult, forceQuitResult := p.parse(result, *conf) diff --git a/internal/parser/keyword/parser.go b/internal/parser/keyword/parser.go index d6609a3..203f6b5 100644 --- a/internal/parser/keyword/parser.go +++ b/internal/parser/keyword/parser.go @@ -32,7 +32,7 @@ func (*Keyword) parse(executorResult stage.ExecutorResult, conf Conf) stage.Pars Count int ScoreChange int } - var results []Result + results := make([]Result, 0, len(matchCount)) for keyword, count := range matchCount { results = append(results, Result{ Keyword: keyword, @@ -66,7 +66,7 @@ func (p *Keyword) Run(results []stage.ExecutorResult, confAny any) ( if err != nil { return nil, true, err } - var res []stage.ParserResult + res := make([]stage.ParserResult, 0, len(results)) forceQuit := false for _, result := range results { parseRes := p.parse(result, *conf) diff --git a/internal/parser/log/parser.go b/internal/parser/log/parser.go index 5a2cb5a..2d46c9d 100644 --- a/internal/parser/log/parser.go +++ b/internal/parser/log/parser.go @@ -43,7 +43,7 @@ func (p *Log) Run(results []stage.ExecutorResult, confAny any) ( if err != nil { return nil, true, err } - var res []stage.ParserResult + res := make([]stage.ParserResult, 0, len(results)) for _, result := range results { res = append(res, p.parse(result, *conf)) } diff --git a/internal/parser/resultdetail/parser.go b/internal/parser/resultdetail/parser.go index 01bf768..dcfb197 100644 --- a/internal/parser/resultdetail/parser.go +++ b/internal/parser/resultdetail/parser.go @@ -14,7 +14,7 @@ func (*ResultDetail) Run(results []stage.ExecutorResult, confAny any) ( return nil, true, err } forceQuit := false - var res []stage.ParserResult + res := make([]stage.ParserResult, 0, len(results)) for _, result := range results { comment := "" if conf.ShowExecutorStatus { diff --git a/internal/parser/resultstatus/parser.go b/internal/parser/resultstatus/parser.go index 89bc338..3941969 100644 --- a/internal/parser/resultstatus/parser.go +++ b/internal/parser/resultstatus/parser.go @@ -15,7 +15,7 @@ func (*ResultStatus) Run(results []stage.ExecutorResult, confAny any) ( } score := conf.Score forceQuit := false - var res []stage.ParserResult + res := make([]stage.ParserResult, 0, len(results)) for _, result := range results { comment := conf.Comment if result.Status != stage.StatusAccepted { diff --git a/internal/parser/sample/parser.go b/internal/parser/sample/parser.go index 331f5ad..5c31803 100644 --- a/internal/parser/sample/parser.go +++ b/internal/parser/sample/parser.go @@ -32,7 +32,7 @@ func (p *Sample) Run(results []stage.ExecutorResult, confAny any) ( if err != nil { return nil, true, err } - var res []stage.ParserResult + res := make([]stage.ParserResult, 0, len(results)) for _, result := range results { res = append(res, p.parse(result, *conf)) } diff --git a/internal/parser/tierscore/parser.go b/internal/parser/tierscore/parser.go index e9e0c00..b91796c 100644 --- a/internal/parser/tierscore/parser.go +++ b/internal/parser/tierscore/parser.go @@ -15,7 +15,7 @@ func (*TierScore) Run(results []stage.ExecutorResult, confAny any) ( return nil, true, err } - var res []stage.ParserResult + res := make([]stage.ParserResult, 0, len(results)) forceQuit := false for _, result := range results { diff --git a/internal/stage/run.go b/internal/stage/run.go index e548dca..4366f3a 100644 --- a/internal/stage/run.go +++ b/internal/stage/run.go @@ -36,7 +36,7 @@ func Run(stages []Stage) ( "name", stage.Executor.Name, ) err = fmt.Errorf("executor not found: %s", stage.Executor.Name) - return + return stageResults, forceQuitStageName, err } executorResults, err = executor.Run(stage.Executor.Cmds) if err != nil { @@ -46,7 +46,7 @@ func Run(stages []Stage) ( "name", stage.Executor.Name, "error", err, ) - return + return stageResults, forceQuitStageName, err } for i, executorResult := range executorResults { slog.Debug( @@ -92,7 +92,7 @@ func Run(stages []Stage) ( "name", stageParser.Name, ) err = fmt.Errorf("parser not found: %s", stageParser.Name) - return + return stageResults, forceQuitStageName, err } var parserForceQuit bool tmpParserResults, parserForceQuit, err = parser.Run( @@ -154,7 +154,7 @@ func Run(stages []Stage) ( break } } - return + return stageResults, forceQuitStageName, err } func Cleanup() { diff --git a/internal/stage/status.go b/internal/stage/status.go index 303a60d..8b47368 100644 --- a/internal/stage/status.go +++ b/internal/stage/status.go @@ -76,7 +76,7 @@ func StringToStatus(s string) (Status, error) { // MarshalJSON convert status into string func (s Status) MarshalJSON() ([]byte, error) { - return []byte("\"" + Status(s).String() + "\""), nil + return []byte("\"" + s.String() + "\""), nil } // UnmarshalJSON convert string into status @@ -86,7 +86,7 @@ func (s *Status) UnmarshalJSON(b []byte) error { if err != nil { return err } - *s = Status(v) + *s = v return nil } diff --git a/pkg/healthcheck/all.go b/pkg/healthcheck/all.go index 562e84a..3722072 100644 --- a/pkg/healthcheck/all.go +++ b/pkg/healthcheck/all.go @@ -31,12 +31,12 @@ func All( res.Msg += fmt.Sprintf("### Meta File Check Failed:\n%s\n", err.Error()) res.Failed = true } - err = NonAsciiFiles(rootDir) + err = NonASCIIFiles(rootDir) if err != nil { res.Msg += fmt.Sprintf("### Non-ASCII Characters File Check Failed:\n%s\n", err.Error()) res.Failed = true } - err = NonAsciiMsg(rootDir) + err = NonASCIIMsg(rootDir) if err != nil { res.Msg += fmt.Sprintf("### Non-ASCII Characters Commit Message Check Failed:\n%s\n", err.Error()) res.Failed = true @@ -46,5 +46,5 @@ func All( res.Msg += fmt.Sprintf("### Repo File Check Failed:\n%s\n", err.Error()) res.Failed = true } - return + return res } diff --git a/pkg/healthcheck/commit.go b/pkg/healthcheck/commit.go index 8c9d041..d27b6e4 100644 --- a/pkg/healthcheck/commit.go +++ b/pkg/healthcheck/commit.go @@ -44,12 +44,12 @@ func checkMsg(msg string) bool { return true } -// nonAsciiMsg checks for non-ASCII characters in the commit message. +// NonASCIIMsg checks for non-ASCII characters in the commit message. // 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. // It skips the non-ASCII characters check for lines starting with specific keywords like "Co-authored-by", "Reviewed-by", and "Co-committed-by". -func NonAsciiMsg(root string) error { +func NonASCIIMsg(root string) error { repo, err := git.PlainOpen(root) if err != nil { slog.Error("opening git repo", "err", err) diff --git a/pkg/healthcheck/meta.go b/pkg/healthcheck/meta.go index 1c1c05f..9b3eb86 100644 --- a/pkg/healthcheck/meta.go +++ b/pkg/healthcheck/meta.go @@ -11,7 +11,7 @@ import ( // getMetas retrieves a list of metadata files that are expected to exist in the specified root directory. // It checks for the existence of each file in the fileList and provides instructions if any file is missing. func getMetas(rootDir string, fileList []string) ([]string, string, error) { - var regexList []*regexp.Regexp + regexList := make([]*regexp.Regexp, 0, len(fileList)) for _, file := range fileList { pattern := "(?i)" + file if !strings.Contains(pattern, "\\.") { diff --git a/pkg/healthcheck/nonascii.go b/pkg/healthcheck/nonascii.go index fbd01b5..c652377 100644 --- a/pkg/healthcheck/nonascii.go +++ b/pkg/healthcheck/nonascii.go @@ -12,10 +12,10 @@ import ( "github.com/go-git/go-git/v5/plumbing/format/gitattributes" ) -// getNonAscii retrieves a list of files in the specified root directory that contain non-ASCII characters. +// getNonASCII retrieves a list of files in the specified root directory that contain non-ASCII characters. // It searches for non-ASCII characters in each file's content and returns a list of paths to files containing non-ASCII characters. -func getNonAscii(root string) ([]string, error) { - var nonAscii []string +func getNonASCII(root string) ([]string, error) { + var nonASCII []string gitattrExist := true var matcher gitattributes.Matcher _, err := os.Stat(".gitattributes") @@ -71,7 +71,7 @@ func getNonAscii(root string) ([]string, error) { cont := true for _, c := range scanner.Text() { if c > unicode.MaxASCII { - nonAscii = append(nonAscii, "\t"+path) + nonASCII = append(nonASCII, "\t"+path) cont = false break } @@ -84,20 +84,20 @@ func getNonAscii(root string) ([]string, error) { return nil }) - return nonAscii, err + return nonASCII, err } -// nonAsciiFiles checks for non-ASCII characters in files within the specified root directory. +// NonASCIIFiles checks for non-ASCII characters in files within the specified root directory. // It prints a message with the paths to files containing non-ASCII characters, if any. -func NonAsciiFiles(root string) error { - nonAscii, err := getNonAscii(root) +func NonASCIIFiles(root string) error { + nonASCII, err := getNonASCII(root) if err != nil { slog.Error("getting non-ascii", "err", err) return fmt.Errorf("error getting non-ascii: %w", err) } - if len(nonAscii) > 0 { + if len(nonASCII) > 0 { return fmt.Errorf("Non-ASCII characters found in the following files:\n%s", - strings.Join(nonAscii, "\n")) + strings.Join(nonASCII, "\n")) } return nil }