如何获取 Go 模块依赖项的路径?

fly*_*lyx 5 code-generation go go-modules

我有两个 Go 模块,我们将它们命名为example.com/aexample.com/b

让这example.com/ago.mod

module example.com/a

go 1.12

require (
  example.com/b v0.4.2
)
Run Code Online (Sandbox Code Playgroud)

example.com/b的根目录下有一个名为data.yaml. example.com/a需要自动生成一些代码作为其构建过程的一部分。这个自动生成需要阅读data.yaml

如何在目录中查询读取该文件example.com/a的路径example.com/b?我知道下载后,该模块将位于其中的某个位置(go env GOPATH)/pkg/mod,但我不知道如何从那里构建路径,因为它包含一些!不属于导入路径的字符。我希望有一些go mod或 的子命令go list可以输出路径,但我在文档中没有找到它。

我考虑过通过(是的,我知道,但我现在不想要求 Go 1.16)包含data.yaml在 Go 代码中,但是只有在编译时需要时,我才能在运行时访问。go-bindata//go:embed

mko*_*iva 5

您可以go list-mflag 和-fflag 一起使用,如下所示:

go list -m -f '{{.Dir}}' example.com/b
Run Code Online (Sandbox Code Playgroud)

旗帜-m

导致 go list 列出模块而不是包。在这种模式下,go list 的参数可以是模块、模块模式(包含 ... 通配符)、版本查询或特殊模式 all,它匹配构建列表中的所有模块。如果未指定参数,则列出主模块。

参考

旗帜-f

使用包模板的语法指定输出的替代格式。使用该标志时,传递给模板的结构-m是:

type Module struct {
    Path      string       // module path
    Version   string       // module version
    Versions  []string     // available module versions (with -versions)
    Replace   *Module      // replaced by this module
    Time      *time.Time   // time version was created
    Update    *Module      // available update, if any (with -u)
    Main      bool         // is this the main module?
    Indirect  bool         // is this module only an indirect dependency of main module?
    Dir       string       // directory holding files for this module, if any
    GoMod     string       // path to go.mod file for this module, if any
    GoVersion string       // go version used in module
    Error     *ModuleError // error loading module }

type ModuleError struct {
    Err string // the error itself
}
Run Code Online (Sandbox Code Playgroud)

[以上引用已根据上下文进行了更改]

参考