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