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