2018-11-02 14:15:31 -06:00
|
|
|
// Copyright 2018 The Go Authors. All rights reserved.
|
|
|
|
// Use of this source code is governed by a BSD-style
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
|
|
|
package source
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
2018-11-05 15:54:12 -07:00
|
|
|
"net/url"
|
2018-11-02 14:15:31 -06:00
|
|
|
"path/filepath"
|
2018-11-14 18:02:22 -07:00
|
|
|
"runtime"
|
2018-11-02 14:15:31 -06:00
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
|
|
|
const fileSchemePrefix = "file://"
|
|
|
|
|
2018-11-05 15:54:12 -07:00
|
|
|
// URI represents the full uri for a file.
|
|
|
|
type URI string
|
|
|
|
|
|
|
|
// Filename gets the file path for the URI.
|
2018-11-02 14:15:31 -06:00
|
|
|
// It will return an error if the uri is not valid, or if the URI was not
|
|
|
|
// a file URI
|
2018-11-05 15:54:12 -07:00
|
|
|
func (uri URI) Filename() (string, error) {
|
2018-11-02 14:15:31 -06:00
|
|
|
s := string(uri)
|
|
|
|
if !strings.HasPrefix(s, fileSchemePrefix) {
|
|
|
|
return "", fmt.Errorf("only file URI's are supported, got %v", uri)
|
|
|
|
}
|
2018-11-05 15:54:12 -07:00
|
|
|
s = s[len(fileSchemePrefix):]
|
|
|
|
s, err := url.PathUnescape(s)
|
|
|
|
if err != nil {
|
|
|
|
return s, err
|
|
|
|
}
|
|
|
|
s = filepath.FromSlash(s)
|
|
|
|
return s, nil
|
2018-11-02 14:15:31 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
// ToURI returns a protocol URI for the supplied path.
|
|
|
|
// It will always have the file scheme.
|
2018-11-05 15:54:12 -07:00
|
|
|
func ToURI(path string) URI {
|
2018-11-14 18:02:22 -07:00
|
|
|
const prefix = "$GOROOT"
|
|
|
|
if strings.EqualFold(prefix, path[:len(prefix)]) {
|
|
|
|
suffix := path[len(prefix):]
|
|
|
|
//TODO: we need a better way to get the GOROOT that uses the packages api
|
|
|
|
path = runtime.GOROOT() + suffix
|
|
|
|
}
|
2018-11-05 15:54:12 -07:00
|
|
|
return URI(fileSchemePrefix + filepath.ToSlash(path))
|
2018-11-02 14:15:31 -06:00
|
|
|
}
|