blob: 616d474c65c539bf6a3d2a2e304875ccb1a33b7c [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",
13 "getatime","islink","exists","isdir","isfile","ismount",
Mark Hammond8696ebc2002-10-08 02:44:31 +000014 "walk","expanduser","expandvars","normpath","abspath","splitunc",
15 "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
189
190# Is a path a symbolic link?
191# This will always return false on systems where posix.lstat doesn't exist.
192
193def islink(path):
194 """Test for symbolic link. On OS/2 always returns false"""
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000195 return False
Andrew MacIntyre5cef5712002-02-24 05:32:32 +0000196
197
198# Does a path exist?
199# This is false for dangling symbolic links.
200
201def exists(path):
202 """Test whether a path exists"""
203 try:
204 st = os.stat(path)
205 except os.error:
Tim Petersbc0e9102002-04-04 22:55:58 +0000206 return False
207 return True
Andrew MacIntyre5cef5712002-02-24 05:32:32 +0000208
209
210# Is a path a directory?
211
212def isdir(path):
213 """Test whether a path is a directory"""
214 try:
215 st = os.stat(path)
216 except os.error:
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000217 return False
Raymond Hettinger32200ae2002-06-01 19:51:15 +0000218 return stat.S_ISDIR(st.st_mode)
Andrew MacIntyre5cef5712002-02-24 05:32:32 +0000219
220
221# Is a path a regular file?
222# This follows symbolic links, so both islink() and isdir() can be true
223# for the same path.
224
225def isfile(path):
226 """Test whether a path is a regular file"""
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_ISREG(st.st_mode)
Andrew MacIntyre5cef5712002-02-24 05:32:32 +0000232
233
234# Is a path a mount point? Either a root (with or without drive letter)
235# or an UNC path with at most a / or \ after the mount point.
236
237def ismount(path):
238 """Test whether a path is a mount point (defined as root of drive)"""
239 unc, rest = splitunc(path)
240 if unc:
241 return rest in ("", "/", "\\")
242 p = splitdrive(path)[1]
243 return len(p) == 1 and p[0] in '/\\'
244
245
246# Directory tree walk.
247# For each directory under top (including top itself, but excluding
248# '.' and '..'), func(arg, dirname, filenames) is called, where
249# dirname is the name of the directory and filenames is the list
250# files files (and subdirectories etc.) in the directory.
251# The func may modify the filenames list, to implement a filter,
252# or to impose a different order of visiting.
253
254def walk(top, func, arg):
255 """Directory tree walk whth callback function.
256
257 walk(top, func, arg) calls func(arg, d, files) for each directory d
258 in the tree rooted at top (including top itself); files is a list
259 of all the files and subdirs in directory d."""
260 try:
261 names = os.listdir(top)
262 except os.error:
263 return
264 func(arg, top, names)
265 exceptions = ('.', '..')
266 for name in names:
267 if name not in exceptions:
268 name = join(top, name)
269 if isdir(name):
270 walk(name, func, arg)
271
272
273# Expand paths beginning with '~' or '~user'.
274# '~' means $HOME; '~user' means that user's home directory.
275# If the path doesn't begin with '~', or if the user or $HOME is unknown,
276# the path is returned unchanged (leaving error reporting to whatever
277# function is called with the expanded path as argument).
278# See also module 'glob' for expansion of *, ? and [...] in pathnames.
279# (A function should also be defined to do full *sh-style environment
280# variable expansion.)
281
282def expanduser(path):
283 """Expand ~ and ~user constructs.
284
285 If user or $HOME is unknown, do nothing."""
286 if path[:1] != '~':
287 return path
288 i, n = 1, len(path)
289 while i < n and path[i] not in '/\\':
290 i = i + 1
291 if i == 1:
Raymond Hettinger54f02222002-06-01 14:18:47 +0000292 if 'HOME' in os.environ:
Andrew MacIntyre5cef5712002-02-24 05:32:32 +0000293 userhome = os.environ['HOME']
Raymond Hettinger54f02222002-06-01 14:18:47 +0000294 elif not 'HOMEPATH' in os.environ:
Andrew MacIntyre5cef5712002-02-24 05:32:32 +0000295 return path
296 else:
297 try:
298 drive = os.environ['HOMEDRIVE']
299 except KeyError:
300 drive = ''
301 userhome = join(drive, os.environ['HOMEPATH'])
302 else:
303 return path
304 return userhome + path[i:]
305
306
307# Expand paths containing shell variable substitutions.
308# The following rules apply:
309# - no expansion within single quotes
310# - no escape character, except for '$$' which is translated into '$'
311# - ${varname} is accepted.
312# - varnames can be made out of letters, digits and the character '_'
313# XXX With COMMAND.COM you can use any characters in a variable name,
314# XXX except '^|<>='.
315
316def expandvars(path):
317 """Expand shell variables of form $var and ${var}.
318
319 Unknown variables are left unchanged."""
320 if '$' not in path:
321 return path
322 import string
323 varchars = string.letters + string.digits + '_-'
324 res = ''
325 index = 0
326 pathlen = len(path)
327 while index < pathlen:
328 c = path[index]
329 if c == '\'': # no expansion within single quotes
330 path = path[index + 1:]
331 pathlen = len(path)
332 try:
333 index = path.index('\'')
334 res = res + '\'' + path[:index + 1]
335 except ValueError:
336 res = res + path
337 index = pathlen - 1
338 elif c == '$': # variable or '$$'
339 if path[index + 1:index + 2] == '$':
340 res = res + c
341 index = index + 1
342 elif path[index + 1:index + 2] == '{':
343 path = path[index+2:]
344 pathlen = len(path)
345 try:
346 index = path.index('}')
347 var = path[:index]
Raymond Hettinger54f02222002-06-01 14:18:47 +0000348 if var in os.environ:
Andrew MacIntyre5cef5712002-02-24 05:32:32 +0000349 res = res + os.environ[var]
350 except ValueError:
351 res = res + path
352 index = pathlen - 1
353 else:
354 var = ''
355 index = index + 1
356 c = path[index:index + 1]
357 while c != '' and c in varchars:
358 var = var + c
359 index = index + 1
360 c = path[index:index + 1]
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 if c != '':
364 res = res + c
365 else:
366 res = res + c
367 index = index + 1
368 return res
369
370
371# Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A/B.
372
373def normpath(path):
374 """Normalize path, eliminating double slashes, etc."""
375 path = path.replace('\\', '/')
376 prefix, path = splitdrive(path)
377 while path[:1] == '/':
378 prefix = prefix + '/'
379 path = path[1:]
380 comps = path.split('/')
381 i = 0
382 while i < len(comps):
383 if comps[i] == '.':
384 del comps[i]
385 elif comps[i] == '..' and i > 0 and comps[i-1] not in ('', '..'):
386 del comps[i-1:i+1]
387 i = i - 1
388 elif comps[i] == '' and i > 0 and comps[i-1] != '':
389 del comps[i]
390 else:
391 i = i + 1
392 # If the path is now empty, substitute '.'
393 if not prefix and not comps:
394 comps.append('.')
395 return prefix + '/'.join(comps)
396
397
398# Return an absolute path.
399def abspath(path):
400 """Return the absolute version of a path"""
401 if not isabs(path):
402 path = join(os.getcwd(), path)
403 return normpath(path)
Mark Hammond8696ebc2002-10-08 02:44:31 +0000404
405supports_unicode_filenames = False