Results of a rewrite pass
[python/dscho.git] / Lib / os2emxpath.py
blob0315da027fa4d7ac87c351ae0e8d7cd7be36882f
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 "supports_unicode_filenames"]
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).
21 def normcase(s):
22 """Normalize case of pathname.
24 Makes all characters lowercase and all altseps into seps."""
25 return s.replace('\\', '/').lower()
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.
34 def isabs(s):
35 """Test whether a path is absolute"""
36 s = splitdrive(s)[1]
37 return s != '' and s[:1] in '/\\'
40 # Join two (or more) paths.
42 def 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
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
58 def 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
66 # Parse UNC paths
67 def splitunc(p):
68 """Split a pathname into UNC mount point and relative path specifiers.
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
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.
100 def split(p):
101 """Split a pathname.
103 Return tuple (head, tail) where tail is everything after the final slash.
104 Either part may be empty."""
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
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.
125 def splitext(p):
126 """Split the extension from a pathname.
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
146 # Return the tail (basename) part of a path.
148 def basename(p):
149 """Returns the final component of a pathname"""
150 return split(p)[1]
153 # Return the head (dirname) part of a path.
155 def dirname(p):
156 """Returns the directory component of a pathname"""
157 return split(p)[0]
160 # Return the longest prefix of all list elements.
162 def 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
175 # Get size, mtime, atime of files.
177 def getsize(filename):
178 """Return the size of a file, reported by os.stat()"""
179 return os.stat(filename).st_size
181 def getmtime(filename):
182 """Return the last modification time of a file, reported by os.stat()"""
183 return os.stat(filename).st_mtime
185 def getatime(filename):
186 """Return the last access time of a file, reported by os.stat()"""
187 return os.stat(filename).st_atime
189 def getctime(filename):
190 """Return the creation time of a file, reported by os.stat()."""
191 return os.stat(filename).st_ctime
193 # Is a path a symbolic link?
194 # This will always return false on systems where posix.lstat doesn't exist.
196 def islink(path):
197 """Test for symbolic link. On OS/2 always returns false"""
198 return False
201 # Does a path exist?
202 # This is false for dangling symbolic links.
204 def exists(path):
205 """Test whether a path exists"""
206 try:
207 st = os.stat(path)
208 except os.error:
209 return False
210 return True
213 # Is a path a directory?
215 def isdir(path):
216 """Test whether a path is a directory"""
217 try:
218 st = os.stat(path)
219 except os.error:
220 return False
221 return stat.S_ISDIR(st.st_mode)
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.
228 def isfile(path):
229 """Test whether a path is a regular file"""
230 try:
231 st = os.stat(path)
232 except os.error:
233 return False
234 return stat.S_ISREG(st.st_mode)
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.
240 def 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 '/\\'
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.
257 def walk(top, func, arg):
258 """Directory tree walk whth callback function.
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)
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.)
285 def expanduser(path):
286 """Expand ~ and ~user constructs.
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:
295 if 'HOME' in os.environ:
296 userhome = os.environ['HOME']
297 elif not 'HOMEPATH' in os.environ:
298 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:]
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 '^|<>='.
319 def expandvars(path):
320 """Expand shell variables of form $var and ${var}.
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]
351 if var in os.environ:
352 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]
364 if var in os.environ:
365 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
374 # Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A/B.
376 def 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)
401 # Return an absolute path.
402 def 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)
408 supports_unicode_filenames = False