alist/pkg/utils/path.go

63 lines
1.2 KiB
Go
Raw Normal View History

2022-06-09 23:05:27 +08:00
package utils
2022-06-23 17:04:37 +08:00
import (
2022-08-11 20:32:17 +08:00
"net/url"
2022-06-28 18:00:11 +08:00
stdpath "path"
2022-06-23 17:04:37 +08:00
"path/filepath"
"runtime"
2022-06-23 17:04:37 +08:00
"strings"
)
2022-06-09 23:05:27 +08:00
2022-06-23 17:04:37 +08:00
// StandardizePath convert path like '/' '/root' '/a/b'
func StandardizePath(path string) string {
2022-06-09 23:05:27 +08:00
path = strings.TrimSuffix(path, "/")
2022-06-27 20:56:17 +08:00
// abs path
if filepath.IsAbs(path) && runtime.GOOS == "windows" {
2022-06-23 17:04:37 +08:00
return path
}
// relative path with prefix '..'
2022-06-27 20:37:05 +08:00
if strings.HasPrefix(path, ".") {
2022-06-23 17:04:37 +08:00
return path
}
2022-06-09 23:05:27 +08:00
if !strings.HasPrefix(path, "/") {
path = "/" + path
}
return path
}
2022-06-11 14:43:03 +08:00
2022-06-13 14:53:44 +08:00
// PathEqual judge path is equal
2022-06-11 14:43:03 +08:00
func PathEqual(path1, path2 string) bool {
2022-06-23 17:04:37 +08:00
return StandardizePath(path1) == StandardizePath(path2)
2022-06-11 14:43:03 +08:00
}
2022-06-28 18:00:11 +08:00
func Ext(path string) string {
ext := stdpath.Ext(path)
if strings.HasPrefix(ext, ".") {
return ext[1:]
}
return ext
}
2022-08-11 20:32:17 +08:00
func EncodePath(path string, all ...bool) string {
seg := strings.Split(path, "/")
toReplace := []struct {
Src string
Dst string
}{
{Src: "%", Dst: "%25"},
{"%", "%25"},
{"?", "%3F"},
{"#", "%23"},
}
for i := range seg {
if len(all) > 0 && all[0] {
seg[i] = url.PathEscape(seg[i])
} else {
for j := range toReplace {
seg[i] = strings.ReplaceAll(seg[i], toReplace[j].Src, toReplace[j].Dst)
}
}
}
return strings.Join(seg, "/")
}