blob: 5dbda89540663bb1b0eee86c31b94e32cf99f850 [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
127# Is a path a symbolic link?
128# This will always return false on systems where posix.lstat doesn't exist.
129
130def islink(path):
Guido van Rossumbfa9f131997-11-04 18:40:53 +0000131 return 0
Guido van Rossum3ed23cc1994-02-15 15:57:15 +0000132
133
134# Does a path exist?
135# This is false for dangling symbolic links.
136
137def exists(path):
138 try:
139 st = os.stat(path)
140 except os.error:
141 return 0
142 return 1
143
144
145# Is a path a dos directory?
146# This follows symbolic links, so both islink() and isdir() can be true
147# for the same path.
148
149def isdir(path):
150 try:
151 st = os.stat(path)
152 except os.error:
153 return 0
154 return stat.S_ISDIR(st[stat.ST_MODE])
155
156
157# Is a path a regular file?
158# This follows symbolic links, so both islink() and isdir() can be true
159# for the same path.
160
161def isfile(path):
162 try:
163 st = os.stat(path)
164 except os.error:
165 return 0
166 return stat.S_ISREG(st[stat.ST_MODE])
167
168
Guido van Rossum3ed23cc1994-02-15 15:57:15 +0000169# Is a path a mount point?
170# XXX This degenerates in: 'is this the root?' on DOS
171
172def ismount(path):
173 return isabs(splitdrive(path)[1])
174
175
176# Directory tree walk.
177# For each directory under top (including top itself, but excluding
178# '.' and '..'), func(arg, dirname, filenames) is called, where
179# dirname is the name of the directory and filenames is the list
180# files files (and subdirectories etc.) in the directory.
181# The func may modify the filenames list, to implement a filter,
182# or to impose a different order of visiting.
183
184def walk(top, func, arg):
185 try:
186 names = os.listdir(top)
187 except os.error:
188 return
189 func(arg, top, names)
190 exceptions = ('.', '..')
191 for name in names:
192 if name not in exceptions:
193 name = join(top, name)
194 if isdir(name):
195 walk(name, func, arg)
196
197
198# Expand paths beginning with '~' or '~user'.
199# '~' means $HOME; '~user' means that user's home directory.
200# If the path doesn't begin with '~', or if the user or $HOME is unknown,
201# the path is returned unchanged (leaving error reporting to whatever
202# function is called with the expanded path as argument).
203# See also module 'glob' for expansion of *, ? and [...] in pathnames.
204# (A function should also be defined to do full *sh-style environment
205# variable expansion.)
206
207def expanduser(path):
208 if path[:1] <> '~':
209 return path
210 i, n = 1, len(path)
211 while i < n and path[i] not in '/\\':
212 i = i+1
213 if i == 1:
214 if not os.environ.has_key('HOME'):
215 return path
216 userhome = os.environ['HOME']
217 else:
218 return path
219 return userhome + path[i:]
220
221
222# Expand paths containing shell variable substitutions.
223# The following rules apply:
224# - no expansion within single quotes
225# - no escape character, except for '$$' which is translated into '$'
226# - ${varname} is accepted.
227# - varnames can be made out of letters, digits and the character '_'
228# XXX With COMMAND.COM you can use any characters in a variable name,
229# XXX except '^|<>='.
230
231varchars = string.letters + string.digits + '_-'
232
233def expandvars(path):
234 if '$' not in path:
235 return path
236 res = ''
237 index = 0
238 pathlen = len(path)
239 while index < pathlen:
240 c = path[index]
241 if c == '\'': # no expansion within single quotes
242 path = path[index + 1:]
243 pathlen = len(path)
244 try:
245 index = string.index(path, '\'')
246 res = res + '\'' + path[:index + 1]
247 except string.index_error:
248 res = res + path
249 index = pathlen -1
250 elif c == '$': # variable or '$$'
251 if path[index + 1:index + 2] == '$':
252 res = res + c
253 index = index + 1
254 elif path[index + 1:index + 2] == '{':
255 path = path[index+2:]
256 pathlen = len(path)
257 try:
258 index = string.index(path, '}')
259 var = path[:index]
260 if os.environ.has_key(var):
261 res = res + os.environ[var]
262 except string.index_error:
263 res = res + path
264 index = pathlen - 1
265 else:
266 var = ''
267 index = index + 1
268 c = path[index:index + 1]
269 while c != '' and c in varchars:
270 var = var + c
271 index = index + 1
272 c = path[index:index + 1]
273 if os.environ.has_key(var):
274 res = res + os.environ[var]
275 if c != '':
276 res = res + c
277 else:
278 res = res + c
279 index = index + 1
280 return res
281
282
283# Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A/B.
284# Also, components of the path are silently truncated to 8+3 notation.
285
286def normpath(path):
Guido van Rossum0d530ce1998-02-19 21:08:36 +0000287 path = string.replace(path, "/", "\\")
Guido van Rossum3ed23cc1994-02-15 15:57:15 +0000288 prefix, path = splitdrive(path)
289 while path[:1] == os.sep:
290 prefix = prefix + os.sep
291 path = path[1:]
292 comps = string.splitfields(path, os.sep)
293 i = 0
294 while i < len(comps):
295 if comps[i] == '.':
296 del comps[i]
297 elif comps[i] == '..' and i > 0 and \
298 comps[i-1] not in ('', '..'):
299 del comps[i-1:i+1]
300 i = i-1
301 elif comps[i] == '' and i > 0 and comps[i-1] <> '':
302 del comps[i]
303 elif '.' in comps[i]:
304 comp = string.splitfields(comps[i], '.')
305 comps[i] = comp[0][:8] + '.' + comp[1][:3]
306 i = i+1
307 elif len(comps[i]) > 8:
308 comps[i] = comps[i][:8]
309 i = i+1
310 else:
311 i = i+1
312 # If the path is now empty, substitute '.'
313 if not prefix and not comps:
314 comps.append('.')
315 return prefix + string.joinfields(comps, os.sep)
316