繁体   English   中英

阅读 go.mod 并检测项目的版本

[英]Read go.mod and detect the version of project

大多数情况下, go.mod文件看起来像这样:

module <module_name>

go 1.16

require (...)

现在,我想在我读取文件并将其存储在缓冲区中的另一个 golang 项目中提取版本值1.16

buf, err := ioutil.ReadFile(goMODfile)
if err != nil {
    return false, err.Error()
}

我想FindString()MatchString()函数可以在这里帮助我,但我不确定如何!

您可以不使用正则表达式,而是使用"golang.org/x/mod/modfile" go.mod "golang.org/x/mod/modfile"来解析go.mod文件的内容。

f, err := modfile.Parse("go.mod", file_bytes, nil)
if err != nil {
    panic(err)
}
fmt.Println(f.Go.Version)

https://play.golang.org/p/XETDzMcTwS_S


如果必须使用正则表达式,则可以执行以下操作:

re := regexp.MustCompile(`(?m)^go (\d+\.\d+(?:\.\d+)?)$`)
match := re.FindSubmatch(file_bytes)
version := string(match[1])

https://play.golang.org/p/L5-LM67cvgP

报告有关 Go 模块的信息的简单方法是使用go list 您可以使用-m标志列出模块的属性,使用-f标志报告特定字段。 如果没有给出特定模块, go list -m报告有关主模块的信息(包含当前工作目录)。

例如,列出主模块的GoVersion

$ go list -f {{.GoVersion}} -m

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM