1 // Copyright 2019 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
18 "golang.org/x/mod/modfile"
19 "golang.org/x/mod/module"
20 "golang.org/x/tools/internal/event"
21 "golang.org/x/tools/internal/gocommand"
22 "golang.org/x/tools/internal/lsp/debug/tag"
23 "golang.org/x/tools/internal/lsp/protocol"
24 "golang.org/x/tools/internal/lsp/source"
25 "golang.org/x/tools/internal/memoize"
26 "golang.org/x/tools/internal/span"
30 SyntaxError = "syntax"
31 GoCommandError = "go command"
34 type parseModHandle struct {
35 handle *memoize.Handle
38 type parseModData struct {
39 parsed *source.ParsedModule
41 // err is any error encountered while parsing the file.
45 func (mh *parseModHandle) parse(ctx context.Context, snapshot *snapshot) (*source.ParsedModule, error) {
46 v, err := mh.handle.Get(ctx, snapshot.generation, snapshot)
50 data := v.(*parseModData)
51 return data.parsed, data.err
54 func (s *snapshot) ParseMod(ctx context.Context, modFH source.FileHandle) (*source.ParsedModule, error) {
55 if handle := s.getParseModHandle(modFH.URI()); handle != nil {
56 return handle.parse(ctx, s)
58 h := s.generation.Bind(modFH.FileIdentity(), func(ctx context.Context, _ memoize.Arg) interface{} {
59 _, done := event.Start(ctx, "cache.ParseModHandle", tag.URI.Of(modFH.URI()))
62 contents, err := modFH.Read()
64 return &parseModData{err: err}
66 m := &protocol.ColumnMapper{
68 Converter: span.NewContentConverter(modFH.URI().Filename(), contents),
71 file, err := modfile.Parse(modFH.URI().Filename(), contents, nil)
73 // Attempt to convert the error to a standardized parse error.
74 var parseErrors []*source.Error
76 if parseErr := extractErrorWithPosition(ctx, err.Error(), s); parseErr != nil {
77 parseErrors = []*source.Error{parseErr}
81 parsed: &source.ParsedModule{
85 ParseErrors: parseErrors,
91 pmh := &parseModHandle{handle: h}
93 s.parseModHandles[modFH.URI()] = pmh
96 return pmh.parse(ctx, s)
99 // goSum reads the go.sum file for the go.mod file at modURI, if it exists. If
100 // it doesn't exist, it returns nil.
101 func (s *snapshot) goSum(ctx context.Context, modURI span.URI) []byte {
102 // Get the go.sum file, either from the snapshot or directly from the
103 // cache. Avoid (*snapshot).GetFile here, as we don't want to add
104 // nonexistent file handles to the snapshot if the file does not exist.
105 sumURI := span.URIFromPath(sumFilename(modURI))
106 var sumFH source.FileHandle = s.FindFile(sumURI)
109 sumFH, err = s.view.session.cache.getFile(ctx, sumURI)
114 content, err := sumFH.Read()
121 func sumFilename(modURI span.URI) string {
122 return strings.TrimSuffix(modURI.Filename(), ".mod") + ".sum"
125 // modKey is uniquely identifies cached data for `go mod why` or dependencies
128 sessionID, env, view string
129 mod source.FileIdentity
140 type modWhyHandle struct {
141 handle *memoize.Handle
144 type modWhyData struct {
145 // why keeps track of the `go mod why` results for each require statement
146 // in the go.mod file.
147 why map[string]string
152 func (mwh *modWhyHandle) why(ctx context.Context, snapshot *snapshot) (map[string]string, error) {
153 v, err := mwh.handle.Get(ctx, snapshot.generation, snapshot)
157 data := v.(*modWhyData)
158 return data.why, data.err
161 func (s *snapshot) ModWhy(ctx context.Context, fh source.FileHandle) (map[string]string, error) {
162 if fh.Kind() != source.Mod {
163 return nil, fmt.Errorf("%s is not a go.mod file", fh.URI())
165 if handle := s.getModWhyHandle(fh.URI()); handle != nil {
166 return handle.why(ctx, s)
169 sessionID: s.view.session.id,
171 mod: fh.FileIdentity(),
172 view: s.view.rootURI.Filename(),
175 h := s.generation.Bind(key, func(ctx context.Context, arg memoize.Arg) interface{} {
176 ctx, done := event.Start(ctx, "cache.ModWhyHandle", tag.URI.Of(fh.URI()))
179 snapshot := arg.(*snapshot)
181 pm, err := snapshot.ParseMod(ctx, fh)
183 return &modWhyData{err: err}
185 // No requires to explain.
186 if len(pm.File.Require) == 0 {
189 // Run `go mod why` on all the dependencies.
190 inv := &gocommand.Invocation{
192 Args: []string{"why", "-m"},
193 WorkingDir: filepath.Dir(fh.URI().Filename()),
195 for _, req := range pm.File.Require {
196 inv.Args = append(inv.Args, req.Mod.Path)
198 stdout, err := snapshot.RunGoCommandDirect(ctx, source.Normal, inv)
200 return &modWhyData{err: err}
202 whyList := strings.Split(stdout.String(), "\n\n")
203 if len(whyList) != len(pm.File.Require) {
205 err: fmt.Errorf("mismatched number of results: got %v, want %v", len(whyList), len(pm.File.Require)),
208 why := make(map[string]string, len(pm.File.Require))
209 for i, req := range pm.File.Require {
210 why[req.Mod.Path] = whyList[i]
212 return &modWhyData{why: why}
215 mwh := &modWhyHandle{handle: h}
217 s.modWhyHandles[fh.URI()] = mwh
220 return mwh.why(ctx, s)
223 type modUpgradeHandle struct {
224 handle *memoize.Handle
227 type modUpgradeData struct {
228 // upgrades maps modules to their latest versions.
229 upgrades map[string]string
234 func (muh *modUpgradeHandle) upgrades(ctx context.Context, snapshot *snapshot) (map[string]string, error) {
235 v, err := muh.handle.Get(ctx, snapshot.generation, snapshot)
239 data := v.(*modUpgradeData)
240 return data.upgrades, data.err
243 // moduleUpgrade describes a module that can be upgraded to a particular
245 type moduleUpgrade struct {
252 func (s *snapshot) ModUpgrade(ctx context.Context, fh source.FileHandle) (map[string]string, error) {
253 if fh.Kind() != source.Mod {
254 return nil, fmt.Errorf("%s is not a go.mod file", fh.URI())
256 if handle := s.getModUpgradeHandle(fh.URI()); handle != nil {
257 return handle.upgrades(ctx, s)
260 sessionID: s.view.session.id,
262 mod: fh.FileIdentity(),
263 view: s.view.rootURI.Filename(),
266 h := s.generation.Bind(key, func(ctx context.Context, arg memoize.Arg) interface{} {
267 ctx, done := event.Start(ctx, "cache.ModUpgradeHandle", tag.URI.Of(fh.URI()))
270 snapshot := arg.(*snapshot)
272 pm, err := snapshot.ParseMod(ctx, fh)
274 return &modUpgradeData{err: err}
277 // No requires to upgrade.
278 if len(pm.File.Require) == 0 {
279 return &modUpgradeData{}
281 // Run "go list -mod readonly -u -m all" to be able to see which deps can be
282 // upgraded without modifying mod file.
283 inv := &gocommand.Invocation{
285 Args: []string{"-u", "-m", "-json", "all"},
286 WorkingDir: filepath.Dir(fh.URI().Filename()),
288 if s.workspaceMode()&tempModfile == 0 || containsVendor(fh.URI()) {
289 // Use -mod=readonly if the module contains a vendor directory
290 // (see golang/go#38711).
291 inv.ModFlag = "readonly"
293 stdout, err := snapshot.RunGoCommandDirect(ctx, source.Normal|source.AllowNetwork, inv)
295 return &modUpgradeData{err: err}
297 var upgradeList []moduleUpgrade
298 dec := json.NewDecoder(stdout)
301 if err := dec.Decode(&m); err == io.EOF {
303 } else if err != nil {
304 return &modUpgradeData{err: err}
306 upgradeList = append(upgradeList, m)
308 if len(upgradeList) <= 1 {
309 return &modUpgradeData{}
311 upgrades := make(map[string]string)
312 for _, upgrade := range upgradeList[1:] {
313 if upgrade.Update.Version == "" {
316 upgrades[upgrade.Path] = upgrade.Update.Version
318 return &modUpgradeData{
322 muh := &modUpgradeHandle{handle: h}
324 s.modUpgradeHandles[fh.URI()] = muh
327 return muh.upgrades(ctx, s)
330 // containsVendor reports whether the module has a vendor folder.
331 func containsVendor(modURI span.URI) bool {
332 dir := filepath.Dir(modURI.Filename())
333 f, err := os.Stat(filepath.Join(dir, "vendor"))
340 var moduleAtVersionRe = regexp.MustCompile(`^(?P<module>.*)@(?P<version>.*)$`)
342 // extractGoCommandError tries to parse errors that come from the go command
343 // and shape them into go.mod diagnostics.
344 func (s *snapshot) extractGoCommandErrors(ctx context.Context, snapshot source.Snapshot, fh source.FileHandle, goCmdError string) []*source.Error {
345 var srcErrs []*source.Error
346 if srcErr := s.parseModError(ctx, fh, goCmdError); srcErr != nil {
347 srcErrs = append(srcErrs, srcErr)
349 // If the error message contains a position, use that. Don't pass a file
350 // handle in, as it might not be the file associated with the error.
351 if srcErr := extractErrorWithPosition(ctx, goCmdError, s); srcErr != nil {
352 srcErrs = append(srcErrs, srcErr)
353 } else if srcErr := s.matchErrorToModule(ctx, fh, goCmdError); srcErr != nil {
354 srcErrs = append(srcErrs, srcErr)
359 // matchErrorToModule attempts to match module version in error messages.
362 // example.com@v1.2.2: reading example.com/@v/v1.2.2.mod: no such file or directory
363 // go: github.com/cockroachdb/apd/v2@v2.0.72: reading github.com/cockroachdb/apd/go.mod at revision v2.0.72: unknown revision v2.0.72
364 // go: example.com@v1.2.3 requires\n\trandom.org@v1.2.3: parsing go.mod:\n\tmodule declares its path as: bob.org\n\tbut was required as: random.org
366 // We split on colons and whitespace, and attempt to match on something
367 // that matches module@version. If we're able to find a match, we try to
368 // find anything that matches it in the go.mod file.
369 func (s *snapshot) matchErrorToModule(ctx context.Context, fh source.FileHandle, goCmdError string) *source.Error {
371 fields := strings.FieldsFunc(goCmdError, func(r rune) bool {
372 return unicode.IsSpace(r) || r == ':'
374 for _, field := range fields {
375 match := moduleAtVersionRe.FindStringSubmatch(field)
379 path, version := match[1], match[2]
380 // Any module versions that come from the workspace module should not
381 // be shown to the user.
382 if source.IsWorkspaceModuleVersion(version) {
385 if err := module.Check(path, version); err != nil {
388 v.Path, v.Version = path, version
391 pm, err := s.ParseMod(ctx, fh)
395 toSourceError := func(line *modfile.Line) *source.Error {
396 rng, err := rangeFromPositions(pm.Mapper, line.Start, line.End)
400 disabledByGOPROXY := strings.Contains(goCmdError, "disabled by GOPROXY=off")
401 shouldAddDep := strings.Contains(goCmdError, "to add it")
402 if v.Path != "" && (disabledByGOPROXY || shouldAddDep) {
403 args, err := source.MarshalArgs(fh.URI(), false, []string{fmt.Sprintf("%v@%v", v.Path, v.Version)})
408 if disabledByGOPROXY {
409 msg = fmt.Sprintf("%v@%v has not been downloaded", v.Path, v.Version)
411 return &source.Error{
413 Kind: source.ListError,
416 SuggestedFixes: []source.SuggestedFix{{
417 Title: fmt.Sprintf("Download %v@%v", v.Path, v.Version),
418 Command: &protocol.Command{
419 Title: source.CommandAddDependency.Title,
420 Command: source.CommandAddDependency.ID(),
426 return &source.Error{
430 Kind: source.ListError,
433 // Check if there are any require, exclude, or replace statements that
434 // match this module version.
435 for _, req := range pm.File.Require {
439 return toSourceError(req.Syntax)
441 for _, ex := range pm.File.Exclude {
445 return toSourceError(ex.Syntax)
447 for _, rep := range pm.File.Replace {
448 if rep.New != v && rep.Old != v {
451 return toSourceError(rep.Syntax)
453 // No match for the module path was found in the go.mod file.
454 // Show the error on the module declaration, if one exists.
455 if pm.File.Module == nil {
458 return toSourceError(pm.File.Module.Syntax)
461 // errorPositionRe matches errors messages of the form <filename>:<line>:<col>,
462 // where the <col> is optional.
463 var errorPositionRe = regexp.MustCompile(`(?P<pos>.*:([\d]+)(:([\d]+))?): (?P<msg>.+)`)
465 // extractErrorWithPosition returns a structured error with position
466 // information for the given unstructured error. If a file handle is provided,
467 // the error position will be on that file. This is useful for parse errors,
468 // where we already know the file with the error.
469 func extractErrorWithPosition(ctx context.Context, goCmdError string, src source.FileSource) *source.Error {
470 matches := errorPositionRe.FindStringSubmatch(strings.TrimSpace(goCmdError))
471 if len(matches) == 0 {
475 for i, name := range errorPositionRe.SubexpNames() {
483 spn := span.Parse(pos)
484 fh, err := src.GetFile(ctx, spn.URI())
488 content, err := fh.Read()
492 m := &protocol.ColumnMapper{
494 Converter: span.NewContentConverter(spn.URI().Filename(), content),
497 rng, err := m.Range(spn)
501 category := GoCommandError
503 category = SyntaxError
505 return &source.Error{