【问题标题】:Read go.mod and detect the version of project阅读 go.mod 并检测项目的版本
【发布时间】:2021-12-06 01:17:03
【问题描述】:

大多数情况下,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() 函数可以在这里帮助我,但我不确定如何!

【问题讨论】:

    标签: regex go


    【解决方案1】:

    您可以使用"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

    【讨论】:

      【解决方案2】:

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

      例如,列出主模块的GoVersion

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-09-27
        • 1970-01-01
        • 1970-01-01
        • 2020-09-21
        • 1970-01-01
        • 2019-07-07
        • 2021-03-01
        • 1970-01-01
        相关资源
        最近更新 更多