Go 仅生成扫描 main.go

Go generate only scans main.go

我在使用 go generate 生成 grpc 服务器时遇到了一些问题运行从我的项目目录的根目录生成 go generate。

当我运行go generate -v它只有returnsmain.go。但是,这些指令是在一个子包中定义的。如果我在子包中 运行 go generate 它按预期工作。我希望进口确保 go generate 会找到子包和 运行 指令。

项目结构如下:

cmd/
  root.go
  run.go
pkg/
  subpkg/
    protobuf/
      proto1.proto
    subpkg.go
main.go

subpkg.go

的内容
//go:generate protoc -I ./protobuf --go_out=plugins=grpc:./protobuf ./protobuf/proto1.proto
package subpkg

main.go 的内容:

package main

import (
    "fmt"
    "os"

    "my-project/cmd"
)

func main() {
    if err := cmd.RootCommand.Execute(); err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
}

在run.go包中,我导入包subpkg。

如何确保 go generate 可以从项目的根目录 运行 执行所有子包中的所有指令。

您正在寻找 go generate ./...

根据 go help generate:

usage: go generate [-run regexp] [-n] [-v] [-x] [build flags] [file.go... | packages]

...

For more about specifying packages, see 'go help packages'.

go help packages:

Many commands apply to a set of packages:

go action [packages]

Usually, [packages] is a list of import paths.

An import path that is a rooted path or that begins with
a . or .. element is interpreted as a file system path and
denotes the package in that directory.

Otherwise, the import path P denotes the package found in
the directory DIR/src/P for some DIR listed in the GOPATH
environment variable (For more details see: 'go help gopath').

If no import paths are given, the action applies to the
package in the current directory.

...

An import path is a pattern if it includes one or more "..." wildcards,
each of which can match any string, including the empty string and
strings containing slashes. Such a pattern expands to all package
directories found in the GOPATH trees with names matching the
patterns.

因此,当您没有为需要一个包的 Go 命令指定一个包时,它假定该包是当前目录。子目录是不同的包,因此不包括在内。 "this package and all packages in sudirectories underneath it recursively" 的方便 shorthand 是 ./...,如

go get ./...
go generate ./...
go test ./...