是否有API获取使用go 1.11模块系统的项目的模块名称?
所以我需要从abc.com/a/m
文件中的模块定义module abc.com/a/m
中获得go.mod
。
答案 0 :(得分:4)
在撰写本文时,我还不知道有任何公开的API。但是,查看go mod
的源代码,有一个功能在Go mod source file中很有用
// ModulePath returns the module path from the gomod file text.
// If it cannot find a module path, it returns an empty string.
// It is tolerant of unrelated problems in the go.mod file.
func ModulePath(mod []byte) string {
//...
}
func main() {
src := `
module github.com/you/hello
require rsc.io/quote v1.5.2
`
mod := ModulePath([]byte(src))
fmt.Println(mod)
}
哪个输出github.com/you/hello
答案 1 :(得分:0)
如果您的起点是一个go.mod
文件,而您正在询问如何解析它,我建议您从go mod edit -json
开始,它将以JSON格式输出一个特定的go.mod
文件。这是文档:
https://golang.org/cmd/go/#hdr-Edit_go_mod_from_tools_or_scripts
或者,您可以使用rogpeppe/go-internal/modfile,这是一个go包,可以解析go.mod
文件,rogpeppe/gohack和更广泛的社区中的其他一些工具也可以使用。 / p>
问题#28101,我认为在Go标准库中添加新API来解析go.mod
文件的跟踪。
以下是go mod edit -json
的文档摘要:
-json标志以JSON格式而不是最终格式打印go.mod文件 将其写回go.mod。 JSON输出对应于这些Go 类型:
type Module struct {
Path string
Version string
}
type GoMod struct {
Module Module
Go string
Require []Require
Exclude []Module
Replace []Replace
}
type Require struct {
Path string
Version string
Indirect bool
}
这是go mod edit -json
的JSON输出示例,显示了实际的模块路径(即模块名称),这是您的原始问题:
{
"Module": {
"Path": "rsc.io/quote"
},
在这种情况下,模块名称为rsc.io/quote
。
答案 2 :(得分:0)
尝试一下?
package main
import (
"fmt"
"io/ioutil"
"os"
modfile "golang.org/x/mod/modfile"
)
const (
RED = "\033[91m"
RESET = "\033[0m"
)
func main() {
modName := GetModuleName()
fmt.Fprintf(os.Stdout, "modName=%+v\n", modName)
}
func exitf(beforeExitFunc func(), code int, format string, args ...interface{}) {
beforeExitFunc()
fmt.Fprintf(os.Stderr, RED+format+RESET, args...)
os.Exit(code)
}
func GetModuleName() string {
goModBytes, err := ioutil.ReadFile("go.mod")
if err != nil {
exitf(func() {}, 1, "%+v\n", err)
}
modName := modfile.ModulePath(goModBytes)
fmt.Fprintf(os.Stdout, "modName=%+v\n", modName)
return modName
}