Skip to content

Commit

Permalink
feat: new gomodcheck linter
Browse files Browse the repository at this point in the history
  • Loading branch information
wwcchh0123 authored and CarlJi committed Sep 2, 2024
1 parent f4a0b59 commit c7ca1d7
Show file tree
Hide file tree
Showing 2 changed files with 82 additions and 0 deletions.
81 changes: 81 additions & 0 deletions internal/linters/go/gomodcheck/gomodcheck.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
package gomodcheck

import (
"bufio"
"context"
"os"
"regexp"

"path/filepath"
"strings"

"github.com/qiniu/reviewbot/config"
"github.com/qiniu/reviewbot/internal/linters"

"github.com/qiniu/x/xlog"
)

var lintName = "gomodcheck"

func init() {
linters.RegisterPullRequestHandler(lintName, goModCheckHandler)
linters.RegisterLinterLanguages(lintName, []string{".go", ".mod"})
}

func goModCheckHandler(ctx context.Context, a linters.Agent) error {
log := xlog.New(ctx.Value(config.EventGUIDKey).(string))
parsedOutput, err := goModCheckOutput(log, a)
if err != nil {
log.Errorf("gomodchecks parse output failed: %v", err)
return err
}
return linters.Report(log, a, parsedOutput)

}

func goModCheckOutput(log *xlog.Logger, a linters.Agent) (map[string][]linters.LinterOutput, error) {
output := make(map[string][]linters.LinterOutput)
for _, file := range a.PullRequestChangedFiles {
if filepath.Ext(file.GetFilename()) != ".mod" {
continue
}

replaceRegex := regexp.MustCompile(`^replace\s+([^\s]+)\s+=>\s+([^\s]+)`)
goModPath := filepath.Join(a.RepoDir, file.GetFilename())
file, err := os.Open(goModPath)
if err != nil {
log.Errorf("Error opening %s: %s", goModPath, err)
continue
}
defer file.Close()

scanner := bufio.NewScanner(file)
lineNumber := 0
filename := strings.TrimPrefix(goModPath, a.RepoDir+"/")
msg := "It is not recommended to use `replace ../xxx` to specify dependency "

for scanner.Scan() {
lineNumber++
line := scanner.Text()
if matches := replaceRegex.FindStringSubmatch(line); len(matches) > 0 {
replacementPath := matches[2]
if strings.HasPrefix(replacementPath, "../") {
output[filename] = append(output[filename], linters.LinterOutput{
File: filename,
Line: lineNumber,
Column: 1,
Message: msg,
})
}
}
}

if err := scanner.Err(); err != nil {
log.Errorf("Error reading go.mod: %s", err)
continue
}

}

return output, nil
}
1 change: 1 addition & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ import (
_ "github.com/qiniu/reviewbot/internal/linters/git-flow/commit-check"
_ "github.com/qiniu/reviewbot/internal/linters/go/gofmt"
_ "github.com/qiniu/reviewbot/internal/linters/go/golangci_lint"
_ "github.com/qiniu/reviewbot/internal/linters/go/gomodcheck"
_ "github.com/qiniu/reviewbot/internal/linters/java/pmdcheck"
_ "github.com/qiniu/reviewbot/internal/linters/java/stylecheck"
_ "github.com/qiniu/reviewbot/internal/linters/lua/luacheck"
Expand Down

0 comments on commit c7ca1d7

Please sign in to comment.