blob: 725b38149520652f8796eeb15603b8a9771acf33 [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):
18 res, s = splitdrive(s)
19 for c in s:
20 if c in '/\\':
21 res = res + os.sep
Guido van Rossum3ed23cc1994-02-15 15:57:15 +000022 else:
23 res = res + c
24 return string.lower(res)
25
26
27# Return wheter a path is absolute.
28# Trivial in Posix, harder on the Mac or MS-DOS.
29# For DOS it is absolute if it starts with a slash or backslash (current
30# volume), or if a pathname after the volume letter and colon starts with
31# a slash or backslash.
32
33def isabs(s):
34 s = splitdrive(s)[1]
35 return s != '' and s[:1] in '/\\'
36
37
38# Join two pathnames.
39# Ignore the first part if the second part is absolute.
40# Insert a '/' unless the first part is empty or already ends in '/'.
41
42def join(a, b):
43 if isabs(b): return b
44 if a == '' or a[-1:] in '/\\': return a + b
45 # Note: join('x', '') returns 'x/'; is this what we want?
46 return a + os.sep + b
47
48
49# Split a path in a drive specification (a drive letter followed by a
50# colon) and the path specification.
51# It is always true that drivespec + pathspec == p
Guido van Rossumfda5c1a1995-08-10 19:27:42 +000052
Guido van Rossum3ed23cc1994-02-15 15:57:15 +000053def splitdrive(p):
54 if p[1:2] == ':':
55 return p[0:2], p[2:]
56 return '', p
57
58
59# Split a path in head (everything up to the last '/') and tail (the
60# rest). If the original path ends in '/' but is not the root, this
61# '/' is stripped. After the trailing '/' is stripped, the invariant
62# join(head, tail) == p holds.
63# The resulting head won't end in '/' unless it is the root.
64
65def split(p):
66 d, p = splitdrive(p)
67 slashes = ''
68 while p and p[-1:] in '/\\':
69 slashes = slashes + p[-1]
70 p = p[:-1]
71 if p == '':
72 p = p + slashes
73 head, tail = '', ''
74 for c in p:
75 tail = tail + c
76 if c in '/\\':
77 head, tail = head + tail, ''
78 slashes = ''
79 while head and head[-1:] in '/\\':
80 slashes = slashes + head[-1]
81 head = head[:-1]
82 if head == '':
83 head = head + slashes
84 return d + head, tail
85
86
87# Split a path in root and extension.
88# The extension is everything starting at the first dot in the last
89# pathname component; the root is everything before that.
90# It is always true that root + ext == p.
91
92def splitext(p):
93 root, ext = '', ''
94 for c in p:
95 if c in '/\\':
96 root, ext = root + ext + c, ''
97 elif c == '.' or ext:
98 ext = ext + c
99 else:
100 root = root + c
101 return root, ext
102
103
104# Return the tail (basename) part of a path.
105
106def basename(p):
107 return split(p)[1]
108
109
110# Return the head (dirname) part of a path.
111
112def dirname(p):
113 return split(p)[0]
114
115
116# Return the longest prefix of all list elements.
117
118def commonprefix(m):
119 if not m: return ''
120 prefix = m[0]
121 for item in m:
122 for i in range(len(prefix)):
123 if prefix[:i+1] <> item[:i+1]:
124 prefix = prefix[:i]
125 if i == 0: return ''
126 break
127 return prefix
128
129
130# Is a path a symbolic link?
131# This will always return false on systems where posix.lstat doesn't exist.
132
133def islink(path):
134 return false
135
136
137# Does a path exist?
138# This is false for dangling symbolic links.
139
140def exists(path):
141 try:
142 st = os.stat(path)
143 except os.error:
144 return 0
145 return 1
146
147
148# Is a path a dos directory?
149# This follows symbolic links, so both islink() and isdir() can be true
150# for the same path.
151
152def isdir(path):
153 try:
154 st = os.stat(path)
155 except os.error:
156 return 0
157 return stat.S_ISDIR(st[stat.ST_MODE])
158
159
160# Is a path a regular file?
161# This follows symbolic links, so both islink() and isdir() can be true
162# for the same path.
163
164def isfile(path):
165 try:
166 st = os.stat(path)
167 except os.error:
168 return 0
169 return stat.S_ISREG(st[stat.ST_MODE])
170
171
172# Are two filenames really pointing to the same file?
173
174def samefile(f1, f2):
175 s1 = os.stat(f1)
176 s2 = os.stat(f2)
177 return samestat(s1, s2)
178
179
180# Are two open files really referencing the same file?
181# (Not necessarily the same file descriptor!)
182# XXX THIS IS BROKEN UNDER DOS! ST_INO seems to indicate number of reads?
183
184def sameopenfile(fp1, fp2):
185 s1 = os.fstat(fp1.fileno())
186 s2 = os.fstat(fp2.fileno())
187 return samestat(s1, s2)
188
189
190# Are two stat buffers (obtained from stat, fstat or lstat)
191# describing the same file?
192
193def samestat(s1, s2):
194 return s1[stat.ST_INO] == s2[stat.ST_INO] and \
195 s1[stat.ST_DEV] == s2[stat.ST_DEV]
196
197
198# Is a path a mount point?
199# XXX This degenerates in: 'is this the root?' on DOS
200
201def ismount(path):
202 return isabs(splitdrive(path)[1])
203
204
205# Directory tree walk.
206# For each directory under top (including top itself, but excluding
207# '.' and '..'), func(arg, dirname, filenames) is called, where
208# dirname is the name of the directory and filenames is the list
209# files files (and subdirectories etc.) in the directory.
210# The func may modify the filenames list, to implement a filter,
211# or to impose a different order of visiting.
212
213def walk(top, func, arg):
214 try:
215 names = os.listdir(top)
216 except os.error:
217 return
218 func(arg, top, names)
219 exceptions = ('.', '..')
220 for name in names:
221 if name not in exceptions:
222 name = join(top, name)
223 if isdir(name):
224 walk(name, func, arg)
225
226
227# Expand paths beginning with '~' or '~user'.
228# '~' means $HOME; '~user' means that user's home directory.
229# If the path doesn't begin with '~', or if the user or $HOME is unknown,
230# the path is returned unchanged (leaving error reporting to whatever
231# function is called with the expanded path as argument).
232# See also module 'glob' for expansion of *, ? and [...] in pathnames.
233# (A function should also be defined to do full *sh-style environment
234# variable expansion.)
235
236def expanduser(path):
237 if path[:1] <> '~':
238 return path
239 i, n = 1, len(path)
240 while i < n and path[i] not in '/\\':
241 i = i+1
242 if i == 1:
243 if not os.environ.has_key('HOME'):
244 return path
245 userhome = os.environ['HOME']
246 else:
247 return path
248 return userhome + path[i:]
249
250
251# Expand paths containing shell variable substitutions.
252# The following rules apply:
253# - no expansion within single quotes
254# - no escape character, except for '$$' which is translated into '$'
255# - ${varname} is accepted.
256# - varnames can be made out of letters, digits and the character '_'
257# XXX With COMMAND.COM you can use any characters in a variable name,
258# XXX except '^|<>='.
259
260varchars = string.letters + string.digits + '_-'
261
262def expandvars(path):
263 if '$' not in path:
264 return path
265 res = ''
266 index = 0
267 pathlen = len(path)
268 while index < pathlen:
269 c = path[index]
270 if c == '\'': # no expansion within single quotes
271 path = path[index + 1:]
272 pathlen = len(path)
273 try:
274 index = string.index(path, '\'')
275 res = res + '\'' + path[:index + 1]
276 except string.index_error:
277 res = res + path
278 index = pathlen -1
279 elif c == '$': # variable or '$$'
280 if path[index + 1:index + 2] == '$':
281 res = res + c
282 index = index + 1
283 elif path[index + 1:index + 2] == '{':
284 path = path[index+2:]
285 pathlen = len(path)
286 try:
287 index = string.index(path, '}')
288 var = path[:index]
289 if os.environ.has_key(var):
290 res = res + os.environ[var]
291 except string.index_error:
292 res = res + path
293 index = pathlen - 1
294 else:
295 var = ''
296 index = index + 1
297 c = path[index:index + 1]
298 while c != '' and c in varchars:
299 var = var + c
300 index = index + 1
301 c = path[index:index + 1]
302 if os.environ.has_key(var):
303 res = res + os.environ[var]
304 if c != '':
305 res = res + c
306 else:
307 res = res + c
308 index = index + 1
309 return res
310
311
312# Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A/B.
313# Also, components of the path are silently truncated to 8+3 notation.
314
315def normpath(path):
316 path = normcase(path)
317 prefix, path = splitdrive(path)
318 while path[:1] == os.sep:
319 prefix = prefix + os.sep
320 path = path[1:]
321 comps = string.splitfields(path, os.sep)
322 i = 0
323 while i < len(comps):
324 if comps[i] == '.':
325 del comps[i]
326 elif comps[i] == '..' and i > 0 and \
327 comps[i-1] not in ('', '..'):
328 del comps[i-1:i+1]
329 i = i-1
330 elif comps[i] == '' and i > 0 and comps[i-1] <> '':
331 del comps[i]
332 elif '.' in comps[i]:
333 comp = string.splitfields(comps[i], '.')
334 comps[i] = comp[0][:8] + '.' + comp[1][:3]
335 i = i+1
336 elif len(comps[i]) > 8:
337 comps[i] = comps[i][:8]
338 i = i+1
339 else:
340 i = i+1
341 # If the path is now empty, substitute '.'
342 if not prefix and not comps:
343 comps.append('.')
344 return prefix + string.joinfields(comps, os.sep)
345