--- /dev/null
+// Copyright 2019 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.
+
+// +build aix darwin dragonfly freebsd js,wasm linux nacl netbsd openbsd solaris
+
+package os
+
+var SplitPath = splitPath
t.Parallel()
newFileTest(t, false)
}
+
+func TestSplitPath(t *testing.T) {
+ t.Parallel()
+ for _, tt := range []struct{ path, wantDir, wantBase string }{
+ {"a", ".", "a"},
+ {"a/", ".", "a"},
+ {"a//", ".", "a"},
+ {"a/b", "a", "b"},
+ {"a/b/", "a", "b"},
+ {"a/b/c", "a/b", "c"},
+ {"/a", "/", "a"},
+ {"/a/", "/", "a"},
+ {"/a/b", "/a", "b"},
+ {"/a/b/", "/a", "b"},
+ {"/a/b/c", "/a/b", "c"},
+ {"//a", "/", "a"},
+ {"//a/", "/", "a"},
+ {"///a", "/", "a"},
+ {"///a/", "/", "a"},
+ } {
+ if dir, base := SplitPath(tt.path); dir != tt.wantDir || base != tt.wantBase {
+ t.Errorf("splitPath(%q) = %q, %q, want %q, %q", tt.path, dir, base, tt.wantDir, tt.wantBase)
+ }
+ }
+}
func splitPath(path string) (string, string) {
// if no better parent is found, the path is relative from "here"
dirname := "."
- // if no slashes in path, base is path
- basename := path
+
+ // Remove all but one leading slash.
+ for len(path) > 1 && path[0] == '/' && path[1] == '/' {
+ path = path[1:]
+ }
i := len(path) - 1
- // Remove trailing slashes
+ // Remove trailing slashes.
for ; i > 0 && path[i] == '/'; i-- {
path = path[:i]
}
+ // if no slashes in path, base is path
+ basename := path
+
// Remove leading directory path
for i--; i >= 0; i-- {
if path[i] == '/' {
- dirname = path[:i]
+ if i == 0 {
+ dirname = path[:1]
+ } else {
+ dirname = path[:i]
+ }
basename = path[i+1:]
break
}