You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

dospath.py 9.7KB

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