| 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 | ) |
| 18 | |
| 19 | // A DocumentURI is the URI of a client editor document. |
| 20 | // |
| 21 | // According to the LSP specification: |
| 22 | // |
| 23 | // Care should be taken to handle encoding in URIs. For |
| 24 | // example, some clients (such as VS Code) may encode colons |
| 25 | // in drive letters while others do not. The URIs below are |
| 26 | // both valid, but clients and servers should be consistent |
| 27 | // with the form they use themselves to ensure the other party |
| 28 | // doesn’t interpret them as distinct URIs. Clients and |
| 29 | // servers should not assume that each other are encoding the |
| 30 | // same way (for example a client encoding colons in drive |
| 31 | // letters cannot assume server responses will have encoded |
| 32 | // colons). The same applies to casing of drive letters - one |
| 33 | // party should not assume the other party will return paths |
| 34 | // with drive letters cased the same as it. |
| 35 | // |
| 36 | // file:///c:/project/readme.md |
| 37 | // file:///C%3A/project/readme.md |
| 38 | // |
| 39 | // This is done during JSON unmarshalling; |
| 40 | // see [DocumentURI.UnmarshalText] for details. |
| 41 | type DocumentURI string |
| 42 | |
| 43 | // A URI is an arbitrary URL (e.g. https), not necessarily a file. |
| 44 | type URI = string |
| 45 | |
| 46 | // UnmarshalText implements decoding of DocumentUri values. |
| 47 | // |
| 48 | // In particular, it implements a systematic correction of various odd |
| 49 | // features of the definition of DocumentUri in the LSP spec that |
| 50 | // appear to be workarounds for bugs in VS Code. For example, it may |
| 51 | // URI-encode the URI itself, so that colon becomes %3A, and it may |
| 52 | // send file://foo.go URIs that have two slashes (not three) and no |
| 53 | // hostname. |
| 54 | // |
| 55 | // We use UnmarshalText, not UnmarshalJSON, because it is called even |
| 56 | // for non-addressable values such as keys and values of map[K]V, |
| 57 | // where there is no pointer of type *K or *V on which to call |
| 58 | // UnmarshalJSON. (See Go issue #28189 for more detail.) |
| 59 | // |
| 60 | // Non-empty DocumentUris are valid "file"-scheme URIs. |
| 61 | // The empty DocumentUri is valid. |
| 62 | func (uri *DocumentURI) UnmarshalText(data []byte) (err error) { |
| 63 | *uri, err = ParseDocumentURI(string(data)) |
| 64 | return err |
| 65 | } |
| 66 | |
| 67 | // Path returns the file path for the given URI. |
| 68 | // |
| 69 | // DocumentUri("").Path() returns the empty string. |
| 70 | // |
| 71 | // Path panics if called on a URI that is not a valid filename. |
| 72 | func (uri DocumentURI) Path() (string, error) { |
| 73 | filename, err := filename(uri) |
| 74 | if err != nil { |
| 75 | // e.g. ParseRequestURI failed. |
| 76 | // |
| 77 | // This can only affect DocumentUris created by |
| 78 | // direct string manipulation; all DocumentUris |
| 79 | // received from the client pass through |
| 80 | // ParseRequestURI, which ensures validity. |
| 81 | return "", fmt.Errorf("invalid URI %q: %w", uri, err) |
| 82 | } |
| 83 | return filepath.FromSlash(filename), nil |
| 84 | } |
| 85 | |
| 86 | func filename(uri DocumentURI) (string, error) { |
| 87 | if uri == "" { |
| 88 | return "", nil |
| 89 | } |
| 90 | |
| 91 | // This conservative check for the common case |
| 92 | // of a simple non-empty absolute POSIX filename |
| 93 | // avoids the allocation of a net.URL. |
| 94 | if strings.HasPrefix(string(uri), "file:///") { |
| 95 | rest := string(uri)[len("file://"):] // leave one slash |
| 96 | for i := range len(rest) { |
| 97 | b := rest[i] |
| 98 | // Reject these cases: |
| 99 | if b < ' ' || b == 0x7f || // control character |
| 100 | b == '%' || b == '+' || // URI escape |
| 101 | b == ':' || // Windows drive letter |
| 102 | b == '@' || b == '&' || b == '?' { // authority or query |
| 103 | goto slow |
| 104 | } |
| 105 | } |
| 106 | return rest, nil |
| 107 | } |
| 108 | slow: |
| 109 | |
| 110 | u, err := url.ParseRequestURI(string(uri)) |
| 111 | if err != nil { |
| 112 | return "", err |
| 113 | } |
| 114 | if u.Scheme != fileScheme { |
| 115 | return "", fmt.Errorf("only file URIs are supported, got %q from %q", u.Scheme, uri) |
| 116 | } |
| 117 | // If the URI is a Windows URI, we trim the leading "/" and uppercase |
| 118 | // the drive letter, which will never be case sensitive. |
| 119 | if isWindowsDrivePath(u.Path) { |
| 120 | u.Path = strings.ToUpper(string(u.Path[1])) + u.Path[2:] |
| 121 | } |
| 122 | |
| 123 | return u.Path, nil |
| 124 | } |
| 125 | |
| 126 | // ParseDocumentURI interprets a string as a DocumentUri, applying VS |
| 127 | // Code workarounds; see [DocumentURI.UnmarshalText] for details. |
| 128 | func ParseDocumentURI(s string) (DocumentURI, error) { |
| 129 | if s == "" { |
| 130 | return "", nil |
| 131 | } |
| 132 | |
| 133 | if !strings.HasPrefix(s, "file://") { |
| 134 | return "", fmt.Errorf("DocumentUri scheme is not 'file': %s", s) |
| 135 | } |
| 136 | |
| 137 | // VS Code sends URLs with only two slashes, |
| 138 | // which are invalid. golang/go#39789. |
| 139 | if !strings.HasPrefix(s, "file:///") { |
| 140 | s = "file:///" + s[len("file://"):] |
| 141 | } |
| 142 | |
| 143 | // Even though the input is a URI, it may not be in canonical form. VS Code |
| 144 | // in particular over-escapes :, @, etc. Unescape and re-encode to canonicalize. |
| 145 | path, err := url.PathUnescape(s[len("file://"):]) |
| 146 | if err != nil { |
| 147 | return "", err |
| 148 | } |
| 149 | |
| 150 | // File URIs from Windows may have lowercase drive letters. |
| 151 | // Since drive letters are guaranteed to be case insensitive, |
| 152 | // we change them to uppercase to remain consistent. |
| 153 | // For example, file:///c:/x/y/z becomes file:///C:/x/y/z. |
| 154 | if isWindowsDrivePath(path) { |
| 155 | path = path[:1] + strings.ToUpper(string(path[1])) + path[2:] |
| 156 | } |
| 157 | u := url.URL{Scheme: fileScheme, Path: path} |
| 158 | return DocumentURI(u.String()), nil |
| 159 | } |
| 160 | |
| 161 | // URIFromPath returns DocumentUri for the supplied file path. |
| 162 | // Given "", it returns "". |
| 163 | func URIFromPath(path string) DocumentURI { |
| 164 | if path == "" { |
| 165 | return "" |
| 166 | } |
| 167 | if abs, err := filepath.Abs(path); err == nil { |
| 168 | path = abs |
| 169 | } |
| 170 | if isWindowsDrivePath(path) { |
| 171 | path = "/" + strings.ToUpper(string(path[0])) + path[1:] |
| 172 | } |
| 173 | path = filepath.ToSlash(path) |
| 174 | filepath.Clean(path) |
| 175 | u := url.URL{ |
| 176 | Scheme: fileScheme, |
| 177 | Path: path, |
| 178 | } |
| 179 | return DocumentURI(u.String()) |
| 180 | } |
| 181 | |
| 182 | const fileScheme = "file" |
| 183 | |
| 184 | // isWindowsDrivePath returns true if the file path is of the form used by |
| 185 | // Windows. We check if the path begins with a drive letter, followed by a ":". |
| 186 | // For example: C:/x/y/z. |
| 187 | func isWindowsDrivePath(path string) bool { |
| 188 | return filepath.VolumeName(path) != "" |
| 189 | } |