Last active
August 29, 2015 14:00
-
-
Save dom96/11382471 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import strutils, os | |
proc simplifyPath(path: string): string = | |
var segments: seq[string] = @[] | |
var i = 0 | |
var curDir = "" | |
while true: | |
case path[i] | |
of dirSep, altSep: | |
if curDir != "" or i == 0: | |
segments.add curDir | |
curDir = "" | |
of '.': | |
if path[i+1] == '.' and path[i+2] in {dirSep, altSep, '\0'}: | |
# Move up a dir. | |
discard segments.pop() | |
i.inc | |
elif path[i+1] notin {dirSep, altSep, '\0'}: | |
curDir.add path[i] | |
of '~': | |
if path[i+1] in {dirSep, altSep, '\0'}: | |
segments.add getHomeDir() | |
of '\0': | |
if curDir != "": | |
segments.add curDir | |
break | |
else: | |
curDir.add path[i] | |
i.inc | |
result = segments.join($dirSep) | |
when isMainModule: | |
when defined(windows): | |
doAssert simplifyPath(r"\User\..\Clay\..\Ben") == r"\Ben" | |
doAssert simplifyPath(r"C:\Test\..\Program Files\Nimrod") == r"C:\Program Files\Nimrod" | |
doAssert simplifyPath(r"/Blah/./../Test/") == r"\Test" | |
doAssert simplifyPath(r"/Blah/./foo.txt/..asf/../a..sd/") == r"\Blah\foo.txt\a..sd" | |
else: | |
doAssert simplifyPath(r"\User\..\Clay\..\Ben") == r"/Ben" | |
doAssert simplifyPath(r"C:\Test\..\Program Files\Nimrod") == r"C:/Program Files/Nimrod" | |
doAssert simplifyPath(r"/Blah/./../Test/") == r"/Test" | |
doAssert simplifyPath(r"/Blah/./foo.txt/..asf/../a..sd/") == r"/Blah/foo.txt/a..sd" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment