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