blob: 05cc92ae2f69b784fc569c7a9e8433413e1ba946 [file] [log] [blame]
Guido van Rossum26847381992-03-31 18:54:35 +00001# Module 'posixpath' -- common operations on POSIX pathnames
Guido van Rossumc6360141990-10-13 19:23:40 +00002
3import posix
Guido van Rossum40d93041990-10-21 16:17:34 +00004import stat
Guido van Rossumc6360141990-10-13 19:23:40 +00005
6
Guido van Rossum7ac48781992-01-14 18:29:32 +00007# Normalize the case of a pathname. Trivial in Posix, string.lower on Mac.
8# On MS-DOS this may also turn slashes into backslashes; however, other
9# normalizations (such as optimizing '../' away) are not allowed
10# (another function should be defined to do that).
11
12def normcase(s):
13 return s
14
15
16# Return wheter a path is absolute.
17# Trivial in Posix, harder on the Mac or MS-DOS.
18
19def isabs(s):
20 return s[:1] == '/'
21
22
Guido van Rossum4d0fdc31991-08-16 13:27:58 +000023# Join two pathnames.
Guido van Rossum7ac48781992-01-14 18:29:32 +000024# Ignore the first part if the second part is absolute.
Guido van Rossum4d0fdc31991-08-16 13:27:58 +000025# Insert a '/' unless the first part is empty or already ends in '/'.
Guido van Rossum7ac48781992-01-14 18:29:32 +000026
Guido van Rossum4d0fdc31991-08-16 13:27:58 +000027def join(a, b):
Guido van Rossumbdfcfcc1992-01-01 19:35:13 +000028 if b[:1] == '/': return b
29 if a == '' or a[-1:] == '/': return a + b
Guido van Rossum4d0fdc31991-08-16 13:27:58 +000030 # Note: join('x', '') returns 'x/'; is this what we want?
Guido van Rossumc6360141990-10-13 19:23:40 +000031 return a + '/' + b
32
33
Guido van Rossum26847381992-03-31 18:54:35 +000034# Split a path in head (everything up to the last '/') and tail (the
35# rest). If the original path ends in '/' but is not the root, this
36# '/' is stripped. After the trailing '/' is stripped, the invariant
37# join(head, tail) == p holds.
38# The resulting head won't end in '/' unless it is the root.
Guido van Rossum7ac48781992-01-14 18:29:32 +000039
Guido van Rossumc6360141990-10-13 19:23:40 +000040def split(p):
Guido van Rossum26847381992-03-31 18:54:35 +000041 if p[-1:] == '/' and p <> '/'*len(p):
42 while p[-1] == '/':
43 p = p[:-1]
Guido van Rossumc6360141990-10-13 19:23:40 +000044 head, tail = '', ''
45 for c in p:
46 tail = tail + c
Guido van Rossumbdfcfcc1992-01-01 19:35:13 +000047 if c == '/':
Guido van Rossumc6360141990-10-13 19:23:40 +000048 head, tail = head + tail, ''
Guido van Rossum26847381992-03-31 18:54:35 +000049 if head[-1:] == '/' and head <> '/'*len(head):
50 while head[-1] == '/':
51 head = head[:-1]
Guido van Rossumc6360141990-10-13 19:23:40 +000052 return head, tail
53
54
Guido van Rossum4d0fdc31991-08-16 13:27:58 +000055# Split a path in root and extension.
56# The extension is everything starting at the first dot in the last
57# pathname component; the root is everything before that.
Guido van Rossum7ac48781992-01-14 18:29:32 +000058# It is always true that root + ext == p.
59
Guido van Rossum4d0fdc31991-08-16 13:27:58 +000060def splitext(p):
61 root, ext = '', ''
62 for c in p:
Guido van Rossumbdfcfcc1992-01-01 19:35:13 +000063 if c == '/':
Guido van Rossum4d0fdc31991-08-16 13:27:58 +000064 root, ext = root + ext + c, ''
Sjoerd Mullender43598601994-12-14 15:29:17 +000065 elif c == '.':
66 if ext:
67 root, ext = root + ext, c
68 else:
69 ext = c
70 elif ext:
Guido van Rossum4d0fdc31991-08-16 13:27:58 +000071 ext = ext + c
72 else:
73 root = root + c
74 return root, ext
75
76
Guido van Rossum221df241995-08-07 20:17:55 +000077# Split a pathname into a drive specification and the rest of the
78# path. Useful on DOS/Windows/NT; on Unix, the drive is always empty.
79
80def splitdrive(p):
81 return '', p
82
83
Guido van Rossumc6360141990-10-13 19:23:40 +000084# Return the tail (basename) part of a path.
Guido van Rossum7ac48781992-01-14 18:29:32 +000085
Guido van Rossumc6360141990-10-13 19:23:40 +000086def basename(p):
87 return split(p)[1]
88
89
Guido van Rossumc629d341992-11-05 10:43:02 +000090# Return the head (dirname) part of a path.
91
92def dirname(p):
93 return split(p)[0]
94
95
Guido van Rossumc6360141990-10-13 19:23:40 +000096# Return the longest prefix of all list elements.
Guido van Rossum7ac48781992-01-14 18:29:32 +000097
Guido van Rossumc6360141990-10-13 19:23:40 +000098def commonprefix(m):
99 if not m: return ''
100 prefix = m[0]
101 for item in m:
102 for i in range(len(prefix)):
103 if prefix[:i+1] <> item[:i+1]:
104 prefix = prefix[:i]
Guido van Rossumbdfcfcc1992-01-01 19:35:13 +0000105 if i == 0: return ''
Guido van Rossumc6360141990-10-13 19:23:40 +0000106 break
107 return prefix
108
109
Guido van Rossum7ac48781992-01-14 18:29:32 +0000110# Is a path a symbolic link?
111# This will always return false on systems where posix.lstat doesn't exist.
112
113def islink(path):
114 try:
115 st = posix.lstat(path)
116 except (posix.error, AttributeError):
117 return 0
118 return stat.S_ISLNK(st[stat.ST_MODE])
119
120
121# Does a path exist?
122# This is false for dangling symbolic links.
123
Guido van Rossumc6360141990-10-13 19:23:40 +0000124def exists(path):
125 try:
126 st = posix.stat(path)
127 except posix.error:
128 return 0
129 return 1
130
131
132# Is a path a posix directory?
Guido van Rossum7ac48781992-01-14 18:29:32 +0000133# This follows symbolic links, so both islink() and isdir() can be true
134# for the same path.
135
Guido van Rossumc6360141990-10-13 19:23:40 +0000136def isdir(path):
137 try:
138 st = posix.stat(path)
139 except posix.error:
140 return 0
Guido van Rossum40d93041990-10-21 16:17:34 +0000141 return stat.S_ISDIR(st[stat.ST_MODE])
Guido van Rossumc6360141990-10-13 19:23:40 +0000142
143
Guido van Rossum26847381992-03-31 18:54:35 +0000144# Is a path a regular file?
Guido van Rossumb6775db1994-08-01 11:34:53 +0000145# This follows symbolic links, so both islink() and isfile() can be true
Guido van Rossum7ac48781992-01-14 18:29:32 +0000146# for the same path.
147
148def isfile(path):
Guido van Rossumc6360141990-10-13 19:23:40 +0000149 try:
Guido van Rossum7ac48781992-01-14 18:29:32 +0000150 st = posix.stat(path)
151 except posix.error:
Guido van Rossumc6360141990-10-13 19:23:40 +0000152 return 0
Guido van Rossum7ac48781992-01-14 18:29:32 +0000153 return stat.S_ISREG(st[stat.ST_MODE])
Guido van Rossumc6360141990-10-13 19:23:40 +0000154
155
Guido van Rossumd3778f91991-11-12 15:37:40 +0000156# Are two filenames really pointing to the same file?
Guido van Rossum7ac48781992-01-14 18:29:32 +0000157
Guido van Rossumd3778f91991-11-12 15:37:40 +0000158def samefile(f1, f2):
159 s1 = posix.stat(f1)
160 s2 = posix.stat(f2)
161 return samestat(s1, s2)
162
163
164# Are two open files really referencing the same file?
165# (Not necessarily the same file descriptor!)
166# XXX Oops, posix.fstat() doesn't exist yet!
Guido van Rossum7ac48781992-01-14 18:29:32 +0000167
Guido van Rossumd3778f91991-11-12 15:37:40 +0000168def sameopenfile(fp1, fp2):
169 s1 = posix.fstat(fp1)
170 s2 = posix.fstat(fp2)
171 return samestat(s1, s2)
172
173
174# Are two stat buffers (obtained from stat, fstat or lstat)
175# describing the same file?
Guido van Rossum7ac48781992-01-14 18:29:32 +0000176
Guido van Rossumd3778f91991-11-12 15:37:40 +0000177def samestat(s1, s2):
Guido van Rossumbdfcfcc1992-01-01 19:35:13 +0000178 return s1[stat.ST_INO] == s2[stat.ST_INO] and \
Guido van Rossum509d24a1992-05-06 11:36:49 +0000179 s1[stat.ST_DEV] == s2[stat.ST_DEV]
Guido van Rossumc6360141990-10-13 19:23:40 +0000180
181
182# Is a path a mount point?
Guido van Rossum509d24a1992-05-06 11:36:49 +0000183# (Does this work for all UNIXes? Is it even guaranteed to work by POSIX?)
Guido van Rossum7ac48781992-01-14 18:29:32 +0000184
Guido van Rossumc6360141990-10-13 19:23:40 +0000185def ismount(path):
Guido van Rossum509d24a1992-05-06 11:36:49 +0000186 try:
187 s1 = posix.stat(path)
188 s2 = posix.stat(join(path, '..'))
189 except posix.error:
190 return 0 # It doesn't exist -- so not a mount point :-)
191 dev1 = s1[stat.ST_DEV]
192 dev2 = s2[stat.ST_DEV]
193 if dev1 != dev2:
194 return 1 # path/.. on a different device as path
195 ino1 = s1[stat.ST_INO]
196 ino2 = s2[stat.ST_INO]
197 if ino1 == ino2:
198 return 1 # path/.. is the same i-node as path
199 return 0
Guido van Rossumc6360141990-10-13 19:23:40 +0000200
201
202# Directory tree walk.
Guido van Rossum7ac48781992-01-14 18:29:32 +0000203# For each directory under top (including top itself, but excluding
204# '.' and '..'), func(arg, dirname, filenames) is called, where
205# dirname is the name of the directory and filenames is the list
206# files files (and subdirectories etc.) in the directory.
207# The func may modify the filenames list, to implement a filter,
Guido van Rossumc6360141990-10-13 19:23:40 +0000208# or to impose a different order of visiting.
Guido van Rossum7ac48781992-01-14 18:29:32 +0000209
Guido van Rossumc6360141990-10-13 19:23:40 +0000210def walk(top, func, arg):
211 try:
212 names = posix.listdir(top)
213 except posix.error:
214 return
215 func(arg, top, names)
216 exceptions = ('.', '..')
217 for name in names:
218 if name not in exceptions:
Guido van Rossum4d0fdc31991-08-16 13:27:58 +0000219 name = join(top, name)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000220 if isdir(name) and not islink(name):
Guido van Rossumc6360141990-10-13 19:23:40 +0000221 walk(name, func, arg)
Guido van Rossum7ac48781992-01-14 18:29:32 +0000222
223
224# Expand paths beginning with '~' or '~user'.
225# '~' means $HOME; '~user' means that user's home directory.
226# If the path doesn't begin with '~', or if the user or $HOME is unknown,
227# the path is returned unchanged (leaving error reporting to whatever
228# function is called with the expanded path as argument).
229# See also module 'glob' for expansion of *, ? and [...] in pathnames.
230# (A function should also be defined to do full *sh-style environment
231# variable expansion.)
232
233def expanduser(path):
234 if path[:1] <> '~':
235 return path
236 i, n = 1, len(path)
237 while i < n and path[i] <> '/':
238 i = i+1
239 if i == 1:
240 if not posix.environ.has_key('HOME'):
241 return path
242 userhome = posix.environ['HOME']
243 else:
244 import pwd
245 try:
246 pwent = pwd.getpwnam(path[1:i])
247 except KeyError:
248 return path
249 userhome = pwent[5]
250 return userhome + path[i:]
Guido van Rossum4732ccf1992-08-09 13:54:50 +0000251
252
253# Expand paths containing shell variable substitutions.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000254# This expands the forms $variable and ${variable} only.
255# Non-existant variables are left unchanged.
256
257_varprog = None
Guido van Rossum4732ccf1992-08-09 13:54:50 +0000258
259def expandvars(path):
Guido van Rossumb6775db1994-08-01 11:34:53 +0000260 global _varprog
Guido van Rossum4732ccf1992-08-09 13:54:50 +0000261 if '$' not in path:
262 return path
Guido van Rossumb6775db1994-08-01 11:34:53 +0000263 if not _varprog:
264 import regex
265 _varprog = regex.compile('$\([a-zA-Z0-9_]+\|{[^}]*}\)')
266 i = 0
267 while 1:
268 i = _varprog.search(path, i)
269 if i < 0:
270 break
271 name = _varprog.group(1)
272 j = i + len(_varprog.group(0))
273 if name[:1] == '{' and name[-1:] == '}':
274 name = name[1:-1]
275 if posix.environ.has_key(name):
276 tail = path[j:]
277 path = path[:i] + posix.environ[name]
278 i = len(path)
279 path = path + tail
280 else:
281 i = j
282 return path
Guido van Rossumc629d341992-11-05 10:43:02 +0000283
284
285# Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A/B.
286# It should be understood that this may change the meaning of the path
287# if it contains symbolic links!
288
289def normpath(path):
290 import string
Guido van Rossumdf563861993-07-06 15:19:36 +0000291 # Treat initial slashes specially
292 slashes = ''
293 while path[:1] == '/':
294 slashes = slashes + '/'
295 path = path[1:]
Guido van Rossumc629d341992-11-05 10:43:02 +0000296 comps = string.splitfields(path, '/')
Guido van Rossumc629d341992-11-05 10:43:02 +0000297 i = 0
298 while i < len(comps):
299 if comps[i] == '.':
300 del comps[i]
301 elif comps[i] == '..' and i > 0 and \
302 comps[i-1] not in ('', '..'):
303 del comps[i-1:i+1]
304 i = i-1
305 elif comps[i] == '' and i > 0 and comps[i-1] <> '':
306 del comps[i]
307 else:
308 i = i+1
309 # If the path is now empty, substitute '.'
Guido van Rossumdf563861993-07-06 15:19:36 +0000310 if not comps and not slashes:
Guido van Rossumc629d341992-11-05 10:43:02 +0000311 comps.append('.')
Guido van Rossumdf563861993-07-06 15:19:36 +0000312 return slashes + string.joinfields(comps, '/')