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) }