macpath.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. """Pathname and path-related operations for the Macintosh."""
  2. # strings representing various path-related bits and pieces
  3. # These are primarily for export; internally, they are hardcoded.
  4. # Should be set before imports for resolving cyclic dependency.
  5. curdir = ':'
  6. pardir = '::'
  7. extsep = '.'
  8. sep = ':'
  9. pathsep = '\n'
  10. defpath = ':'
  11. altsep = None
  12. devnull = 'Dev:Null'
  13. import os
  14. from stat import *
  15. import genericpath
  16. from genericpath import *
  17. import warnings
  18. warnings.warn('the macpath module is deprecated in 3.7 and will be removed '
  19. 'in 3.8', DeprecationWarning, stacklevel=2)
  20. __all__ = ["normcase","isabs","join","splitdrive","split","splitext",
  21. "basename","dirname","commonprefix","getsize","getmtime",
  22. "getatime","getctime", "islink","exists","lexists","isdir","isfile",
  23. "expanduser","expandvars","normpath","abspath",
  24. "curdir","pardir","sep","pathsep","defpath","altsep","extsep",
  25. "devnull","realpath","supports_unicode_filenames"]
  26. def _get_colon(path):
  27. if isinstance(path, bytes):
  28. return b':'
  29. else:
  30. return ':'
  31. # Normalize the case of a pathname. Dummy in Posix, but <s>.lower() here.
  32. def normcase(path):
  33. if not isinstance(path, (bytes, str)):
  34. raise TypeError("normcase() argument must be str or bytes, "
  35. "not '{}'".format(path.__class__.__name__))
  36. return path.lower()
  37. def isabs(s):
  38. """Return true if a path is absolute.
  39. On the Mac, relative paths begin with a colon,
  40. but as a special case, paths with no colons at all are also relative.
  41. Anything else is absolute (the string up to the first colon is the
  42. volume name)."""
  43. colon = _get_colon(s)
  44. return colon in s and s[:1] != colon
  45. def join(s, *p):
  46. try:
  47. colon = _get_colon(s)
  48. path = s
  49. if not p:
  50. path[:0] + colon #23780: Ensure compatible data type even if p is null.
  51. for t in p:
  52. if (not path) or isabs(t):
  53. path = t
  54. continue
  55. if t[:1] == colon:
  56. t = t[1:]
  57. if colon not in path:
  58. path = colon + path
  59. if path[-1:] != colon:
  60. path = path + colon
  61. path = path + t
  62. return path
  63. except (TypeError, AttributeError, BytesWarning):
  64. genericpath._check_arg_types('join', s, *p)
  65. raise
  66. def split(s):
  67. """Split a pathname into two parts: the directory leading up to the final
  68. bit, and the basename (the filename, without colons, in that directory).
  69. The result (s, t) is such that join(s, t) yields the original argument."""
  70. colon = _get_colon(s)
  71. if colon not in s: return s[:0], s
  72. col = 0
  73. for i in range(len(s)):
  74. if s[i:i+1] == colon: col = i + 1
  75. path, file = s[:col-1], s[col:]
  76. if path and not colon in path:
  77. path = path + colon
  78. return path, file
  79. def splitext(p):
  80. if isinstance(p, bytes):
  81. return genericpath._splitext(p, b':', altsep, b'.')
  82. else:
  83. return genericpath._splitext(p, sep, altsep, extsep)
  84. splitext.__doc__ = genericpath._splitext.__doc__
  85. def splitdrive(p):
  86. """Split a pathname into a drive specification and the rest of the
  87. path. Useful on DOS/Windows/NT; on the Mac, the drive is always
  88. empty (don't use the volume name -- it doesn't have the same
  89. syntactic and semantic oddities as DOS drive letters, such as there
  90. being a separate current directory per drive)."""
  91. return p[:0], p
  92. # Short interfaces to split()
  93. def dirname(s): return split(s)[0]
  94. def basename(s): return split(s)[1]
  95. def ismount(s):
  96. if not isabs(s):
  97. return False
  98. components = split(s)
  99. return len(components) == 2 and not components[1]
  100. def islink(s):
  101. """Return true if the pathname refers to a symbolic link."""
  102. try:
  103. import Carbon.File
  104. return Carbon.File.ResolveAliasFile(s, 0)[2]
  105. except:
  106. return False
  107. # Is `stat`/`lstat` a meaningful difference on the Mac? This is safe in any
  108. # case.
  109. def lexists(path):
  110. """Test whether a path exists. Returns True for broken symbolic links"""
  111. try:
  112. st = os.lstat(path)
  113. except OSError:
  114. return False
  115. return True
  116. def expandvars(path):
  117. """Dummy to retain interface-compatibility with other operating systems."""
  118. return path
  119. def expanduser(path):
  120. """Dummy to retain interface-compatibility with other operating systems."""
  121. return path
  122. class norm_error(Exception):
  123. """Path cannot be normalized"""
  124. def normpath(s):
  125. """Normalize a pathname. Will return the same result for
  126. equivalent paths."""
  127. colon = _get_colon(s)
  128. if colon not in s:
  129. return colon + s
  130. comps = s.split(colon)
  131. i = 1
  132. while i < len(comps)-1:
  133. if not comps[i] and comps[i-1]:
  134. if i > 1:
  135. del comps[i-1:i+1]
  136. i = i - 1
  137. else:
  138. # best way to handle this is to raise an exception
  139. raise norm_error('Cannot use :: immediately after volume name')
  140. else:
  141. i = i + 1
  142. s = colon.join(comps)
  143. # remove trailing ":" except for ":" and "Volume:"
  144. if s[-1:] == colon and len(comps) > 2 and s != colon*len(s):
  145. s = s[:-1]
  146. return s
  147. def abspath(path):
  148. """Return an absolute path."""
  149. if not isabs(path):
  150. if isinstance(path, bytes):
  151. cwd = os.getcwdb()
  152. else:
  153. cwd = os.getcwd()
  154. path = join(cwd, path)
  155. return normpath(path)
  156. # realpath is a no-op on systems without islink support
  157. def realpath(path):
  158. path = abspath(path)
  159. try:
  160. import Carbon.File
  161. except ImportError:
  162. return path
  163. if not path:
  164. return path
  165. colon = _get_colon(path)
  166. components = path.split(colon)
  167. path = components[0] + colon
  168. for c in components[1:]:
  169. path = join(path, c)
  170. try:
  171. path = Carbon.File.FSResolveAliasFile(path, 1)[0].as_pathname()
  172. except Carbon.File.Error:
  173. pass
  174. return path
  175. supports_unicode_filenames = True