Skip to content

Instantly share code, notes, and snippets.

@Varriount
Created April 28, 2014 19:32
Show Gist options
  • Save Varriount/11381792 to your computer and use it in GitHub Desktop.
Save Varriount/11381792 to your computer and use it in GitHub Desktop.
path
import strutils, os
type PathToken = enum
ptParentDir
ptCurrentDir
ptExtraSep
ptNone
proc parsePathToken(s: string, offset: int): PathToken =
result = ptNone
echo "Trying to parse token at ", offset
if (offset + parDir.len) < s.len() and s.continuesWith(parDir, offset):
if (offset + parDir.len) == s.len() or
s[offset + (parDir.len)] in {altSep, dirSep}:
result = ptParentDir
elif s[offset] == curDir:
if (offset + 1) == s.len() or s[offset + 1] in {altSep, dirSep}:
result = ptCurrentDir
elif (offset + 1) != s.len() and s[offset] in {dirSep, altSep}:
result = ptExtraSep
proc simplifyPath(path: string): string =
## Simplify a path, removing redundant path seperators and current directory
## tokens, and applying parent directory tokens,
result = path
var
bounds = newSeq[int]()
writePos, readPos = 0
while readPos < path.len:
echo("Writing '$#' at $# to '$#' at $#".format(path[readPos], readPos, result[writePos], writePos))
if path[readPos] in {altSep, dirSep}: # Handle possible meta-paths and junk
while true:
case parsePathToken(path, readPos+1)
of ptParentDir:
echo("Got ptParentDir")
writePos = bounds.pop()
echo "Popping boundary to writePos: ", writePos
readPos.inc(3)
echo "readPos incremented to ", readPos
of ptCurrentDir:
echo("Got ptCurrentDir")
readPos.inc(2)
echo "readPos incremented to ", readPos
of ptExtraSep:
echo("Got ptExtraSep")
readPos.inc(1)
echo "readPos incremented to ", readPos
else:
echo("Got ptNone")
break
echo "Adding bound at ", readPos
bounds.add(readPos)
result[writePos] = path[readPos]
writePos.inc
readPos.inc
echo readPos, ' ', writePos
result.setLen(writePos)
echo simplifyPath(r"\User\..\Clay\..\Ben")
##
## "/User/Clay/../Ben/../../"
##
## " "
##
## "/User/Clay/../Ben/../../"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment