Debian Codegraph @

gopls/internal/protocol/uri.go

raw symbols SCIP
1 // Copyright 2023 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.
4
5 package protocol
6
7 // This file declares URI, DocumentURI, and its methods.
8 //
9 // For the LSP definition of these types, see
10 // https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#uri
11
12 import (
13 "fmt"
14 "net/url"
15 "path/filepath"
16 "strings"
17 "unicode"
18
19 "golang.org/x/tools/gopls/internal/util/pathutil"
20 )
21
22 // A DocumentURI is the URI of a client editor document.
23 //
24 // According to the LSP specification:
25 //
26 // Care should be taken to handle encoding in URIs. For
27 // example, some clients (such as VS Code) may encode colons
28 // in drive letters while others do not. The URIs below are
29 // both valid, but clients and servers should be consistent
30 // with the form they use themselves to ensure the other party
31 // doesn’t interpret them as distinct URIs. Clients and
32 // servers should not assume that each other are encoding the
33 // same way (for example a client encoding colons in drive
34 // letters cannot assume server responses will have encoded
35 // colons). The same applies to casing of drive letters - one
36 // party should not assume the other party will return paths
37 // with drive letters cased the same as it.
38 //
39 // file:///c:/project/readme.md
40 // file:///C%3A/project/readme.md
41 //
42 // This is done during JSON unmarshalling;
43 // see [DocumentURI.UnmarshalText] for details.
44 type DocumentURI string
45
46 // A URI is an arbitrary URL (e.g. https), not necessarily a file.
47 type URI = string
48
49 // UnmarshalText implements decoding of DocumentURI values.
50 //
51 // In particular, it implements a systematic correction of various odd
52 // features of the definition of DocumentURI in the LSP spec that
53 // appear to be workarounds for bugs in VS Code. For example, it may
54 // URI-encode the URI itself, so that colon becomes %3A, and it may
55 // send file://foo.go URIs that have two slashes (not three) and no
56 // hostname.
57 //
58 // We use UnmarshalText, not UnmarshalJSON, because it is called even
59 // for non-addressable values such as keys and values of map[K]V,
60 // where there is no pointer of type *K or *V on which to call
61 // UnmarshalJSON. (See Go issue #28189 for more detail.)
62 //
63 // Non-empty DocumentURIs are valid "file"-scheme URIs.
64 // The empty DocumentURI is valid.
65 func (uri *DocumentURI) UnmarshalText(data []byte) (err error) {
66 *uri, err = ParseDocumentURI(string(data))
67 return
68 }
69
70 // Clean returns the cleaned uri by triggering filepath.Clean underlying.
71 func (uri DocumentURI) Clean() DocumentURI {
72 return URIFromPath(filepath.Clean(uri.Path()))
73 }
74
75 // Path returns the file path for the given URI.
76 //
77 // DocumentURI("").Path() returns the empty string.
78 //
79 // Path panics if called on a URI that is not a valid filename.
80 func (uri DocumentURI) Path() string {
81 filename, err := filename(uri)
82 if err != nil {
83 // e.g. ParseRequestURI failed.
84 //
85 // This can only affect DocumentURIs created by
86 // direct string manipulation; all DocumentURIs
87 // received from the client pass through
88 // ParseRequestURI, which ensures validity.
89 panic(err)
90 }
91 return filepath.FromSlash(filename)
92 }
93
94 // Base returns the base name of the file path of the given URI.
95 func (uri DocumentURI) Base() string {
96 return filepath.Base(uri.Path())
97 }
98
99 // Dir returns the URI for the directory containing the receiver.
100 func (uri DocumentURI) Dir() DocumentURI {
101 // This function could be more efficiently implemented by avoiding any call
102 // to Path(), but at least consolidates URI manipulation.
103 return URIFromPath(uri.DirPath())
104 }
105
106 // DirPath returns the file path to the directory containing this URI, which
107 // must be a file URI.
108 func (uri DocumentURI) DirPath() string {
109 return filepath.Dir(uri.Path())
110 }
111
112 // Encloses reports whether uri's path, considered as a sequence of segments,
113 // is a prefix of file's path.
114 func (uri DocumentURI) Encloses(file DocumentURI) bool {
115 return pathutil.InDir(uri.Path(), file.Path())
116 }
117
118 // Location returns the Location for the specified range of this URI's file.
119 func (uri DocumentURI) Location(rng Range) Location {
120 return Location{URI: uri, Range: rng}
121 }
122
123 func filename(uri DocumentURI) (string, error) {
124 if uri == "" {
125 return "", nil
126 }
127
128 // This conservative check for the common case
129 // of a simple non-empty absolute POSIX filename
130 // avoids the allocation of a net.URL.
131 if strings.HasPrefix(string(uri), "file:///") {
132 rest := string(uri)[len("file://"):] // leave one slash
133 for i := 0; i < len(rest); i++ {
134 b := rest[i]
135 // Reject these cases:
136 if b < ' ' || b == 0x7f || // control character
137 b == '%' || b == '+' || // URI escape
138 b == ':' || // Windows drive letter
139 b == '&' || b == '?' { // authority or query
140 goto slow
141 }
142 // We do not reject '@' as it cannot be part of the
143 // authority (e.g. user:[email protected]) in a
144 // "file:///" URL, and '@' commonly appears in file
145 // paths such as GOMODCACHE/module@version/...
146 }
147 return rest, nil
148 }
149 slow:
150
151 u, err := url.ParseRequestURI(string(uri))
152 if err != nil {
153 return "", err
154 }
155 if u.Scheme != fileScheme {
156 return "", fmt.Errorf("only file URIs are supported, got %q from %q", u.Scheme, uri)
157 }
158 // If the URI is a Windows URI, we trim the leading "/" and uppercase
159 // the drive letter, which will never be case sensitive.
160 if isWindowsDriveURIPath(u.Path) {
161 u.Path = strings.ToUpper(string(u.Path[1])) + u.Path[2:]
162 }
163
164 return u.Path, nil
165 }
166
167 // ParseDocumentURI interprets a string as a DocumentURI, applying VS
168 // Code workarounds; see [DocumentURI.UnmarshalText] for details.
169 // If "s" is a file name, use [URIFromPath] instead.
170 func ParseDocumentURI(s string) (DocumentURI, error) {
171 if s == "" {
172 return "", nil
173 }
174
175 if !strings.HasPrefix(s, "file://") {
176 return "", fmt.Errorf("DocumentURI scheme is not 'file': %s", s)
177 }
178
179 // VS Code sends URLs with only two slashes,
180 // which are invalid. golang/go#39789.
181 if !strings.HasPrefix(s, "file:///") {
182 s = "file:///" + s[len("file://"):]
183 }
184
185 // Even though the input is a URI, it may not be in canonical form. VS Code
186 // in particular over-escapes :, @, etc. Unescape and re-encode to canonicalize.
187 path, err := url.PathUnescape(s[len("file://"):])
188 if err != nil {
189 return "", err
190 }
191
192 // File URIs from Windows may have lowercase drive letters.
193 // Since drive letters are guaranteed to be case insensitive,
194 // we change them to uppercase to remain consistent.
195 // For example, file:///c:/x/y/z becomes file:///C:/x/y/z.
196 if isWindowsDriveURIPath(path) {
197 path = path[:1] + strings.ToUpper(string(path[1])) + path[2:]
198 }
199 u := url.URL{Scheme: fileScheme, Path: path}
200 return DocumentURI(u.String()), nil
201 }
202
203 // URIFromPath returns DocumentURI for the supplied file path.
204 // Given "", it returns "".
205 func URIFromPath(path string) DocumentURI {
206 if path == "" {
207 return ""
208 }
209 if !IsWindowsDrivePath(path) {
210 if abs, err := filepath.Abs(path); err == nil {
211 path = abs
212 }
213 }
214 // Check the file path again, in case it became absolute.
215 if IsWindowsDrivePath(path) {
216 path = "/" + strings.ToUpper(string(path[0])) + path[1:]
217 }
218 path = filepath.ToSlash(path)
219 u := url.URL{
220 Scheme: fileScheme,
221 Path: path,
222 }
223 return DocumentURI(u.String())
224 }
225
226 const fileScheme = "file"
227
228 // IsWindowsDrivePath returns true if the file path is of the form used by
229 // Windows. We check if the path begins with a drive letter, followed by a ":".
230 // For example: C:/x/y/z.
231 func IsWindowsDrivePath(path string) bool {
232 if len(path) < 3 {
233 return false
234 }
235 return unicode.IsLetter(rune(path[0])) && path[1] == ':'
236 }
237
238 // isWindowsDriveURIPath returns true if the file URI is of the format used by
239 // Windows URIs. The url.Parse package does not specially handle Windows paths
240 // (see golang/go#6027), so we check if the URI path has a drive prefix (e.g. "/C:").
241 func isWindowsDriveURIPath(uri string) bool {
242 if len(uri) < 4 {
243 return false
244 }
245 return uri[0] == '/' && unicode.IsLetter(rune(uri[1])) && uri[2] == ':'
246 }