为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
繁花不似锦 2022-08-24 18:42:27
我有两个Go模块,让我们将它们命名为.example.com/aexample.com/b让它成为 :example.com/ago.modmodule example.com/ago 1.12require (  example.com/b v0.4.2)在 的根目录中,有一个名为 的文件。 需要自动生成一些代码作为其构建过程的一部分。此自动生成需要读取 。example.com/bdata.yamlexample.com/adata.yaml我怎样才能在查询的目录中为路径读取该文件?我知道下载后,模块将位于某个地方,但我不知道如何从那里构造路径,因为它包含一些不属于导入路径的字符。我希望有一些子命令或将输出路径,但我在文档中没有找到它。example.com/aexample.com/b(go env GOPATH)/pkg/mod!go modgo list我已经考虑过通过包含在Go代码中(是的,我知道,但我现在不想需要Go 1.16),但是当我在编译时需要它时,我只能在运行时访问。data.yamlgo-bindata//go:embed
查看完整描述

2 回答

?
慕桂英546537

TA贡献1848条经验 获得超10个赞

您可以像这样与标志和标志一起使用:go list-m-f

go list -m -f '{{.Dir}}' example.com/b

旗帜:-m

导致 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

}


查看完整回答
反对 回复 2022-08-24
?
jeck猫

TA贡献1909条经验 获得超7个赞

您可以像这样计算出模块路径:


package main


import (

    "fmt"

    "os"

    "path"


    "golang.org/x/mod/module"

)


func GetModulePath(name, version string) (string, error) {

    // first we need GOMODCACHE

    cache, ok := os.LookupEnv("GOMODCACHE")

    if !ok {

        cache = path.Join(os.Getenv("GOPATH"), "pkg", "mod")

    }


    // then we need to escape path

    escapedPath, err := module.EscapePath(name)

    if err != nil {

        return "", err

    }


    // version also

    escapedVersion, err := module.EscapeVersion(version)

    if err != nil {

        return "", err

    }


    return path.Join(cache, escapedPath+"@"+escapedVersion), nil

}


func main() {

    var path, err = GetModulePath("github.com/jakubDoka/mlok", "v0.4.7")

    if err != nil {

        panic(err)

    }


    if _, err := os.Stat(path); os.IsNotExist(err) {

        fmt.Println("you don't have this module/version installed")

    }

    fmt.Println("module found in", path)

}


查看完整回答
反对 回复 2022-08-24
  • 2 回答
  • 0 关注
  • 151 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号