读取 go.mod 文件并检测项目的版本。

huangapple go评论109阅读模式
英文:

Read go.mod and detect the version of project

问题

大多数情况下,go.mod文件的样子如下:

  1. module <module_name>
  2. go 1.16
  3. require (...)

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

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

我猜FindString()MatchString()函数可以帮助我,但我不确定如何使用!

英文:

Mostly, go.mod file looks something like this :

  1. module &lt;module_name&gt;
  2. go 1.16
  3. require (...)

Now, I want to extract the version value 1.16 in another golang project
I read the file and stored it in a buffer.

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

I guess FindString() or MatchString() functions can help me out here, but I am not sure how !

答案1

得分: 3

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

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

如果你必须使用正则表达式,可以按照以下方式操作:

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

Instead of regexp you could just use &quot;golang.org/x/mod/modfile&quot; to parse the go.mod file's contents.

  1. f, err := modfile.Parse(&quot;go.mod&quot;, file_bytes, nil)
  2. if err != nil {
  3. panic(err)
  4. }
  5. fmt.Println(f.Go.Version)

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


If you have to use regexp, then you could do the following:

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

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

答案2

得分: 1

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

例如,要列出主模块的GoVersion

  1. $ go list -f {{.GoVersion}} -m
英文:

The simple way to report information about a Go module is to use go list. You can use the -m flag to list properties of modules and the -f flag to report specific fields. If no specific module is given, go list -m reports information about the main module (containing the current working directory).

For example, to list the GoVersion for the main module:

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

huangapple
  • 本文由 发表于 2021年10月19日 12:54:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/69625297.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定