Vega strike Python Modules doc  0.5.1
Documentation of the " Modules " folder of Vega strike
 All Data Structures Namespaces Files Functions Variables
dospath.py
Go to the documentation of this file.
1 """Common operations on DOS pathnames."""
2 
3 import os
4 import stat
5 
6 __all__ = ["normcase","isabs","join","splitdrive","split","splitext",
7  "basename","dirname","commonprefix","getsize","getmtime",
8  "getatime","islink","exists","isdir","isfile","ismount",
9  "walk","expanduser","expandvars","normpath","abspath"]
10 
11 def normcase(s):
12  """Normalize the case of a pathname.
13  On MS-DOS it maps the pathname to lowercase, turns slashes into
14  backslashes.
15  Other normalizations (such as optimizing '../' away) are not allowed
16  (this is done by normpath).
17  Previously, this version mapped invalid consecutive characters to a
18  single '_', but this has been removed. This functionality should
19  possibly be added as a new function."""
20 
21  return s.replace("/", "\\").lower()
22 
23 
24 def isabs(s):
25  """Return whether a path is absolute.
26  Trivial in Posix, harder on the Mac or MS-DOS.
27  For DOS it is absolute if it starts with a slash or backslash (current
28  volume), or if a pathname after the volume letter and colon starts with
29  a slash or backslash."""
30 
31  s = splitdrive(s)[1]
32  return s != '' and s[:1] in '/\\'
33 
34 
35 def join(a, *p):
36  """Join two (or more) paths."""
37 
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 + "\\" + b
46  return path
47 
48 
49 def splitdrive(p):
50  """Split a path into a drive specification (a drive letter followed
51  by a colon) and path specification.
52  It is always true that drivespec + pathspec == p."""
53 
54  if p[1:2] == ':':
55  return p[0:2], p[2:]
56  return '', p
57 
58 
59 def split(p):
60  """Split a path into head (everything up to the last '/') and tail
61  (the rest). After the trailing '/' is stripped, the invariant
62  join(head, tail) == p holds.
63  The resulting head won't end in '/' unless it is the root."""
64 
65  d, p = splitdrive(p)
66  # set i to index beyond p's last slash
67  i = len(p)
68  while i and p[i-1] not in '/\\':
69  i = i - 1
70  head, tail = p[:i], p[i:] # now tail has no slashes
71  # remove trailing slashes from head, unless it's all slashes
72  head2 = head
73  while head2 and head2[-1] in '/\\':
74  head2 = head2[:-1]
75  head = head2 or head
76  return d + head, tail
77 
78 
79 def splitext(p):
80  """Split a path into root and extension.
81  The extension is everything starting at the first dot in the last
82  pathname component; the root is everything before that.
83  It is always true that root + ext == p."""
84 
85  root, ext = '', ''
86  for c in p:
87  if c in '/\\':
88  root, ext = root + ext + c, ''
89  elif c == '.' or ext:
90  ext = ext + c
91  else:
92  root = root + c
93  return root, ext
94 
95 
96 def basename(p):
97  """Return the tail (basename) part of a path."""
98 
99  return split(p)[1]
100 
101 
102 def dirname(p):
103  """Return the head (dirname) part of a path."""
104 
105  return split(p)[0]
106 
107 
109  """Return the longest prefix of all list elements."""
110 
111  if not m: return ''
112  prefix = m[0]
113  for item in m:
114  for i in range(len(prefix)):
115  if prefix[:i+1] != item[:i+1]:
116  prefix = prefix[:i]
117  if i == 0: return ''
118  break
119  return prefix
120 
121 
122 # Get size, mtime, atime of files.
123 
124 def getsize(filename):
125  """Return the size of a file, reported by os.stat()."""
126  st = os.stat(filename)
127  return st[stat.ST_SIZE]
128 
129 def getmtime(filename):
130  """Return the last modification time of a file, reported by os.stat()."""
131  st = os.stat(filename)
132  return st[stat.ST_MTIME]
133 
134 def getatime(filename):
135  """Return the last access time of a file, reported by os.stat()."""
136  st = os.stat(filename)
137  return st[stat.ST_ATIME]
138 
139 
140 def islink(path):
141  """Is a path a symbolic link?
142  This will always return false on systems where posix.lstat doesn't exist."""
143 
144  return 0
145 
146 
147 def exists(path):
148  """Does a path exist?
149  This is false for dangling symbolic links."""
150 
151  try:
152  st = os.stat(path)
153  except os.error:
154  return 0
155  return 1
156 
157 
158 def isdir(path):
159  """Is a path a dos directory?"""
160 
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 def isfile(path):
169  """Is a path a regular file?"""
170 
171  try:
172  st = os.stat(path)
173  except os.error:
174  return 0
175  return stat.S_ISREG(st[stat.ST_MODE])
176 
177 
178 def ismount(path):
179  """Is a path a mount point?"""
180  # XXX This degenerates in: 'is this the root?' on DOS
181 
182  return isabs(splitdrive(path)[1])
183 
184 
185 def walk(top, func, arg):
186  """Directory tree walk with callback function.
187 
188  For each directory in the directory tree rooted at top (including top
189  itself, but excluding '.' and '..'), call func(arg, dirname, fnames).
190  dirname is the name of the directory, and fnames a list of the names of
191  the files and subdirectories in dirname (excluding '.' and '..'). func
192  may modify the fnames list in-place (e.g. via del or slice assignment),
193  and walk will only recurse into the subdirectories whose names remain in
194  fnames; this can be used to implement a filter, or to impose a specific
195  order of visiting. No semantics are defined for, or required of, arg,
196  beyond that arg is always passed to func. It can be used, e.g., to pass
197  a filename pattern, or a mutable object designed to accumulate
198  statistics. Passing None for arg is common."""
199 
200  try:
201  names = os.listdir(top)
202  except os.error:
203  return
204  func(arg, top, names)
205  exceptions = ('.', '..')
206  for name in names:
207  if name not in exceptions:
208  name = join(top, name)
209  if isdir(name):
210  walk(name, func, arg)
211 
212 
213 def expanduser(path):
214  """Expand paths beginning with '~' or '~user'.
215  '~' means $HOME; '~user' means that user's home directory.
216  If the path doesn't begin with '~', or if the user or $HOME is unknown,
217  the path is returned unchanged (leaving error reporting to whatever
218  function is called with the expanded path as argument).
219  See also module 'glob' for expansion of *, ? and [...] in pathnames.
220  (A function should also be defined to do full *sh-style environment
221  variable expansion.)"""
222 
223  if path[:1] != '~':
224  return path
225  i, n = 1, len(path)
226  while i < n and path[i] not in '/\\':
227  i = i+1
228  if i == 1:
229  if not os.environ.has_key('HOME'):
230  return path
231  userhome = os.environ['HOME']
232  else:
233  return path
234  return userhome + path[i:]
235 
236 
237 def expandvars(path):
238  """Expand paths containing shell variable substitutions.
239  The following rules apply:
240  - no expansion within single quotes
241  - no escape character, except for '$$' which is translated into '$'
242  - ${varname} is accepted.
243  - varnames can be made out of letters, digits and the character '_'"""
244  # XXX With COMMAND.COM you can use any characters in a variable name,
245  # XXX except '^|<>='.
246 
247  if '$' not in path:
248  return path
249  import string
250  varchars = string.ascii_letters + string.digits + "_-"
251  res = ''
252  index = 0
253  pathlen = len(path)
254  while index < pathlen:
255  c = path[index]
256  if c == '\'': # no expansion within single quotes
257  path = path[index + 1:]
258  pathlen = len(path)
259  try:
260  index = path.index('\'')
261  res = res + '\'' + path[:index + 1]
262  except ValueError:
263  res = res + path
264  index = pathlen -1
265  elif c == '$': # variable or '$$'
266  if path[index + 1:index + 2] == '$':
267  res = res + c
268  index = index + 1
269  elif path[index + 1:index + 2] == '{':
270  path = path[index+2:]
271  pathlen = len(path)
272  try:
273  index = path.index('}')
274  var = path[:index]
275  if os.environ.has_key(var):
276  res = res + os.environ[var]
277  except ValueError:
278  res = res + path
279  index = pathlen - 1
280  else:
281  var = ''
282  index = index + 1
283  c = path[index:index + 1]
284  while c != '' and c in varchars:
285  var = var + c
286  index = index + 1
287  c = path[index:index + 1]
288  if os.environ.has_key(var):
289  res = res + os.environ[var]
290  if c != '':
291  res = res + c
292  else:
293  res = res + c
294  index = index + 1
295  return res
296 
297 
298 def normpath(path):
299  """Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A/B.
300  Also, components of the path are silently truncated to 8+3 notation."""
301 
302  path = path.replace("/", "\\")
303  prefix, path = splitdrive(path)
304  while path[:1] == "\\":
305  prefix = prefix + "\\"
306  path = path[1:]
307  comps = path.split("\\")
308  i = 0
309  while i < len(comps):
310  if comps[i] == '.':
311  del comps[i]
312  elif comps[i] == '..' and i > 0 and \
313  comps[i-1] not in ('', '..'):
314  del comps[i-1:i+1]
315  i = i - 1
316  elif comps[i] == '' and i > 0 and comps[i-1] != '':
317  del comps[i]
318  elif '.' in comps[i]:
319  comp = comps[i].split('.')
320  comps[i] = comp[0][:8] + '.' + comp[1][:3]
321  i = i + 1
322  elif len(comps[i]) > 8:
323  comps[i] = comps[i][:8]
324  i = i + 1
325  else:
326  i = i + 1
327  # If the path is now empty, substitute '.'
328  if not prefix and not comps:
329  comps.append('.')
330  return prefix + "\\".join(comps)
331 
332 
333 
334 def abspath(path):
335  """Return an absolute path."""
336  if not isabs(path):
337  path = join(os.getcwd(), path)
338  return normpath(path)
339 
340 # realpath is a no-op on systems without islink support
341 realpath = abspath