From 2e21e2857a508fadfc65475bd545a30e29c28004 Mon Sep 17 00:00:00 2001 From: Wirawan Purwanto Date: Tue, 25 Jun 2013 17:01:26 -0400 Subject: [PATCH] * Added function relpath() to compute relative path from one to another path. --- shell_tools.py | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/shell_tools.py b/shell_tools.py index 59253f3..1d2bec4 100644 --- a/shell_tools.py +++ b/shell_tools.py @@ -21,6 +21,9 @@ except: print >>sys.stderr, "Newer subprocess module does not exist, using older interfaces." has_subprocess = False + +# Files, directories, and filename utilities + def mcd(subdir): # Assuming we have GNU coreutils' mkdir mkdir("-p", subdir) @@ -47,6 +50,35 @@ def provide_link(dest, src): os.symlink(src, dest.rstrip("/")) +# The following 3 routines are from +# http://code.activestate.com/recipes/208993-compute-relative-path-from-one-directory-to-anothe/ +# by Cimarron Taylor +# (PSF license) + +def _pathsplit(p, rest=[]): + (h,t) = os.path.split(p) + if len(h) < 1: return [t]+rest + if len(t) < 1: return [h]+rest + return _pathsplit(h,[t]+rest) + +def _commonpath(l1, l2, common=[]): + if len(l1) < 1: return (common, l1, l2) + if len(l2) < 1: return (common, l1, l2) + if l1[0] != l2[0]: return (common, l1, l2) + return _commonpath(l1[1:], l2[1:], common+[l1[0]]) + +def relpath(p1, p2): + """Computes the relative path of p2 with respect to p1.""" + (common,l1,l2) = _commonpath(_pathsplit(p1), _pathsplit(p2)) + p = [] + if len(l1) > 0: + p = [ '../' * len(l1) ] + p = p + l2 + return os.path.join( *p ) + +# /// end code snippet + + # Globbing utilities: def sorted_glob(pathname):#, cmp=None, key=None, reverse=None):