Skip to content

Commit 266276d

Browse files
findleyrdennypenta
authored andcommitted
gopls/internal/protocol: add DocumentURI.DirPath
To simplify many callsites where we called filepath.Dir on uri.Path(), introduce the DocumentURI.DirPath helper method. This clarified many call sites, and could make it easier to optimize URI manipulation in the future. Change-Id: Icc64155b6bba631f9df5da5a05e3126c7cb7954b Reviewed-on: https://go-review.googlesource.com/c/tools/+/626716 LUCI-TryBot-Result: Go LUCI <[email protected]> Reviewed-by: Alan Donovan <[email protected]>
1 parent 02f8356 commit 266276d

22 files changed

+51
-77
lines changed

gopls/internal/cache/check.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1782,7 +1782,7 @@ func depsErrors(ctx context.Context, snapshot *Snapshot, mp *metadata.Package) (
17821782
}
17831783
}
17841784

1785-
modFile, err := nearestModFile(ctx, mp.CompiledGoFiles[0], snapshot)
1785+
modFile, err := findRootPattern(ctx, mp.CompiledGoFiles[0].Dir(), "go.mod", snapshot)
17861786
if err != nil {
17871787
return nil, err
17881788
}

gopls/internal/cache/filemap.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,7 @@ func (m *fileMap) set(key protocol.DocumentURI, fh file.Handle) {
104104

105105
// addDirs adds all directories containing u to the dirs set.
106106
func (m *fileMap) addDirs(u protocol.DocumentURI) {
107-
dir := filepath.Dir(u.Path())
107+
dir := u.DirPath()
108108
for dir != "" && !m.dirs.Contains(dir) {
109109
m.dirs.Add(dir)
110110
dir = filepath.Dir(dir)

gopls/internal/cache/mod.go

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@ import (
88
"context"
99
"errors"
1010
"fmt"
11-
"path/filepath"
1211
"regexp"
1312
"strings"
1413

@@ -251,7 +250,7 @@ func modWhyImpl(ctx context.Context, snapshot *Snapshot, fh file.Handle) (map[st
251250
for _, req := range pm.File.Require {
252251
args = append(args, req.Mod.Path)
253252
}
254-
inv, cleanupInvocation, err := snapshot.GoCommandInvocation(false, filepath.Dir(fh.URI().Path()), "mod", args)
253+
inv, cleanupInvocation, err := snapshot.GoCommandInvocation(false, fh.URI().DirPath(), "mod", args)
255254
if err != nil {
256255
return nil, err
257256
}

gopls/internal/cache/mod_tidy.go

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -107,13 +107,8 @@ func modTidyImpl(ctx context.Context, snapshot *Snapshot, pm *ParsedModule) (*Ti
107107
}
108108
defer cleanup()
109109

110-
inv, cleanupInvocation, err := snapshot.GoCommandInvocation(
111-
false,
112-
pm.URI.Dir().Path(),
113-
"mod",
114-
[]string{"tidy", "-modfile=" + filepath.Join(tempDir, "go.mod")},
115-
"GOWORK=off",
116-
)
110+
args := []string{"tidy", "-modfile=" + filepath.Join(tempDir, "go.mod")}
111+
inv, cleanupInvocation, err := snapshot.GoCommandInvocation(false, pm.URI.DirPath(), "mod", args, "GOWORK=off")
117112
if err != nil {
118113
return nil, err
119114
}

gopls/internal/cache/session.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -191,7 +191,7 @@ func (s *Session) createView(ctx context.Context, def *viewDefinition) (*View, *
191191
} else {
192192
dirs = append(dirs, def.folder.Env.GOMODCACHE)
193193
for m := range def.workspaceModFiles {
194-
dirs = append(dirs, filepath.Dir(m.Path()))
194+
dirs = append(dirs, m.DirPath())
195195
}
196196
}
197197
ignoreFilter = newIgnoreFilter(dirs)

gopls/internal/cache/snapshot.go

Lines changed: 9 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -375,7 +375,7 @@ func (s *Snapshot) RunGoModUpdateCommands(ctx context.Context, modURI protocol.D
375375
// TODO(rfindley): we must use ModFlag and ModFile here (rather than simply
376376
// setting Args), because without knowing the verb, we can't know whether
377377
// ModFlag is appropriate. Refactor so that args can be set by the caller.
378-
inv, cleanupInvocation, err := s.GoCommandInvocation(true, modURI.Dir().Path(), "", nil, "GOWORK=off")
378+
inv, cleanupInvocation, err := s.GoCommandInvocation(true, modURI.DirPath(), "", nil, "GOWORK=off")
379379
if err != nil {
380380
return nil, nil, err
381381
}
@@ -807,7 +807,7 @@ func (s *Snapshot) fileWatchingGlobPatterns() map[protocol.RelativePattern]unit
807807
var dirs []string
808808
if s.view.typ.usesModules() {
809809
if s.view.typ == GoWorkView {
810-
workVendorDir := filepath.Join(s.view.gowork.Dir().Path(), "vendor")
810+
workVendorDir := filepath.Join(s.view.gowork.DirPath(), "vendor")
811811
workVendorURI := protocol.URIFromPath(workVendorDir)
812812
patterns[protocol.RelativePattern{BaseURI: workVendorURI, Pattern: watchGoFiles}] = unit{}
813813
}
@@ -818,8 +818,7 @@ func (s *Snapshot) fileWatchingGlobPatterns() map[protocol.RelativePattern]unit
818818
// The assumption is that the user is not actively editing non-workspace
819819
// modules, so don't pay the price of file watching.
820820
for modFile := range s.view.workspaceModFiles {
821-
dir := filepath.Dir(modFile.Path())
822-
dirs = append(dirs, dir)
821+
dirs = append(dirs, modFile.DirPath())
823822

824823
// TODO(golang/go#64724): thoroughly test these patterns, particularly on
825824
// on Windows.
@@ -1059,15 +1058,6 @@ func moduleForURI(modFiles map[protocol.DocumentURI]struct{}, uri protocol.Docum
10591058
return match
10601059
}
10611060

1062-
// nearestModFile finds the nearest go.mod file contained in the directory
1063-
// containing uri, or a parent of that directory.
1064-
//
1065-
// The given uri must be a file, not a directory.
1066-
func nearestModFile(ctx context.Context, uri protocol.DocumentURI, fs file.Source) (protocol.DocumentURI, error) {
1067-
dir := filepath.Dir(uri.Path())
1068-
return findRootPattern(ctx, protocol.URIFromPath(dir), "go.mod", fs)
1069-
}
1070-
10711061
// Metadata returns the metadata for the specified package,
10721062
// or nil if it was not found.
10731063
func (s *Snapshot) Metadata(id PackageID) *metadata.Package {
@@ -1350,7 +1340,7 @@ searchOverlays:
13501340
)
13511341
if initialErr != nil {
13521342
msg = fmt.Sprintf("initialization failed: %v", initialErr.MainError)
1353-
} else if goMod, err := nearestModFile(ctx, fh.URI(), s); err == nil && goMod != "" {
1343+
} else if goMod, err := findRootPattern(ctx, fh.URI().Dir(), "go.mod", file.Source(s)); err == nil && goMod != "" {
13541344
// Check if the file's module should be loadable by considering both
13551345
// loaded modules and workspace modules. The former covers cases where
13561346
// the file is outside of a workspace folder. The latter covers cases
@@ -1363,7 +1353,7 @@ searchOverlays:
13631353
// prescriptive diagnostic in the case that there is no go.mod file, but
13641354
// it is harder to be precise in that case, and less important.
13651355
if !(loadedMod || workspaceMod) {
1366-
modDir := filepath.Dir(goMod.Path())
1356+
modDir := goMod.DirPath()
13671357
viewDir := s.view.folder.Dir.Path()
13681358

13691359
// When the module is underneath the view dir, we offer
@@ -1664,7 +1654,7 @@ func (s *Snapshot) clone(ctx, bgCtx context.Context, changed StateChange, done f
16641654
continue // like with go.mod files, we only reinit when things change on disk
16651655
}
16661656
dir, base := filepath.Split(uri.Path())
1667-
if base == "go.work.sum" && s.view.typ == GoWorkView && dir == filepath.Dir(s.view.gowork.Path()) {
1657+
if base == "go.work.sum" && s.view.typ == GoWorkView && dir == s.view.gowork.DirPath() {
16681658
reinit = true
16691659
}
16701660
if base == "go.sum" {
@@ -1947,7 +1937,7 @@ func deleteMostRelevantModFile(m *persistent.Map[protocol.DocumentURI, *memoize.
19471937

19481938
m.Range(func(modURI protocol.DocumentURI, _ *memoize.Promise) {
19491939
if len(modURI) > len(mostRelevant) {
1950-
if pathutil.InDir(filepath.Dir(modURI.Path()), changedFile) {
1940+
if pathutil.InDir(modURI.DirPath(), changedFile) {
19511941
mostRelevant = modURI
19521942
}
19531943
}
@@ -1999,12 +1989,12 @@ func invalidatedPackageIDs(uri protocol.DocumentURI, known map[protocol.Document
19991989
}{fi, err}
20001990
return fi, err
20011991
}
2002-
dir := filepath.Dir(uri.Path())
1992+
dir := uri.DirPath()
20031993
fi, err := getInfo(dir)
20041994
if err == nil {
20051995
// Aggregate all possibly relevant package IDs.
20061996
for knownURI, ids := range known {
2007-
knownDir := filepath.Dir(knownURI.Path())
1997+
knownDir := knownURI.DirPath()
20081998
knownFI, err := getInfo(knownDir)
20091999
if err != nil {
20102000
continue

gopls/internal/cache/view.go

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -673,11 +673,10 @@ func (s *Snapshot) initialize(ctx context.Context, firstAttempt bool) {
673673
addError(modURI, fmt.Errorf("no module path for %s", modURI))
674674
continue
675675
}
676-
moduleDir := filepath.Dir(modURI.Path())
677676
// Previously, we loaded <modulepath>/... for each module path, but that
678677
// is actually incorrect when the pattern may match packages in more than
679678
// one module. See golang/go#59458 for more details.
680-
scopes = append(scopes, moduleLoadScope{dir: moduleDir, modulePath: parsed.File.Module.Mod.Path})
679+
scopes = append(scopes, moduleLoadScope{dir: modURI.DirPath(), modulePath: parsed.File.Module.Mod.Path})
681680
}
682681
} else {
683682
scopes = append(scopes, viewLoadScope{})
@@ -826,7 +825,7 @@ func defineView(ctx context.Context, fs file.Source, folder *Folder, forFile fil
826825
}
827826
dir := folder.Dir.Path()
828827
if forFile != nil {
829-
dir = filepath.Dir(forFile.URI().Path())
828+
dir = forFile.URI().DirPath()
830829
}
831830

832831
def := new(viewDefinition)

gopls/internal/golang/addtest.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -294,7 +294,7 @@ func AddTestForFunc(ctx context.Context, snapshot *cache.Snapshot, loc protocol.
294294
}
295295

296296
testBase := strings.TrimSuffix(filepath.Base(loc.URI.Path()), ".go") + "_test.go"
297-
goTestFileURI := protocol.URIFromPath(filepath.Join(loc.URI.Dir().Path(), testBase))
297+
goTestFileURI := protocol.URIFromPath(filepath.Join(loc.URI.DirPath(), testBase))
298298

299299
testFH, err := snapshot.ReadFile(ctx, goTestFileURI)
300300
if err != nil {

gopls/internal/golang/assembly.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ import (
3030
// - cross-link jumps and block labels, like github.com/aclements/objbrowse.
3131
func AssemblyHTML(ctx context.Context, snapshot *cache.Snapshot, pkg *cache.Package, symbol string, web Web) ([]byte, error) {
3232
// Compile the package with -S, and capture its stderr stream.
33-
inv, cleanupInvocation, err := snapshot.GoCommandInvocation(false, pkg.Metadata().CompiledGoFiles[0].Dir().Path(), "build", []string{"-gcflags=-S", "."})
33+
inv, cleanupInvocation, err := snapshot.GoCommandInvocation(false, pkg.Metadata().CompiledGoFiles[0].DirPath(), "build", []string{"-gcflags=-S", "."})
3434
if err != nil {
3535
return nil, err // e.g. failed to write overlays (rare)
3636
}

gopls/internal/golang/completion/package.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -205,7 +205,7 @@ func packageSuggestions(ctx context.Context, snapshot *cache.Snapshot, fileURI p
205205
}
206206
}()
207207

208-
dirPath := filepath.Dir(fileURI.Path())
208+
dirPath := fileURI.DirPath()
209209
dirName := filepath.Base(dirPath)
210210
if !isValidDirName(dirName) {
211211
return packages, nil
@@ -227,7 +227,7 @@ func packageSuggestions(ctx context.Context, snapshot *cache.Snapshot, fileURI p
227227
// Only add packages that are previously used in the current directory.
228228
var relevantPkg bool
229229
for _, uri := range mp.CompiledGoFiles {
230-
if filepath.Dir(uri.Path()) == dirPath {
230+
if uri.DirPath() == dirPath {
231231
relevantPkg = true
232232
break
233233
}

0 commit comments

Comments
 (0)