Skip to content

Commit f0ace13

Browse files
mateusz834gopherbot
authored andcommitted
go/packages: take into account cfg.Dir while querying relative files
Otherwise, relative file queries are resolved based on the current working directory, rather than the configured cfg.Dir, which causes the adhocPackage fallback to be used in such cases. Change-Id: Id6fee3942e8d02d54c4f442a27424ba8ba8460bc Reviewed-on: https://go-review.googlesource.com/c/tools/+/680817 Reviewed-by: Alan Donovan <[email protected]> Commit-Queue: Alan Donovan <[email protected]> Auto-Submit: Alan Donovan <[email protected]> LUCI-TryBot-Result: Go LUCI <[email protected]> Reviewed-by: Robert Findley <[email protected]>
1 parent 5099dda commit f0ace13

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

go/packages/golist.go

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -224,13 +224,22 @@ extractQueries:
224224
return response.dr, nil
225225
}
226226

227+
// abs returns an absolute representation of path, based on cfg.Dir.
228+
func (cfg *Config) abs(path string) (string, error) {
229+
if filepath.IsAbs(path) {
230+
return path, nil
231+
}
232+
// In case cfg.Dir is relative, pass it to filepath.Abs.
233+
return filepath.Abs(filepath.Join(cfg.Dir, path))
234+
}
235+
227236
func (state *golistState) runContainsQueries(response *responseDeduper, queries []string) error {
228237
for _, query := range queries {
229238
// TODO(matloob): Do only one query per directory.
230239
fdir := filepath.Dir(query)
231240
// Pass absolute path of directory to go list so that it knows to treat it as a directory,
232241
// not a package path.
233-
pattern, err := filepath.Abs(fdir)
242+
pattern, err := state.cfg.abs(fdir)
234243
if err != nil {
235244
return fmt.Errorf("could not determine absolute path of file= query path %q: %v", query, err)
236245
}

go/packages/packages_test.go

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3400,3 +3400,27 @@ func writeTree(t *testing.T, archive string) string {
34003400
}
34013401
return root
34023402
}
3403+
3404+
func TestLoadFileRelativePath(t *testing.T) {
3405+
exported := packagestest.Export(t, packagestest.Modules, []packagestest.Module{
3406+
{
3407+
Name: "fake/pkg",
3408+
Files: map[string]any{
3409+
"pkg.go": "package pkg; type A int",
3410+
},
3411+
},
3412+
})
3413+
t.Cleanup(exported.Cleanup)
3414+
3415+
exported.Config.Mode = packages.LoadSyntax
3416+
pkgs, err := packages.Load(exported.Config, "file=pkg.go")
3417+
if err != nil {
3418+
t.Fatal(err)
3419+
}
3420+
if len(pkgs) != 1 {
3421+
t.Fatalf("len(pkgs) = %v; want = 1", len(pkgs))
3422+
}
3423+
if pkgs[0].ID != "fake/pkg" {
3424+
t.Fatalf(`pkgs[0].Id = %q; want "fake/pkg"`, pkgs[0].ID)
3425+
}
3426+
}

0 commit comments

Comments
 (0)