0

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

当我运行go generate -v它只返回main.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 可以从项目的根目录运行并执行所有子包中的所有指令。

4

1 回答 1

3

你正在寻找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 命令指定一个包时,它假定该包是当前目录。子目录是不同的包,因此不包括在内。“此包及其下的子目录中的所有包递归”的方便简写是./...,如

go get ./...
go generate ./...
go test ./...
于 2020-01-17T20:59:07.773 回答