macpath.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. """Pathname and path-related operations for the Macintosh."""
  2. import os
  3. from stat import *
  4. __all__ = ["normcase","isabs","join","splitdrive","split","splitext",
  5. "basename","dirname","commonprefix","getsize","getmtime",
  6. "getatime","getctime", "islink","exists","lexists","isdir","isfile",
  7. "walk","expanduser","expandvars","normpath","abspath",
  8. "curdir","pardir","sep","pathsep","defpath","altsep","extsep",
  9. "devnull","realpath","supports_unicode_filenames"]
  10. # strings representing various path-related bits and pieces
  11. curdir = ':'
  12. pardir = '::'
  13. extsep = '.'
  14. sep = ':'
  15. pathsep = '\n'
  16. defpath = ':'
  17. altsep = None
  18. devnull = 'Dev:Null'
  19. # Normalize the case of a pathname. Dummy in Posix, but <s>.lower() here.
  20. def normcase(path):
  21. return path.lower()
  22. def isabs(s):
  23. """Return true if a path is absolute.
  24. On the Mac, relative paths begin with a colon,
  25. but as a special case, paths with no colons at all are also relative.
  26. Anything else is absolute (the string up to the first colon is the
  27. volume name)."""
  28. return ':' in s and s[0] != ':'
  29. def join(s, *p):
  30. path = s
  31. for t in p:
  32. if (not s) or isabs(t):
  33. path = t
  34. continue
  35. if t[:1] == ':':
  36. t = t[1:]
  37. if ':' not in path:
  38. path = ':' + path
  39. if path[-1:] != ':':
  40. path = path + ':'
  41. path = path + t
  42. return path
  43. def split(s):
  44. """Split a pathname into two parts: the directory leading up to the final
  45. bit, and the basename (the filename, without colons, in that directory).
  46. The result (s, t) is such that join(s, t) yields the original argument."""
  47. if ':' not in s: return '', s
  48. colon = 0
  49. for i in range(len(s)):
  50. if s[i] == ':': colon = i + 1
  51. path, file = s[:colon-1], s[colon:]
  52. if path and not ':' in path:
  53. path = path + ':'
  54. return path, file
  55. def splitext(p):
  56. """Split a path into root and extension.
  57. The extension is everything starting at the last dot in the last
  58. pathname component; the root is everything before that.
  59. It is always true that root + ext == p."""
  60. i = p.rfind('.')
  61. if i<=p.rfind(':'):
  62. return p, ''
  63. else:
  64. return p[:i], p[i:]
  65. def splitdrive(p):
  66. """Split a pathname into a drive specification and the rest of the
  67. path. Useful on DOS/Windows/NT; on the Mac, the drive is always
  68. empty (don't use the volume name -- it doesn't have the same
  69. syntactic and semantic oddities as DOS drive letters, such as there
  70. being a separate current directory per drive)."""
  71. return '', p
  72. # Short interfaces to split()
  73. def dirname(s): return split(s)[0]
  74. def basename(s): return split(s)[1]
  75. def ismount(s):
  76. if not isabs(s):
  77. return False
  78. components = split(s)
  79. return len(components) == 2 and components[1] == ''
  80. def isdir(s):
  81. """Return true if the pathname refers to an existing directory."""
  82. try:
  83. st = os.stat(s)
  84. except os.error:
  85. return 0
  86. return S_ISDIR(st.st_mode)
  87. # Get size, mtime, atime of files.
  88. def getsize(filename):
  89. """Return the size of a file, reported by os.stat()."""
  90. return os.stat(filename).st_size
  91. def getmtime(filename):
  92. """Return the last modification time of a file, reported by os.stat()."""
  93. return os.stat(filename).st_mtime
  94. def getatime(filename):
  95. """Return the last access time of a file, reported by os.stat()."""
  96. return os.stat(filename).st_atime
  97. def islink(s):
  98. """Return true if the pathname refers to a symbolic link."""
  99. try:
  100. import Carbon.File
  101. return Carbon.File.ResolveAliasFile(s, 0)[2]
  102. except:
  103. return False
  104. def isfile(s):
  105. """Return true if the pathname refers to an existing regular file."""
  106. try:
  107. st = os.stat(s)
  108. except os.error:
  109. return False
  110. return S_ISREG(st.st_mode)
  111. def getctime(filename):
  112. """Return the creation time of a file, reported by os.stat()."""
  113. return os.stat(filename).st_ctime
  114. def exists(s):
  115. """Test whether a path exists. Returns False for broken symbolic links"""
  116. try:
  117. st = os.stat(s)
  118. except os.error:
  119. return False
  120. return True
  121. # Is `stat`/`lstat` a meaningful difference on the Mac? This is safe in any
  122. # case.
  123. def lexists(path):
  124. """Test whether a path exists. Returns True for broken symbolic links"""
  125. try:
  126. st = os.lstat(path)
  127. except os.error:
  128. return False
  129. return True
  130. # Return the longest prefix of all list elements.
  131. def commonprefix(m):
  132. "Given a list of pathnames, returns the longest common leading component"
  133. if not m: return ''
  134. prefix = m[0]
  135. for item in m:
  136. for i in range(len(prefix)):
  137. if prefix[:i+1] != item[:i+1]:
  138. prefix = prefix[:i]
  139. if i == 0: return ''
  140. break
  141. return prefix
  142. def expandvars(path):
  143. """Dummy to retain interface-compatibility with other operating systems."""
  144. return path
  145. def expanduser(path):
  146. """Dummy to retain interface-compatibility with other operating systems."""
  147. return path
  148. class norm_error(Exception):
  149. """Path cannot be normalized"""
  150. def normpath(s):
  151. """Normalize a pathname. Will return the same result for
  152. equivalent paths."""
  153. if ":" not in s:
  154. return ":"+s
  155. comps = s.split(":")
  156. i = 1
  157. while i < len(comps)-1:
  158. if comps[i] == "" and comps[i-1] != "":
  159. if i > 1:
  160. del comps[i-1:i+1]
  161. i = i - 1
  162. else:
  163. # best way to handle this is to raise an exception
  164. raise norm_error, 'Cannot use :: immediately after volume name'
  165. else:
  166. i = i + 1
  167. s = ":".join(comps)
  168. # remove trailing ":" except for ":" and "Volume:"
  169. if s[-1] == ":" and len(comps) > 2 and s != ":"*len(s):
  170. s = s[:-1]
  171. return s
  172. def walk(top, func, arg):
  173. """Directory tree walk with callback function.
  174. For each directory in the directory tree rooted at top (including top
  175. itself, but excluding '.' and '..'), call func(arg, dirname, fnames).
  176. dirname is the name of the directory, and fnames a list of the names of
  177. the files and subdirectories in dirname (excluding '.' and '..'). func
  178. may modify the fnames list in-place (e.g. via del or slice assignment),
  179. and walk will only recurse into the subdirectories whose names remain in
  180. fnames; this can be used to implement a filter, or to impose a specific
  181. order of visiting. No semantics are defined for, or required of, arg,
  182. beyond that arg is always passed to func. It can be used, e.g., to pass
  183. a filename pattern, or a mutable object designed to accumulate
  184. statistics. Passing None for arg is common."""
  185. try:
  186. names = os.listdir(top)
  187. except os.error:
  188. return
  189. func(arg, top, names)
  190. for name in names:
  191. name = join(top, name)
  192. if isdir(name) and not islink(name):
  193. walk(name, func, arg)
  194. def abspath(path):
  195. """Return an absolute path."""
  196. if not isabs(path):
  197. path = join(os.getcwd(), path)
  198. return normpath(path)
  199. # realpath is a no-op on systems without islink support
  200. def realpath(path):
  201. path = abspath(path)
  202. try:
  203. import Carbon.File
  204. except ImportError:
  205. return path
  206. if not path:
  207. return path
  208. components = path.split(':')
  209. path = components[0] + ':'
  210. for c in components[1:]:
  211. path = join(path, c)
  212. path = Carbon.File.FSResolveAliasFile(path, 1)[0].as_pathname()
  213. return path
  214. supports_unicode_filenames = False