This example is a slight tweak on the best-practices example for working with Go modules as development dependencies.
The downside of the existing example is that someone who git clone
s your module to make a contribution, would not be able to run go generate
(without extra work).
$ go generate
painkiller.go:5: running "stringer": exec: "stringer": executable file not found in $PATH
Instead of requiring that the stringer
executable be on everyone's path, the go:generate
comment can be changed to use go run
instead of calling the executable directly.
For example, in painkiller.go
, use this
//go:generate go run golang.org/x/tools/cmd/stringer -type=Pill
instead of this
//go:generate stringer -type=Pill
Create a module:
$ mkdir -p /home/gopher/scratchpad/tools
$ cd /home/gopher/scratchpad/tools
$ git init -q
$ git remote add origin https://github.com/go-modules-by-example/tools
$ go mod init
go: creating new go.mod: module github.com/go-modules-by-example/tools
Add stringer
as a dependency by importing the package in a build constraint-ignored file. This file will never be
compiled (nor will it compile, because we are importing a main
package); it is used simply to record the dependency.
The file and the build constraint names are not particularly important, but we choose tools
for the sake of
consistency:
$ cat tools.go
// +build tools
package tools
import (
_ "golang.org/x/tools/cmd/stringer"
)
Use go run golang.org/x/tools/cmd/stringer
via a go:generate
directive:
$ cat painkiller.go
package main
import "fmt"
//go:generate go run golang.org/x/tools/cmd/stringer -type=Pill
type Pill int
const (
Placebo Pill = iota
Aspirin
Ibuprofen
Paracetamol
Acetaminophen = Paracetamol
)
func main() {
fmt.Printf("For headaches, take %v\n", Ibuprofen)
}
go generate
and run the result:
$ go generate
$ go run .
For headaches, take Ibuprofen
Commit and push the results:
$ git add -A
$ git commit -q -am 'Initial commit'
$ git push -q origin
@tooolbox I think go.mod handles that?