Update version number and release date.
[python/dscho.git] / Lib / os2emxpath.py
blob67f00df10c8724d926482753d585a8500891a5e6
1 # Module 'os2emxpath' -- common operations on OS/2 pathnames
2 """Common pathname manipulations, OS/2 EMX version.
4 Instead of importing this module directly, import os and refer to this
5 module as os.path.
6 """
8 import os
9 import stat
11 __all__ = ["normcase","isabs","join","splitdrive","split","splitext",
12 "basename","dirname","commonprefix","getsize","getmtime",
13 "getatime","getctime", "islink","exists","isdir","isfile","ismount",
14 "walk","expanduser","expandvars","normpath","abspath","splitunc",
15 "curdir","pardir","sep","pathsep","defpath","altsep","extsep",
16 "realpath","supports_unicode_filenames"]
18 # strings representing various path-related bits and pieces
19 curdir = '.'
20 pardir = '..'
21 extsep = '.'
22 sep = '/'
23 altsep = '\\'
24 pathsep = ';'
25 defpath = '.;C:\\bin'
27 # 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).
31 def normcase(s):
32 """Normalize case of pathname.
34 Makes all characters lowercase and all altseps into seps."""
35 return s.replace('\\', '/').lower()
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.
44 def isabs(s):
45 """Test whether a path is absolute"""
46 s = splitdrive(s)[1]
47 return s != '' and s[:1] in '/\\'
50 # Join two (or more) paths.
52 def 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
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
68 def 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
76 # Parse UNC paths
77 def splitunc(p):
78 """Split a pathname into UNC mount point and relative path specifiers.
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
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.
110 def split(p):
111 """Split a pathname.
113 Return tuple (head, tail) where tail is everything after the final slash.
114 Either part may be empty."""
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
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.
135 def splitext(p):
136 """Split the extension from a pathname.
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
156 # Return the tail (basename) part of a path.
158 def basename(p):
159 """Returns the final component of a pathname"""
160 return split(p)[1]
163 # Return the head (dirname) part of a path.
165 def dirname(p):
166 """Returns the directory component of a pathname"""
167 return split(p)[0]
170 # Return the longest prefix of all list elements.
172 def 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
185 # Get size, mtime, atime of files.
187 def getsize(filename):
188 """Return the size of a file, reported by os.stat()"""
189 return os.stat(filename).st_size
191 def getmtime(filename):
192 """Return the last modification time of a file, reported by os.stat()"""
193 return os.stat(filename).st_mtime
195 def getatime(filename):
196 """Return the last access time of a file, reported by os.stat()"""
197 return os.stat(filename).st_atime
199 def getctime(filename):
200 """Return the creation time of a file, reported by os.stat()."""
201 return os.stat(filename).st_ctime
203 # Is a path a symbolic link?
204 # This will always return false on systems where posix.lstat doesn't exist.
206 def islink(path):
207 """Test for symbolic link. On OS/2 always returns false"""
208 return False
211 # Does a path exist?
212 # This is false for dangling symbolic links.
214 def exists(path):
215 """Test whether a path exists"""
216 try:
217 st = os.stat(path)
218 except os.error:
219 return False
220 return True
223 # Is a path a directory?
225 def isdir(path):
226 """Test whether a path is a directory"""
227 try:
228 st = os.stat(path)
229 except os.error:
230 return False
231 return stat.S_ISDIR(st.st_mode)
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.
238 def isfile(path):
239 """Test whether a path is a regular file"""
240 try:
241 st = os.stat(path)
242 except os.error:
243 return False
244 return stat.S_ISREG(st.st_mode)
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.
250 def 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 '/\\'
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.
267 def walk(top, func, arg):
268 """Directory tree walk whth callback function.
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)
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.)
295 def expanduser(path):
296 """Expand ~ and ~user constructs.
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:
305 if 'HOME' in os.environ:
306 userhome = os.environ['HOME']
307 elif not 'HOMEPATH' in os.environ:
308 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:]
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 '^|<>='.
329 def expandvars(path):
330 """Expand shell variables of form $var and ${var}.
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]
361 if var in os.environ:
362 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]
374 if var in os.environ:
375 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
384 # Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A/B.
386 def 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)
411 # Return an absolute path.
412 def 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)
418 # realpath is a no-op on systems without islink support
419 realpath = abspath
421 supports_unicode_filenames = False