blob: a956c09269c989ab6f708e4b4fd7fcf4a23dacd3 [file] [log] [blame]
Guido van Rossum3ed23cc1994-02-15 15:57:15 +00001# Module 'dospath' -- common operations on DOS pathnames
2
3import os
4import stat
5import string
6
7
8# Normalize the case of a pathname.
9# On MS-DOS it maps the pathname to lowercase, turns slashes into
Guido van Rossumfda5c1a1995-08-10 19:27:42 +000010# backslashes.
Guido van Rossum3ed23cc1994-02-15 15:57:15 +000011# Other normalizations (such as optimizing '../' away) are not allowed
12# (this is done by normpath).
Guido van Rossumfda5c1a1995-08-10 19:27:42 +000013# Previously, this version mapped invalid consecutive characters to a
14# single '_', but this has been removed. This functionality should
15# possibly be added as a new function.
Guido van Rossum3ed23cc1994-02-15 15:57:15 +000016
17def normcase(s):
Guido van Rossum0d530ce1998-02-19 21:08:36 +000018 return string.lower(string.replace(s, "/", "\\"))
Guido van Rossum3ed23cc1994-02-15 15:57:15 +000019
20
21# Return wheter a path is absolute.
22# Trivial in Posix, harder on the Mac or MS-DOS.
23# For DOS it is absolute if it starts with a slash or backslash (current
24# volume), or if a pathname after the volume letter and colon starts with
25# a slash or backslash.
26
27def isabs(s):
28 s = splitdrive(s)[1]
29 return s != '' and s[:1] in '/\\'
30
31
Guido van Rossumae590db1997-10-07 14:48:23 +000032# Join two (or more) paths.
Guido van Rossum3ed23cc1994-02-15 15:57:15 +000033
Guido van Rossumae590db1997-10-07 14:48:23 +000034def join(a, *p):
35 path = a
36 for b in p:
37 if isabs(b):
38 path = b
39 elif path == '' or path[-1:] in '/\\':
40 path = path + b
41 else:
42 path = path + os.sep + b
43 return path
Guido van Rossum3ed23cc1994-02-15 15:57:15 +000044
45
46# Split a path in a drive specification (a drive letter followed by a
47# colon) and the path specification.
48# It is always true that drivespec + pathspec == p
Guido van Rossumfda5c1a1995-08-10 19:27:42 +000049
Guido van Rossum3ed23cc1994-02-15 15:57:15 +000050def splitdrive(p):
51 if p[1:2] == ':':
52 return p[0:2], p[2:]
53 return '', p
54
55
56# Split a path in head (everything up to the last '/') and tail (the
57# rest). If the original path ends in '/' but is not the root, this
58# '/' is stripped. After the trailing '/' is stripped, the invariant
59# join(head, tail) == p holds.
60# The resulting head won't end in '/' unless it is the root.
61
62def split(p):
63 d, p = splitdrive(p)
64 slashes = ''
65 while p and p[-1:] in '/\\':
66 slashes = slashes + p[-1]
67 p = p[:-1]
68 if p == '':
69 p = p + slashes
70 head, tail = '', ''
71 for c in p:
72 tail = tail + c
73 if c in '/\\':
74 head, tail = head + tail, ''
75 slashes = ''
76 while head and head[-1:] in '/\\':
77 slashes = slashes + head[-1]
78 head = head[:-1]
79 if head == '':
80 head = head + slashes
81 return d + head, tail
82
83
84# Split a path in root and extension.
85# The extension is everything starting at the first dot in the last
86# pathname component; the root is everything before that.
87# It is always true that root + ext == p.
88
89def splitext(p):
90 root, ext = '', ''
91 for c in p:
92 if c in '/\\':
93 root, ext = root + ext + c, ''
94 elif c == '.' or ext:
95 ext = ext + c
96 else:
97 root = root + c
98 return root, ext
99
100
101# Return the tail (basename) part of a path.
102
103def basename(p):
104 return split(p)[1]
105
106
107# Return the head (dirname) part of a path.
108
109def dirname(p):
110 return split(p)[0]
111
112
113# Return the longest prefix of all list elements.
114
115def commonprefix(m):
116 if not m: return ''
117 prefix = m[0]
118 for item in m:
119 for i in range(len(prefix)):
120 if prefix[:i+1] <> item[:i+1]:
121 prefix = prefix[:i]
122 if i == 0: return ''
123 break
124 return prefix
125
126
Guido van Rossum2bc1f8f1998-07-24 20:49:26 +0000127# Get size, mtime, atime of files.
128
129def getsize(filename):
130 """Return the size of a file, reported by os.stat()."""
131 st = os.stat(filename)
132 return st[stat.ST_SIZE]
133
134def getmtime(filename):
135 """Return the last modification time of a file, reported by os.stat()."""
136 st = os.stat(filename)
137 return st[stat.ST_MTIME]
138
139def getatime(filename):
140 """Return the last access time of a file, reported by os.stat()."""
141 st = os.stat(filename)
142 return st[stat.ST_MTIME]
143
144
Guido van Rossum3ed23cc1994-02-15 15:57:15 +0000145# Is a path a symbolic link?
146# This will always return false on systems where posix.lstat doesn't exist.
147
148def islink(path):
Guido van Rossumbfa9f131997-11-04 18:40:53 +0000149 return 0
Guido van Rossum3ed23cc1994-02-15 15:57:15 +0000150
151
152# Does a path exist?
153# This is false for dangling symbolic links.
154
155def exists(path):
156 try:
157 st = os.stat(path)
158 except os.error:
159 return 0
160 return 1
161
162
163# Is a path a dos directory?
164# This follows symbolic links, so both islink() and isdir() can be true
165# for the same path.
166
167def isdir(path):
168 try:
169 st = os.stat(path)
170 except os.error:
171 return 0
172 return stat.S_ISDIR(st[stat.ST_MODE])
173
174
175# Is a path a regular file?
176# This follows symbolic links, so both islink() and isdir() can be true
177# for the same path.
178
179def isfile(path):
180 try:
181 st = os.stat(path)
182 except os.error:
183 return 0
184 return stat.S_ISREG(st[stat.ST_MODE])
185
186
Guido van Rossum3ed23cc1994-02-15 15:57:15 +0000187# Is a path a mount point?
188# XXX This degenerates in: 'is this the root?' on DOS
189
190def ismount(path):
191 return isabs(splitdrive(path)[1])
192
193
194# Directory tree walk.
195# For each directory under top (including top itself, but excluding
196# '.' and '..'), func(arg, dirname, filenames) is called, where
197# dirname is the name of the directory and filenames is the list
198# files files (and subdirectories etc.) in the directory.
199# The func may modify the filenames list, to implement a filter,
200# or to impose a different order of visiting.
201
202def walk(top, func, arg):
203 try:
204 names = os.listdir(top)
205 except os.error:
206 return
207 func(arg, top, names)
208 exceptions = ('.', '..')
209 for name in names:
210 if name not in exceptions:
211 name = join(top, name)
212 if isdir(name):
213 walk(name, func, arg)
214
215
216# Expand paths beginning with '~' or '~user'.
217# '~' means $HOME; '~user' means that user's home directory.
218# If the path doesn't begin with '~', or if the user or $HOME is unknown,
219# the path is returned unchanged (leaving error reporting to whatever
220# function is called with the expanded path as argument).
221# See also module 'glob' for expansion of *, ? and [...] in pathnames.
222# (A function should also be defined to do full *sh-style environment
223# variable expansion.)
224
225def expanduser(path):
226 if path[:1] <> '~':
227 return path
228 i, n = 1, len(path)
229 while i < n and path[i] not in '/\\':
230 i = i+1
231 if i == 1:
232 if not os.environ.has_key('HOME'):
233 return path
234 userhome = os.environ['HOME']
235 else:
236 return path
237 return userhome + path[i:]
238
239
240# Expand paths containing shell variable substitutions.
241# The following rules apply:
242# - no expansion within single quotes
243# - no escape character, except for '$$' which is translated into '$'
244# - ${varname} is accepted.
245# - varnames can be made out of letters, digits and the character '_'
246# XXX With COMMAND.COM you can use any characters in a variable name,
247# XXX except '^|<>='.
248
249varchars = string.letters + string.digits + '_-'
250
251def expandvars(path):
252 if '$' not in path:
253 return path
254 res = ''
255 index = 0
256 pathlen = len(path)
257 while index < pathlen:
258 c = path[index]
259 if c == '\'': # no expansion within single quotes
260 path = path[index + 1:]
261 pathlen = len(path)
262 try:
263 index = string.index(path, '\'')
264 res = res + '\'' + path[:index + 1]
265 except string.index_error:
266 res = res + path
267 index = pathlen -1
268 elif c == '$': # variable or '$$'
269 if path[index + 1:index + 2] == '$':
270 res = res + c
271 index = index + 1
272 elif path[index + 1:index + 2] == '{':
273 path = path[index+2:]
274 pathlen = len(path)
275 try:
276 index = string.index(path, '}')
277 var = path[:index]
278 if os.environ.has_key(var):
279 res = res + os.environ[var]
280 except string.index_error:
281 res = res + path
282 index = pathlen - 1
283 else:
284 var = ''
285 index = index + 1
286 c = path[index:index + 1]
287 while c != '' and c in varchars:
288 var = var + c
289 index = index + 1
290 c = path[index:index + 1]
291 if os.environ.has_key(var):
292 res = res + os.environ[var]
293 if c != '':
294 res = res + c
295 else:
296 res = res + c
297 index = index + 1
298 return res
299
300
301# Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A/B.
302# Also, components of the path are silently truncated to 8+3 notation.
303
304def normpath(path):
Guido van Rossum0d530ce1998-02-19 21:08:36 +0000305 path = string.replace(path, "/", "\\")
Guido van Rossum3ed23cc1994-02-15 15:57:15 +0000306 prefix, path = splitdrive(path)
307 while path[:1] == os.sep:
308 prefix = prefix + os.sep
309 path = path[1:]
310 comps = string.splitfields(path, os.sep)
311 i = 0
312 while i < len(comps):
313 if comps[i] == '.':
314 del comps[i]
315 elif comps[i] == '..' and i > 0 and \
316 comps[i-1] not in ('', '..'):
317 del comps[i-1:i+1]
318 i = i-1
319 elif comps[i] == '' and i > 0 and comps[i-1] <> '':
320 del comps[i]
321 elif '.' in comps[i]:
322 comp = string.splitfields(comps[i], '.')
323 comps[i] = comp[0][:8] + '.' + comp[1][:3]
324 i = i+1
325 elif len(comps[i]) > 8:
326 comps[i] = comps[i][:8]
327 i = i+1
328 else:
329 i = i+1
330 # If the path is now empty, substitute '.'
331 if not prefix and not comps:
332 comps.append('.')
333 return prefix + string.joinfields(comps, os.sep)
334