blob: f92841fd5f9eca507770a7453e199c16de41556d [file] [log] [blame]
Andrew MacIntyre5cef5712002-02-24 05:32:32 +00001# Module 'os2emxpath' -- common operations on OS/2 pathnames
Tim Peters863ac442002-04-16 01:38:40 +00002"""Common pathname manipulations, OS/2 EMX version.
Andrew MacIntyre5cef5712002-02-24 05:32:32 +00003
4Instead of importing this module directly, import os and refer to this
5module as os.path.
6"""
7
8import os
9import stat
10
11__all__ = ["normcase","isabs","join","splitdrive","split","splitext",
12 "basename","dirname","commonprefix","getsize","getmtime",
Martin v. Löwis96a60e42002-12-31 13:11:54 +000013 "getatime","getctime", "islink","exists","isdir","isfile","ismount",
Mark Hammond8696ebc2002-10-08 02:44:31 +000014 "walk","expanduser","expandvars","normpath","abspath","splitunc",
Neal Norwitz61cdac62003-01-03 18:01:57 +000015 "realpath","supports_unicode_filenames"]
Andrew MacIntyre5cef5712002-02-24 05:32:32 +000016
17# Normalize the case of a pathname and map slashes to backslashes.
18# Other normalizations (such as optimizing '../' away) are not done
19# (this is done by normpath).
20
21def normcase(s):
22 """Normalize case of pathname.
23
24 Makes all characters lowercase and all altseps into seps."""
25 return s.replace('\\', '/').lower()
26
27
28# Return whether a path is absolute.
29# Trivial in Posix, harder on the Mac or MS-DOS.
30# For DOS it is absolute if it starts with a slash or backslash (current
31# volume), or if a pathname after the volume letter and colon / UNC resource
32# starts with a slash or backslash.
33
34def isabs(s):
35 """Test whether a path is absolute"""
36 s = splitdrive(s)[1]
37 return s != '' and s[:1] in '/\\'
38
39
40# Join two (or more) paths.
41
42def join(a, *p):
43 """Join two or more pathname components, inserting sep as needed"""
44 path = a
45 for b in p:
46 if isabs(b):
47 path = b
48 elif path == '' or path[-1:] in '/\\:':
49 path = path + b
50 else:
51 path = path + '/' + b
52 return path
53
54
55# Split a path in a drive specification (a drive letter followed by a
56# colon) and the path specification.
57# It is always true that drivespec + pathspec == p
58def splitdrive(p):
59 """Split a pathname into drive and path specifiers. Returns a 2-tuple
60"(drive,path)"; either part may be empty"""
61 if p[1:2] == ':':
62 return p[0:2], p[2:]
63 return '', p
64
65
66# Parse UNC paths
67def splitunc(p):
68 """Split a pathname into UNC mount point and relative path specifiers.
69
70 Return a 2-tuple (unc, rest); either part may be empty.
71 If unc is not empty, it has the form '//host/mount' (or similar
72 using backslashes). unc+rest is always the input path.
73 Paths containing drive letters never have an UNC part.
74 """
75 if p[1:2] == ':':
76 return '', p # Drive letter present
77 firstTwo = p[0:2]
78 if firstTwo == '/' * 2 or firstTwo == '\\' * 2:
79 # is a UNC path:
80 # vvvvvvvvvvvvvvvvvvvv equivalent to drive letter
81 # \\machine\mountpoint\directories...
82 # directory ^^^^^^^^^^^^^^^
83 normp = normcase(p)
84 index = normp.find('/', 2)
85 if index == -1:
86 ##raise RuntimeError, 'illegal UNC path: "' + p + '"'
87 return ("", p)
88 index = normp.find('/', index + 1)
89 if index == -1:
90 index = len(p)
91 return p[:index], p[index:]
92 return '', p
93
94
95# Split a path in head (everything up to the last '/') and tail (the
96# rest). After the trailing '/' is stripped, the invariant
97# join(head, tail) == p holds.
98# The resulting head won't end in '/' unless it is the root.
99
100def split(p):
101 """Split a pathname.
102
103 Return tuple (head, tail) where tail is everything after the final slash.
104 Either part may be empty."""
105
106 d, p = splitdrive(p)
107 # set i to index beyond p's last slash
108 i = len(p)
109 while i and p[i-1] not in '/\\':
110 i = i - 1
111 head, tail = p[:i], p[i:] # now tail has no slashes
112 # remove trailing slashes from head, unless it's all slashes
113 head2 = head
114 while head2 and head2[-1] in '/\\':
115 head2 = head2[:-1]
116 head = head2 or head
117 return d + head, tail
118
119
120# Split a path in root and extension.
121# The extension is everything starting at the last dot in the last
122# pathname component; the root is everything before that.
123# It is always true that root + ext == p.
124
125def splitext(p):
126 """Split the extension from a pathname.
127
128 Extension is everything from the last dot to the end.
129 Return (root, ext), either part may be empty."""
130 root, ext = '', ''
131 for c in p:
132 if c in ['/','\\']:
133 root, ext = root + ext + c, ''
134 elif c == '.':
135 if ext:
136 root, ext = root + ext, c
137 else:
138 ext = c
139 elif ext:
140 ext = ext + c
141 else:
142 root = root + c
143 return root, ext
144
145
146# Return the tail (basename) part of a path.
147
148def basename(p):
149 """Returns the final component of a pathname"""
150 return split(p)[1]
151
152
153# Return the head (dirname) part of a path.
154
155def dirname(p):
156 """Returns the directory component of a pathname"""
157 return split(p)[0]
158
159
160# Return the longest prefix of all list elements.
161
162def commonprefix(m):
163 "Given a list of pathnames, returns the longest common leading component"
164 if not m: return ''
165 prefix = m[0]
166 for item in m:
167 for i in range(len(prefix)):
168 if prefix[:i+1] != item[:i+1]:
169 prefix = prefix[:i]
170 if i == 0: return ''
171 break
172 return prefix
173
174
175# Get size, mtime, atime of files.
176
177def getsize(filename):
178 """Return the size of a file, reported by os.stat()"""
Raymond Hettinger32200ae2002-06-01 19:51:15 +0000179 return os.stat(filename).st_size
Andrew MacIntyre5cef5712002-02-24 05:32:32 +0000180
181def getmtime(filename):
182 """Return the last modification time of a file, reported by os.stat()"""
Raymond Hettinger32200ae2002-06-01 19:51:15 +0000183 return os.stat(filename).st_mtime
Andrew MacIntyre5cef5712002-02-24 05:32:32 +0000184
185def getatime(filename):
186 """Return the last access time of a file, reported by os.stat()"""
Raymond Hettinger32200ae2002-06-01 19:51:15 +0000187 return os.stat(filename).st_atime
Andrew MacIntyre5cef5712002-02-24 05:32:32 +0000188
Martin v. Löwis96a60e42002-12-31 13:11:54 +0000189def getctime(filename):
190 """Return the creation time of a file, reported by os.stat()."""
191 return os.stat(filename).st_ctime
Andrew MacIntyre5cef5712002-02-24 05:32:32 +0000192
193# Is a path a symbolic link?
194# This will always return false on systems where posix.lstat doesn't exist.
195
196def islink(path):
197 """Test for symbolic link. On OS/2 always returns false"""
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000198 return False
Andrew MacIntyre5cef5712002-02-24 05:32:32 +0000199
200
201# Does a path exist?
202# This is false for dangling symbolic links.
203
204def exists(path):
205 """Test whether a path exists"""
206 try:
207 st = os.stat(path)
208 except os.error:
Tim Petersbc0e9102002-04-04 22:55:58 +0000209 return False
210 return True
Andrew MacIntyre5cef5712002-02-24 05:32:32 +0000211
212
213# Is a path a directory?
214
215def isdir(path):
216 """Test whether a path is a directory"""
217 try:
218 st = os.stat(path)
219 except os.error:
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000220 return False
Raymond Hettinger32200ae2002-06-01 19:51:15 +0000221 return stat.S_ISDIR(st.st_mode)
Andrew MacIntyre5cef5712002-02-24 05:32:32 +0000222
223
224# Is a path a regular file?
225# This follows symbolic links, so both islink() and isdir() can be true
226# for the same path.
227
228def isfile(path):
229 """Test whether a path is a regular file"""
230 try:
231 st = os.stat(path)
232 except os.error:
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000233 return False
Raymond Hettinger32200ae2002-06-01 19:51:15 +0000234 return stat.S_ISREG(st.st_mode)
Andrew MacIntyre5cef5712002-02-24 05:32:32 +0000235
236
237# Is a path a mount point? Either a root (with or without drive letter)
238# or an UNC path with at most a / or \ after the mount point.
239
240def ismount(path):
241 """Test whether a path is a mount point (defined as root of drive)"""
242 unc, rest = splitunc(path)
243 if unc:
244 return rest in ("", "/", "\\")
245 p = splitdrive(path)[1]
246 return len(p) == 1 and p[0] in '/\\'
247
248
249# Directory tree walk.
250# For each directory under top (including top itself, but excluding
251# '.' and '..'), func(arg, dirname, filenames) is called, where
252# dirname is the name of the directory and filenames is the list
253# files files (and subdirectories etc.) in the directory.
254# The func may modify the filenames list, to implement a filter,
255# or to impose a different order of visiting.
256
257def walk(top, func, arg):
258 """Directory tree walk whth callback function.
259
260 walk(top, func, arg) calls func(arg, d, files) for each directory d
261 in the tree rooted at top (including top itself); files is a list
262 of all the files and subdirs in directory d."""
263 try:
264 names = os.listdir(top)
265 except os.error:
266 return
267 func(arg, top, names)
268 exceptions = ('.', '..')
269 for name in names:
270 if name not in exceptions:
271 name = join(top, name)
272 if isdir(name):
273 walk(name, func, arg)
274
275
276# Expand paths beginning with '~' or '~user'.
277# '~' means $HOME; '~user' means that user's home directory.
278# If the path doesn't begin with '~', or if the user or $HOME is unknown,
279# the path is returned unchanged (leaving error reporting to whatever
280# function is called with the expanded path as argument).
281# See also module 'glob' for expansion of *, ? and [...] in pathnames.
282# (A function should also be defined to do full *sh-style environment
283# variable expansion.)
284
285def expanduser(path):
286 """Expand ~ and ~user constructs.
287
288 If user or $HOME is unknown, do nothing."""
289 if path[:1] != '~':
290 return path
291 i, n = 1, len(path)
292 while i < n and path[i] not in '/\\':
293 i = i + 1
294 if i == 1:
Raymond Hettinger54f02222002-06-01 14:18:47 +0000295 if 'HOME' in os.environ:
Andrew MacIntyre5cef5712002-02-24 05:32:32 +0000296 userhome = os.environ['HOME']
Raymond Hettinger54f02222002-06-01 14:18:47 +0000297 elif not 'HOMEPATH' in os.environ:
Andrew MacIntyre5cef5712002-02-24 05:32:32 +0000298 return path
299 else:
300 try:
301 drive = os.environ['HOMEDRIVE']
302 except KeyError:
303 drive = ''
304 userhome = join(drive, os.environ['HOMEPATH'])
305 else:
306 return path
307 return userhome + path[i:]
308
309
310# Expand paths containing shell variable substitutions.
311# The following rules apply:
312# - no expansion within single quotes
313# - no escape character, except for '$$' which is translated into '$'
314# - ${varname} is accepted.
315# - varnames can be made out of letters, digits and the character '_'
316# XXX With COMMAND.COM you can use any characters in a variable name,
317# XXX except '^|<>='.
318
319def expandvars(path):
320 """Expand shell variables of form $var and ${var}.
321
322 Unknown variables are left unchanged."""
323 if '$' not in path:
324 return path
325 import string
326 varchars = string.letters + string.digits + '_-'
327 res = ''
328 index = 0
329 pathlen = len(path)
330 while index < pathlen:
331 c = path[index]
332 if c == '\'': # no expansion within single quotes
333 path = path[index + 1:]
334 pathlen = len(path)
335 try:
336 index = path.index('\'')
337 res = res + '\'' + path[:index + 1]
338 except ValueError:
339 res = res + path
340 index = pathlen - 1
341 elif c == '$': # variable or '$$'
342 if path[index + 1:index + 2] == '$':
343 res = res + c
344 index = index + 1
345 elif path[index + 1:index + 2] == '{':
346 path = path[index+2:]
347 pathlen = len(path)
348 try:
349 index = path.index('}')
350 var = path[:index]
Raymond Hettinger54f02222002-06-01 14:18:47 +0000351 if var in os.environ:
Andrew MacIntyre5cef5712002-02-24 05:32:32 +0000352 res = res + os.environ[var]
353 except ValueError:
354 res = res + path
355 index = pathlen - 1
356 else:
357 var = ''
358 index = index + 1
359 c = path[index:index + 1]
360 while c != '' and c in varchars:
361 var = var + c
362 index = index + 1
363 c = path[index:index + 1]
Raymond Hettinger54f02222002-06-01 14:18:47 +0000364 if var in os.environ:
Andrew MacIntyre5cef5712002-02-24 05:32:32 +0000365 res = res + os.environ[var]
366 if c != '':
367 res = res + c
368 else:
369 res = res + c
370 index = index + 1
371 return res
372
373
374# Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A/B.
375
376def normpath(path):
377 """Normalize path, eliminating double slashes, etc."""
378 path = path.replace('\\', '/')
379 prefix, path = splitdrive(path)
380 while path[:1] == '/':
381 prefix = prefix + '/'
382 path = path[1:]
383 comps = path.split('/')
384 i = 0
385 while i < len(comps):
386 if comps[i] == '.':
387 del comps[i]
388 elif comps[i] == '..' and i > 0 and comps[i-1] not in ('', '..'):
389 del comps[i-1:i+1]
390 i = i - 1
391 elif comps[i] == '' and i > 0 and comps[i-1] != '':
392 del comps[i]
393 else:
394 i = i + 1
395 # If the path is now empty, substitute '.'
396 if not prefix and not comps:
397 comps.append('.')
398 return prefix + '/'.join(comps)
399
400
401# Return an absolute path.
402def abspath(path):
403 """Return the absolute version of a path"""
404 if not isabs(path):
405 path = join(os.getcwd(), path)
406 return normpath(path)
Mark Hammond8696ebc2002-10-08 02:44:31 +0000407
Neal Norwitz61cdac62003-01-03 18:01:57 +0000408# realpath is a no-op on systems without islink support
409realpath = abspath
410
Mark Hammond8696ebc2002-10-08 02:44:31 +0000411supports_unicode_filenames = False