Standard library / go/build
go/build.FindOnly
Finds package directory without reading its source files. Expected stdout: 'true 0\n'.
Formal Syntax & Structure
go syntaxgo
const FindOnly ImportMode = 1Working Example
Example Snippetgo
package main
import ( "fmt" "go/build" "os" "path/filepath")
func check(e error) { if e != nil { panic(e) }}func directory() (string, func()) { d, e := os.MkdirTemp("", "build-demo-") check(e) for n, s := range map[string]string{"base.go": "package demo\n", "only_linux.go": "package demo\n", "only_windows.go": "package demo\n", "feature.go": "//go:build feature\n\npackage demo\n"} { check(os.WriteFile(filepath.Join(d, n), []byte(s), 0600)) } return d, func() { check(os.RemoveAll(d)) }}func target() build.Context { c := build.Default c.GOOS = "linux" c.GOARCH = "amd64" c.CgoEnabled = false c.BuildTags = nil return c}
func main() { d, cleanup := directory() defer cleanup() c := target() p, e := c.ImportDir(d, build.FindOnly) check(e) fmt.Println(p.Dir == d, len(p.GoFiles))}