From e6fde8b54fd6d4affe0db8931c722f1112c578b6 Mon Sep 17 00:00:00 2001 From: BooTun <96464651+bootun@users.noreply.github.com> Date: Tue, 10 Jun 2025 16:16:41 +0800 Subject: [PATCH] refactor: parse go.mod using modfile --- parser/module.go | 26 ++++++++++++-------------- 1 file changed, 12 insertions(+), 14 deletions(-) diff --git a/parser/module.go b/parser/module.go index 536c75f..1119779 100644 --- a/parser/module.go +++ b/parser/module.go @@ -2,9 +2,9 @@ package parser import ( "os" - "regexp" "github.com/pkg/errors" + "golang.org/x/mod/modfile" ) // Go mod 信息 @@ -25,21 +25,19 @@ func ParseGoModuleInfo(path string) (*GoModuleInfo, error) { } func parseGoModContent(content []byte) (*GoModuleInfo, error) { - var info GoModuleInfo - // TODO: simple parser - moduleExp := regexp.MustCompile(`module (.+)`) - goVersionExp := regexp.MustCompile(`go (.+)`) - - if matches := moduleExp.FindSubmatch(content); len(matches) == 2 { - info.Name = string(matches[1]) - } else { + mf, err := modfile.Parse("go.mod", content, nil) + if err != nil { + return nil, err + } + if mf.Module == nil { return nil, errors.New("module name not found") } - - if matches := goVersionExp.FindSubmatch(content); len(matches) == 2 { - info.GoVersion = string(matches[1]) - } else { + if mf.Go == nil { return nil, errors.New("go version not found") } - return &info, nil + info := &GoModuleInfo{ + Name: mf.Module.Mod.Path, + GoVersion: mf.Go.Version, + } + return info, nil }