diff options
author | willmcgugan@gmail.com <willmcgugan@gmail.com@67cdc799-7952-0410-af00-57a81ceafa0f> | 2013-06-28 12:28:08 +0000 |
---|---|---|
committer | willmcgugan@gmail.com <willmcgugan@gmail.com@67cdc799-7952-0410-af00-57a81ceafa0f> | 2013-06-28 12:28:08 +0000 |
commit | 9545ff3d5e3605d2c70a67a2de9607bd34d08014 (patch) | |
tree | 62afbfcd04de8b294a49d3801cae150a7ee86b30 /fs/path.py | |
parent | 8a78d3236747fc2602eff9e307ff938607a14444 (diff) | |
download | pyfilesystem-9545ff3d5e3605d2c70a67a2de9607bd34d08014.tar.gz |
Added 'relativefrom' method to path.py
git-svn-id: http://pyfilesystem.googlecode.com/svn/trunk@857 67cdc799-7952-0410-af00-57a81ceafa0f
Diffstat (limited to 'fs/path.py')
-rw-r--r-- | fs/path.py | 28 |
1 files changed, 28 insertions, 0 deletions
@@ -396,6 +396,29 @@ def frombase(path1, path2): return path2[len(path1):] +def relativefrom(base, path): + """Return a path relative from a given base path, + i.e. insert backrefs as appropriate to reach the path from the base. + + :param base_path: Path to a directory + :param path: Path you wish to make relative + + + >>> relativefrom("foo/bar", "baz/index.html") + '../baz/index.html' + + """ + base = list(iteratepath(base)) + path = list(iteratepath(path)) + + while base and path and base[0] == path[0]: + base.pop(0) + path.pop(0) + + # If you multiply a list by a negative number, you get an empty list! + return u'/'.join([u'..'] * len(base) + path) + + class PathMap(object): """Dict-like object with paths for keys. @@ -626,3 +649,8 @@ def iswildcard(path): if __name__ == "__main__": print recursepath('a/b/c') + + print relativefrom('/', '/foo') + print relativefrom('/foo/bar', '/foo/baz') + print relativefrom('/foo/bar/baz', '/foo/egg') + print relativefrom('/foo/bar/baz/egg', '/foo/egg') |