@@ -8,11 +8,13 @@ import (
8
8
"bytes"
9
9
"context"
10
10
"fmt"
11
+ "io"
11
12
"strings"
12
13
13
14
"slices"
14
15
15
16
"golang.org/x/tools/gopls/internal/cache"
17
+ "golang.org/x/tools/gopls/internal/protocol"
16
18
"golang.org/x/tools/gopls/internal/util/immutable"
17
19
"golang.org/x/tools/internal/mcp"
18
20
)
@@ -60,15 +62,11 @@ func (h *handler) workspaceHandler(ctx context.Context, _ *mcp.ServerSession, _
60
62
61
63
case cache .GoModView :
62
64
fmt .Fprintf (& summary , "The `%s` directory uses Go modules, with the following main modules:\n " , dir )
63
- for _ , m := range v .ModFiles () {
64
- fmt .Fprintf (& summary , "\t %s\n " , m .Path ())
65
- }
65
+ summarizeModFiles (ctx , & summary , snapshot )
66
66
67
67
case cache .GoWorkView :
68
68
fmt .Fprintf (& summary , "The `%s` directory is in the go workspace defined by `%s`, with the following main modules:\n " , dir , v .GoWork ().Path ())
69
- for _ , m := range v .ModFiles () {
70
- fmt .Fprintf (& summary , "\t %s\n " , m .Path ())
71
- }
69
+ summarizeModFiles (ctx , & summary , snapshot )
72
70
73
71
case cache .AdHocView :
74
72
fmt .Fprintf (& summary , "The `%s` directory is an ad-hoc Go package, not in a Go module.\n " , dir )
@@ -85,6 +83,33 @@ func (h *handler) workspaceHandler(ctx context.Context, _ *mcp.ServerSession, _
85
83
return textResult (summary .String ()), nil
86
84
}
87
85
86
+ func summarizeModFiles (ctx context.Context , w io.Writer , snapshot * cache.Snapshot ) {
87
+ v := snapshot .View ()
88
+ for _ , m := range v .ModFiles () {
89
+ if modPath , err := modulePath (ctx , snapshot , m ); err != nil {
90
+ // Fall back on just the go.mod file.
91
+ fmt .Fprintf (w , "\t %s\n " , m .Path ())
92
+ } else {
93
+ fmt .Fprintf (w , "\t %s (module %s)\n " , m .Path (), modPath )
94
+ }
95
+ }
96
+ }
97
+
98
+ func modulePath (ctx context.Context , snapshot * cache.Snapshot , uri protocol.DocumentURI ) (string , error ) {
99
+ fh , err := snapshot .ReadFile (ctx , uri )
100
+ if err != nil {
101
+ return "" , fmt .Errorf ("Reading %s: %v" , uri , err )
102
+ }
103
+ pmf , err := snapshot .ParseMod (ctx , fh )
104
+ if err != nil {
105
+ return "" , fmt .Errorf ("parsing modfile: %v" , err )
106
+ }
107
+ if pmf .File == nil || pmf .File .Module == nil {
108
+ return "" , fmt .Errorf ("malformed modfile" )
109
+ }
110
+ return pmf .File .Module .Mod .Path , nil
111
+ }
112
+
88
113
func packageSummaries (snapshot * cache.Snapshot , pkgs immutable.Map [cache.PackageID , cache.PackagePath ]) []string {
89
114
var summaries []string
90
115
for id := range pkgs .All () {
0 commit comments