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