| 🛟 Updated. 28d5985 k33g 17h ago | 1 | package lsp |
| 2 | |
| 3 | import ( |
| 4 | "net/url" |
| 5 | "path/filepath" |
| 6 | "strings" |
| 7 | ) |
| 8 | |
| 9 | // PathToURI turns a file path into the file:// URI the protocol names |
| 10 | // documents by. |
| 11 | // |
| 12 | // The path is made absolute first, since a language server has no idea what |
| 13 | // the editor's working directory is. |
| 14 | // |
| 15 | // lsp.PathToURI("main.go") // file:///home/you/project/main.go |
| 16 | func PathToURI(path string) string { |
| 17 | absolute, err := filepath.Abs(path) |
| 18 | if err != nil { |
| 19 | absolute = path |
| 20 | } |
| 21 | absolute = filepath.ToSlash(absolute) |
| 22 | |
| 23 | if !strings.HasPrefix(absolute, "/") { |
| 24 | // A Windows path such as C:/x becomes /C:/x, which is what the URI |
| 25 | // form of a drive letter looks like. |
| 26 | absolute = "/" + absolute |
| 27 | } |
| 28 | |
| 29 | uri := url.URL{Scheme: "file", Path: absolute} |
| 30 | return uri.String() |
| 31 | } |
| 32 | |
| 33 | // URIToPath turns a file:// URI back into a path. Anything that is not a file |
| 34 | // URI comes back unchanged, since there is nothing better to do with it. |
| 35 | func URIToPath(uri string) string { |
| 36 | parsed, err := url.Parse(uri) |
| 37 | if err != nil || parsed.Scheme != "file" { |
| 38 | return uri |
| 39 | } |
| 40 | |
| 41 | path := parsed.Path |
| 42 | // Undo the leading slash added in front of a Windows drive letter. |
| 43 | if len(path) > 2 && path[0] == '/' && path[2] == ':' { |
| 44 | path = path[1:] |
| 45 | } |
| 46 | return filepath.FromSlash(path) |
| 47 | } |