[英]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])
报告有关 Go 模块的信息的简单方法是使用go list
。 您可以使用-m
标志列出模块的属性,使用-f
标志报告特定字段。 如果没有给出特定模块, go list -m
报告有关主模块的信息(包含当前工作目录)。
例如,列出主模块的GoVersion
:
$ go list -f {{.GoVersion}} -m
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.