splitPath() behavior synchronized with splitFile() (#12481)

* splitPath() behavior synchronized with splitFile() having the expected behavior in all languages

splitPath() docstrings update, tests added for both splitPath() and splitFile()

* Path splitting refined and described
This commit is contained in:
Artem V L 2019-10-28 12:58:02 +01:00 • committed by Andreas Rumpf
commit 580462c886
2 changed files with 17 additions and 3 deletions

View file

@ -8,6 +8,7 @@
### Breaking changes in the standard library
- `base64.encode` no longer supports `lineLen` and `newLine` use `base64.encodeMIME` instead.
- `os.splitPath()` behavior synchronized with `os.splitFile()` to return "/" as the dir component of "/root_sub_dir" instead of the empty string.
### Breaking changes in the compiler

View file

@ -216,8 +216,12 @@ proc splitPath*(path: string): tuple[head, tail: string] {.
runnableExamples:
assert splitPath("usr/local/bin") == ("usr/local", "bin")
assert splitPath("usr/local/bin/") == ("usr/local/bin", "")
assert splitPath("/bin/") == ("/bin", "")
when (NimMajor, NimMinor) <= (1, 0):
assert splitPath("/bin") == ("", "bin")
else:
assert splitPath("/bin") == ("/", "bin")
assert splitPath("bin") == ("", "bin")
assert splitPath("/bin") == ("", "bin")
assert splitPath("") == ("", "")
var sepPos = -1
@ -226,7 +230,12 @@ proc splitPath*(path: string): tuple[head, tail: string] {.
sepPos = i
break
if sepPos >= 0:
result.head = substr(path, 0, sepPos-1)
result.head = substr(path, 0,
when (NimMajor, NimMinor) <= (1, 0):
sepPos-1
else:
if likely(sepPos >= 1): sepPos-1 else: 0
)
result.tail = substr(path, sepPos+1)
else:
result.head = ""
@ -597,13 +606,17 @@ proc splitFile*(path: string): tuple[dir, name, ext: string] {.
assert dir == "/usr/local"
assert name == ""
assert ext == ""
(dir, name, ext) = splitFile("/tmp.txt")
assert dir == "/"
assert name == "tmp"
assert ext == ".txt"
var namePos = 0
var dotPos = 0
for i in countdown(len(path) - 1, 0):
if path[i] in {DirSep, AltSep} or i == 0:
if path[i] in {DirSep, AltSep}:
result.dir = substr(path, 0, max(0, i - 1))
result.dir = substr(path, 0, if likely(i >= 1): i - 1 else: 0)
namePos = i + 1
if dotPos > i:
result.name = substr(path, namePos, dotPos - 1)