Skip to content

Instantly share code, notes, and snippets.

@dom96
Last active August 29, 2015 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dom96/11382471 to your computer and use it in GitHub Desktop.
Save dom96/11382471 to your computer and use it in GitHub Desktop.
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