fspath: make JoinRootPath convert backslashes to slashes on Windows

The function is used for contructing remotes which may have
backslashes in on Windows.
This commit is contained in:
Nick Craig-Wood 2020-09-01 17:55:06 +01:00
parent 23c826db52
commit 3affc2e066
2 changed files with 12 additions and 3 deletions

View File

@ -105,14 +105,21 @@ func Split(remote string) (parent string, leaf string, err error) {
// JoinRootPath joins any number of path elements into a single path, adding a
// separating slash if necessary. The result is Cleaned; in particular,
// all empty strings are ignored.
//
// If the first non empty element has a leading "//" this is preserved.
//
// If the path contains \ these will be converted to / on Windows.
func JoinRootPath(elem ...string) string {
for i, e := range elem {
es := make([]string, len(elem))
for i := range es {
es[i] = filepath.ToSlash(elem[i])
}
for i, e := range es {
if e != "" {
if strings.HasPrefix(e, "//") {
return "/" + path.Clean(strings.Join(elem[i:], "/"))
return "/" + path.Clean(strings.Join(es[i:], "/"))
}
return path.Clean(strings.Join(elem[i:], "/"))
return path.Clean(strings.Join(es[i:], "/"))
}
}
return ""

View File

@ -2,6 +2,7 @@ package fspath
import (
"fmt"
"path/filepath"
"runtime"
"strings"
"testing"
@ -153,6 +154,7 @@ func TestJoinRootPath(t *testing.T) {
{[]string{"", "//server/sub", "path"}, "//server/sub/path"},
{[]string{"", "//server", "//path"}, "//server/path"},
{[]string{"", "//server/sub", "//path"}, "//server/sub/path"},
{[]string{"", filepath.FromSlash("//server/sub"), filepath.FromSlash("//path")}, "//server/sub/path"},
} {
got := JoinRootPath(test.elements...)
assert.Equal(t, test.want, got)