Commit a32a775d by willmcgugan

Some optimizations

parent 1c7a928c
...@@ -10,7 +10,9 @@ optional leading slash). ...@@ -10,7 +10,9 @@ optional leading slash).
""" """
import re
_requires_normalization = re.compile(r'/\.\.|\./|//|\\').search
def normpath(path): def normpath(path):
"""Normalizes a path to be in the format expected by FS objects. """Normalizes a path to be in the format expected by FS objects.
...@@ -34,8 +36,14 @@ def normpath(path): ...@@ -34,8 +36,14 @@ def normpath(path):
ValueError: too many backrefs in path 'foo/../../bar' ValueError: too many backrefs in path 'foo/../../bar'
""" """
if not path:
if path in ('', '/'):
return path return path
# An early out if there is no need to normalize this paath
if not _requires_normalization(path):
return path.rstrip('/')
components = [] components = []
append = components.append append = components.append
for comp in [c for c in path.replace('\\','/').split("/") if c not in ('', '.')]: for comp in [c for c in path.replace('\\','/').split("/") if c not in ('', '.')]:
...@@ -43,8 +51,7 @@ def normpath(path): ...@@ -43,8 +51,7 @@ def normpath(path):
try: try:
components.pop() components.pop()
except IndexError: except IndexError:
err = "too many backrefs in path '%s'" % (path,) raise ValueError("too many backrefs in path '%s'" % path)
raise ValueError(err)
else: else:
append(comp) append(comp)
if path[0] in '\\/': if path[0] in '\\/':
...@@ -78,18 +85,22 @@ def recursepath(path, reverse=False): ...@@ -78,18 +85,22 @@ def recursepath(path, reverse=False):
['/', u'/a', u'/a/b', u'/a/b/c'] ['/', u'/a', u'/a/b', u'/a/b/c']
""" """
if path in ('', '/'):
return [u'/']
path = abspath(normpath(path)) + '/'
paths = [u'/'] paths = [u'/']
append = paths.append
path = u'/' + normpath(path.lstrip('/'))
find = path.find find = path.find
append = paths.append
pos = 1 pos = 1
if len(path) > 1: len_path = len(path)
while 1:
pos = find('/', pos + 1) while pos < len_path:
if pos == -1: pos = find('/', pos)
append(path)
break
append(path[:pos]) append(path[:pos])
pos += 1
if reverse: if reverse:
return paths[::-1] return paths[::-1]
...@@ -534,3 +545,6 @@ def iswildcard(path): ...@@ -534,3 +545,6 @@ def iswildcard(path):
assert path is not None assert path is not None
base_chars = frozenset(basename(path)) base_chars = frozenset(basename(path))
return not base_chars.isdisjoint(_wild_chars) return not base_chars.isdisjoint(_wild_chars)
if __name__ == "__main__":
print recursepath('a/b/c')
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment