From 27f88d9b7a2f740ca09706d3579bfed0afe4c2a9 Mon Sep 17 00:00:00 2001 From: Alan Donovan Date: Wed, 5 Oct 2016 14:15:28 -0400 Subject: [PATCH] cmd/guru: if query file is not beneath GOPATH, treat it as a package This allows type-based guru queries to work on arbitrary files at the root or even outside of a GOPATH workspace (as "go run foo.go" does). Fixes golang/go#15797 Change-Id: I2be28f7259448e6398aae84d6ae7e71d8649967a Reviewed-on: https://go-review.googlesource.com/30451 Reviewed-by: Robert Griesemer --- cmd/guru/guru.go | 53 +++++++++++++++++++++++++----------------------- 1 file changed, 28 insertions(+), 25 deletions(-) diff --git a/cmd/guru/guru.go b/cmd/guru/guru.go index 0cc91573..9e631130 100644 --- a/cmd/guru/guru.go +++ b/cmd/guru/guru.go @@ -173,32 +173,35 @@ func importQueryPackage(pos string, conf *loader.Config) (string, error) { _, importPath, err := guessImportPath(filename, conf.Build) if err != nil { - return "", err // can't find GOPATH dir - } + // Can't find GOPATH dir. + // Treat the query file as its own package. + importPath = "command-line-arguments" + conf.CreateFromFilenames(importPath, filename) + } else { + // Check that it's possible to load the queried package. + // (e.g. guru tests contain different 'package' decls in same dir.) + // Keep consistent with logic in loader/util.go! + cfg2 := *conf.Build + cfg2.CgoEnabled = false + bp, err := cfg2.Import(importPath, "", 0) + if err != nil { + return "", err // no files for package + } - // Check that it's possible to load the queried package. - // (e.g. guru tests contain different 'package' decls in same dir.) - // Keep consistent with logic in loader/util.go! - cfg2 := *conf.Build - cfg2.CgoEnabled = false - bp, err := cfg2.Import(importPath, "", 0) - if err != nil { - return "", err // no files for package - } - - switch pkgContainsFile(bp, filename) { - case 'T': - conf.ImportWithTests(importPath) - case 'X': - conf.ImportWithTests(importPath) - importPath += "_test" // for TypeCheckFuncBodies - case 'G': - conf.Import(importPath) - default: - // This happens for ad-hoc packages like - // $GOROOT/src/net/http/triv.go. - return "", fmt.Errorf("package %q doesn't contain file %s", - importPath, filename) + switch pkgContainsFile(bp, filename) { + case 'T': + conf.ImportWithTests(importPath) + case 'X': + conf.ImportWithTests(importPath) + importPath += "_test" // for TypeCheckFuncBodies + case 'G': + conf.Import(importPath) + default: + // This happens for ad-hoc packages like + // $GOROOT/src/net/http/triv.go. + return "", fmt.Errorf("package %q doesn't contain file %s", + importPath, filename) + } } conf.TypeCheckFuncBodies = func(p string) bool { return p == importPath }