summaryrefslogtreecommitdiffstats
path: root/modules/util
diff options
context:
space:
mode:
Diffstat (limited to 'modules/util')
-rw-r--r--modules/util/path.go23
-rw-r--r--modules/util/path_test.go58
2 files changed, 81 insertions, 0 deletions
diff --git a/modules/util/path.go b/modules/util/path.go
index aa3d009899..2ac8f4d80a 100644
--- a/modules/util/path.go
+++ b/modules/util/path.go
@@ -6,9 +6,12 @@ package util
import (
"errors"
+ "net/url"
"os"
"path"
"path/filepath"
+ "regexp"
+ "runtime"
"strings"
)
@@ -150,3 +153,23 @@ func StatDir(rootPath string, includeDir ...bool) ([]string, error) {
}
return statDir(rootPath, "", isIncludeDir, false, false)
}
+
+// FileURLToPath extracts the path informations from a file://... url.
+func FileURLToPath(u *url.URL) (string, error) {
+ if u.Scheme != "file" {
+ return "", errors.New("URL scheme is not 'file': " + u.String())
+ }
+
+ path := u.Path
+
+ if runtime.GOOS != "windows" {
+ return path, nil
+ }
+
+ // If it looks like there's a Windows drive letter at the beginning, strip off the leading slash.
+ re := regexp.MustCompile("/[A-Za-z]:/")
+ if re.MatchString(path) {
+ return path[1:], nil
+ }
+ return path, nil
+}
diff --git a/modules/util/path_test.go b/modules/util/path_test.go
new file mode 100644
index 0000000000..41104f79fc
--- /dev/null
+++ b/modules/util/path_test.go
@@ -0,0 +1,58 @@
+// Copyright 2021 The Gitea Authors. All rights reserved.
+// Use of this source code is governed by a MIT-style
+// license that can be found in the LICENSE file.
+
+package util
+
+import (
+ "net/url"
+ "runtime"
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+)
+
+func TestFileURLToPath(t *testing.T) {
+ var cases = []struct {
+ url string
+ expected string
+ haserror bool
+ windows bool
+ }{
+ // case 0
+ {
+ url: "",
+ haserror: true,
+ },
+ // case 1
+ {
+ url: "http://test.io",
+ haserror: true,
+ },
+ // case 2
+ {
+ url: "file:///path",
+ expected: "/path",
+ },
+ // case 3
+ {
+ url: "file:///C:/path",
+ expected: "C:/path",
+ windows: true,
+ },
+ }
+
+ for n, c := range cases {
+ if c.windows && runtime.GOOS != "windows" {
+ continue
+ }
+ u, _ := url.Parse(c.url)
+ p, err := FileURLToPath(u)
+ if c.haserror {
+ assert.Error(t, err, "case %d: should return error", n)
+ } else {
+ assert.NoError(t, err, "case %d: should not return error", n)
+ assert.Equal(t, c.expected, p, "case %d: should be equal", n)
+ }
+ }
+}