added rewritten normpath from Moshe Zadka that does the right thing with

paths containing ..
This commit is contained in:
Skip Montanaro 2000-07-19 17:09:51 +00:00
parent 7cb1524586
commit 018dfae246
1 changed files with 18 additions and 23 deletions

View File

@ -346,30 +346,25 @@ are left unchanged"""
def normpath(path): def normpath(path):
"""Normalize path, eliminating double slashes, etc.""" """Normalize path, eliminating double slashes, etc."""
if path == '':
return '.'
import string import string
# Treat initial slashes specially initial_slash = (path[0] == '/')
slashes = '' comps = string.split(path, '/')
while path[:1] == '/': new_comps = []
slashes = slashes + '/' for comp in comps:
path = path[1:] if comp in ('', '.'):
comps = string.splitfields(path, '/') continue
i = 0 if (comp != '..' or (not initial_slash and not new_comps) or
while i < len(comps): (new_comps and new_comps[-1] == '..')):
if comps[i] == '.': new_comps.append(comp)
del comps[i] elif new_comps:
while i < len(comps) and comps[i] == '': new_comps.pop()
del comps[i] comps = new_comps
elif comps[i] == '..' and i > 0 and comps[i-1] not in ('', '..'): path = string.join(comps, '/')
del comps[i-1:i+1] if initial_slash:
i = i-1 path = '/' + path
elif comps[i] == '' and i > 0 and comps[i-1] <> '': return path or '.'
del comps[i]
else:
i = i+1
# If the path is now empty, substitute '.'
if not comps and not slashes:
comps.append('.')
return slashes + string.joinfields(comps, '/')
def abspath(path): def abspath(path):