从模块中获取包列表的方法 - Golang实践指南

从模块中获取包列表的方法 - Golang实践指南 我们有一个包含许多包的Go模块。 例如:

go list github.com/myco/bigmodule/...
github.com/myco/bigmodule
github.com/myco/bigmodule/pkg1
github.com/myco/bigmodule/pkg2
github.com/myco/bigmodule/suspkg
github.com/myco/bigmodule/pkg4

在我们的例子中,这个列表大约有50个包长。其中有一个包存在问题,我们想在所有代码仓库中搜索对该特定包的使用。

我可以执行 go list -m all 来查看一个仓库是否使用了这个大模块。 但我需要找出该仓库是否使用了某个特定的包。

也就是说,这个仓库是否使用了这个包: github.com/myco/bigmodule/suspkg

我希望有一种方法,不需要搜索整个源代码树。

有没有一种方法可以让 go list 返回正在使用的特定包?


更多关于从模块中获取包列表的方法 - Golang实践指南的实战教程也可以访问 https://www.itying.com/category-94-b0.html

2 回复

如果代码是公开的,那么 pkg.go.dev 会提供一个“被导入”的列表。

以下是我的一个库的示例:https://pkg.go.dev/github.com/ncw/directio?tab=importedby

更多关于从模块中获取包列表的方法 - Golang实践指南的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


你可以使用 go list 命令配合 -deps 标志来检查特定包是否被当前模块使用。以下是具体方法:

// 检查当前模块是否依赖特定包
go list -f '{{.ImportPath}}' -deps ./... | grep github.com/myco/bigmodule/suspkg

如果该包被使用,命令会输出包路径;如果没有输出,则表示未使用。

更精确的方法是检查特定包是否在依赖树中:

// 检查特定包是否在依赖中
go list -f '{{if .Deps}}{{range .Deps}}{{.}}{{"\n"}}{{end}}{{end}}' ./... | grep github.com/myco/bigmodule/suspkg

或者使用 JSON 格式输出并解析:

// 使用 JSON 输出并查找特定包
go list -json -deps ./... | jq -r '.Deps[]' | grep github.com/myco/bigmodule/suspkg

如果你需要编程方式实现,可以这样:

package main

import (
    "bytes"
    "fmt"
    "os/exec"
    "strings"
)

func isPackageUsed(pkgPath string) (bool, error) {
    cmd := exec.Command("go", "list", "-f", `{{range .Deps}}{{.}}{{"\n"}}{{end}}`, "./...")
    var out bytes.Buffer
    cmd.Stdout = &out
    err := cmd.Run()
    if err != nil {
        return false, err
    }
    
    deps := strings.Split(out.String(), "\n")
    for _, dep := range deps {
        if dep == pkgPath {
            return true, nil
        }
    }
    return false, nil
}

func main() {
    used, err := isPackageUsed("github.com/myco/bigmodule/suspkg")
    if err != nil {
        fmt.Printf("Error: %v\n", err)
        return
    }
    fmt.Printf("Package used: %v\n", used)
}

对于你的具体需求,最直接的方法是:

# 检查当前目录下所有包是否依赖特定包
go list -deps ./... | grep "github.com/myco/bigmodule/suspkg$"

如果该包被使用,你会看到包含该包路径的输出行。

回到顶部