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