From 580462c886209a0a5b1c1059fcc5b905b6bf1814 Mon Sep 17 00:00:00 2001 From: Artem V L Date: Mon, 28 Oct 2019 12:58:02 +0100 Subject: [PATCH] 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 --- changelog.md | 1 + lib/pure/os.nim | 19 ++++++++++++++++--- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/changelog.md b/changelog.md index 8b1aaeadc..6a30ab852 100644 --- a/changelog.md +++ b/changelog.md @@ -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 diff --git a/lib/pure/os.nim b/lib/pure/os.nim index 9894831a6..b27eee782 100644 --- a/lib/pure/os.nim +++ b/lib/pure/os.nim @@ -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)