-
-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathuri.go
99 lines (81 loc) · 2.25 KB
/
uri.go
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package lsp
import (
"encoding/json"
"net/url"
"path/filepath"
"regexp"
"github.com/arduino/go-paths-helper"
"github.com/pkg/errors"
)
type DocumentURI struct {
url url.URL
}
// NilURI is the empty DocumentURI
var NilURI = DocumentURI{}
var expDriveID = regexp.MustCompile("^/[a-zA-Z]:")
// AsPath convert the DocumentURI to a paths.Path
func (uri DocumentURI) AsPath() *paths.Path {
return paths.New(uri.Unbox())
}
// Unbox convert the DocumentURI to a file path string
func (uri DocumentURI) Unbox() string {
path := uri.url.Path
if expDriveID.MatchString(path) {
return path[1:]
}
return path
}
// Canonical returns the canonical path to the file pointed by the URI
func (uri DocumentURI) Canonical() string {
return uri.AsPath().Canonical().String()
}
func (uri DocumentURI) String() string {
return uri.url.String()
}
// Ext returns the extension of the file pointed by the URI
func (uri DocumentURI) Ext() string {
return filepath.Ext(uri.Unbox())
}
// NewDocumentURIFromPath create a DocumentURI from the given Path object
func NewDocumentURIFromPath(path *paths.Path) DocumentURI {
return NewDocumentURI(path.String())
}
var toSlash = filepath.ToSlash
// NewDocumentURI create a DocumentURI from the given string path
func NewDocumentURI(path string) DocumentURI {
// tranform path into URI
path = toSlash(path)
if len(path) == 0 || path[0] != '/' {
path = "/" + path
}
uri, err := NewDocumentURIFromURL("file://" + path)
if err != nil {
panic(err)
}
return uri
}
// NewDocumentURIFromURL converts an URL into a DocumentURI
func NewDocumentURIFromURL(inURL string) (DocumentURI, error) {
uri, err := url.Parse(inURL)
if err != nil {
return NilURI, err
}
return DocumentURI{url: *uri}, nil
}
// UnmarshalJSON implements json.Unmarshaller interface
func (uri *DocumentURI) UnmarshalJSON(data []byte) error {
var s string
if err := json.Unmarshal(data, &s); err != nil {
return errors.WithMessage(err, "expoected JSON string for DocumentURI")
}
newDocURI, err := NewDocumentURIFromURL(s)
if err != nil {
return errors.WithMessage(err, "parsing DocumentURI")
}
*uri = newDocURI
return nil
}
// MarshalJSON implements json.Marshaller interface
func (uri DocumentURI) MarshalJSON() ([]byte, error) {
return json.Marshal(uri.url.String())
}