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