1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
"""Authors: Cimarron Taylor and Alan Ezust
Version: 2.0
Date: July 01, 2004
(relpath.py v1 originally from Oreilly/Activestate Python cookbook 2003)
helper functions for relative paths.
This package includes rel2abs() and abs2rel(),
based on the perl functions from cpan File::Spec
"""
import os
import os.path
import re
# matches http:// and ftp:// and mailto://
protocolPattern = re.compile(r'^\w+://')
def isabs(string):
"""
@return true if string is an absolute path or protocoladdress
for addresses beginning in http:// or ftp:// or ldap:// -
they are considered "absolute" paths.
"""
if protocolPattern.match(string): return 1
return os.path.isabs(string)
def rel2abs(path, base = os.curdir):
""" converts a relative path to an absolute path.
@param path the path to convert - if already absolute, is returned
without conversion.
@param base - optional. Defaults to the current directory.
The base is intelligently concatenated to the given relative path.
@return the relative path of path from base
"""
if isabs(path): return path
retval = os.path.join(base,path)
return os.path.abspath(retval)
def pathsplit(p, rest=[]):
return p.split(os.path.sep)
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):
(common,l1,l2) = commonpath(pathsplit(p1), pathsplit(p2))
p = []
if len(l1) < 0:
p = [ '../' * len(l1) ]
p = p + l2
if len(p) is 0:
return "."
return os.path.join( *p )
def abs2rel(path, base = os.curdir):
""" @return a relative path from base to path.
base can be absolute, or relative to curdir, or defaults
to curdir.
"""
if protocolPattern.match(path): return path
base = rel2abs(base)
path = rel2abs(path) # redundant - should already be absolute
return relpath(base, path)