//example:
/a/b/.. -> /a/
/a/b/./ -> /a/b/
/a/b// -> /a/b/
/a/b/../../ -> /
///// -> /
/a/b/../../.. -> throw
string sanitize-path(path):
if path == null || (path = path.trim()) == "":
throw
// assume split removes empty entries
tokens = path.split("/")
target = 0
for i = 0, i < tokens.length, i++:
if tokens[i] == ".":
// do nothing
else if tokens[i] == "..":
target--
if target < 0:
throw "invalid input"
else:
tokens[target] == tokens[i]
target++
buffer = new
buffer.append("/")
for i = 0, i < target, i++:
buffer.append(tokens[i])
buffer.append("/")
return buffer.tostring()
[Hat tip to LM]
No comments:
Post a Comment