PageRenderTime 47ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/2.7/posixpath.py

https://bitbucket.org/kkris/pypy
Python | 415 lines | 412 code | 0 blank | 3 comment | 0 complexity | cfb2257ecfa2818643266e98ea20256e MD5 | raw file
  1. """Common operations on Posix pathnames.
  2. Instead of importing this module directly, import os and refer to
  3. this module as os.path. The "os.path" name is an alias for this
  4. module on Posix systems; on other systems (e.g. Mac, Windows),
  5. os.path provides the same operations in a manner specific to that
  6. platform, and is an alias to another module (e.g. macpath, ntpath).
  7. Some of this can actually be useful on non-Posix systems too, e.g.
  8. for manipulation of the pathname component of URLs.
  9. """
  10. import os
  11. import sys
  12. import stat
  13. import genericpath
  14. import warnings
  15. from genericpath import *
  16. __all__ = ["normcase","isabs","join","splitdrive","split","splitext",
  17. "basename","dirname","commonprefix","getsize","getmtime",
  18. "getatime","getctime","islink","exists","lexists","isdir","isfile",
  19. "ismount","walk","expanduser","expandvars","normpath","abspath",
  20. "samefile","sameopenfile","samestat",
  21. "curdir","pardir","sep","pathsep","defpath","altsep","extsep",
  22. "devnull","realpath","supports_unicode_filenames","relpath"]
  23. # strings representing various path-related bits and pieces
  24. curdir = '.'
  25. pardir = '..'
  26. extsep = '.'
  27. sep = '/'
  28. pathsep = ':'
  29. defpath = ':/bin:/usr/bin'
  30. altsep = None
  31. devnull = '/dev/null'
  32. # Normalize the case of a pathname. Trivial in Posix, string.lower on Mac.
  33. # On MS-DOS this may also turn slashes into backslashes; however, other
  34. # normalizations (such as optimizing '../' away) are not allowed
  35. # (another function should be defined to do that).
  36. def normcase(s):
  37. """Normalize case of pathname. Has no effect under Posix"""
  38. return s
  39. # Return whether a path is absolute.
  40. # Trivial in Posix, harder on the Mac or MS-DOS.
  41. def isabs(s):
  42. """Test whether a path is absolute"""
  43. return s.startswith('/')
  44. # Join pathnames.
  45. # Ignore the previous parts if a part is absolute.
  46. # Insert a '/' unless the first part is empty or already ends in '/'.
  47. def join(a, *p):
  48. """Join two or more pathname components, inserting '/' as needed.
  49. If any component is an absolute path, all previous path components
  50. will be discarded."""
  51. path = a
  52. for b in p:
  53. if b.startswith('/'):
  54. path = b
  55. elif path == '' or path.endswith('/'):
  56. path += b
  57. else:
  58. path += '/' + b
  59. return path
  60. # Split a path in head (everything up to the last '/') and tail (the
  61. # rest). If the path ends in '/', tail will be empty. If there is no
  62. # '/' in the path, head will be empty.
  63. # Trailing '/'es are stripped from head unless it is the root.
  64. def split(p):
  65. """Split a pathname. Returns tuple "(head, tail)" where "tail" is
  66. everything after the final slash. Either part may be empty."""
  67. i = p.rfind('/') + 1
  68. head, tail = p[:i], p[i:]
  69. if head and head != '/'*len(head):
  70. head = head.rstrip('/')
  71. return head, tail
  72. # Split a path in root and extension.
  73. # The extension is everything starting at the last dot in the last
  74. # pathname component; the root is everything before that.
  75. # It is always true that root + ext == p.
  76. def splitext(p):
  77. return genericpath._splitext(p, sep, altsep, extsep)
  78. splitext.__doc__ = genericpath._splitext.__doc__
  79. # Split a pathname into a drive specification and the rest of the
  80. # path. Useful on DOS/Windows/NT; on Unix, the drive is always empty.
  81. def splitdrive(p):
  82. """Split a pathname into drive and path. On Posix, drive is always
  83. empty."""
  84. return '', p
  85. # Return the tail (basename) part of a path, same as split(path)[1].
  86. def basename(p):
  87. """Returns the final component of a pathname"""
  88. i = p.rfind('/') + 1
  89. return p[i:]
  90. # Return the head (dirname) part of a path, same as split(path)[0].
  91. def dirname(p):
  92. """Returns the directory component of a pathname"""
  93. i = p.rfind('/') + 1
  94. head = p[:i]
  95. if head and head != '/'*len(head):
  96. head = head.rstrip('/')
  97. return head
  98. # Is a path a symbolic link?
  99. # This will always return false on systems where os.lstat doesn't exist.
  100. def islink(path):
  101. """Test whether a path is a symbolic link"""
  102. try:
  103. st = os.lstat(path)
  104. except (os.error, AttributeError):
  105. return False
  106. return stat.S_ISLNK(st.st_mode)
  107. # Being true for dangling symbolic links is also useful.
  108. def lexists(path):
  109. """Test whether a path exists. Returns True for broken symbolic links"""
  110. try:
  111. os.lstat(path)
  112. except os.error:
  113. return False
  114. return True
  115. # Are two filenames really pointing to the same file?
  116. def samefile(f1, f2):
  117. """Test whether two pathnames reference the same actual file"""
  118. s1 = os.stat(f1)
  119. s2 = os.stat(f2)
  120. return samestat(s1, s2)
  121. # Are two open files really referencing the same file?
  122. # (Not necessarily the same file descriptor!)
  123. def sameopenfile(fp1, fp2):
  124. """Test whether two open file objects reference the same file"""
  125. s1 = os.fstat(fp1)
  126. s2 = os.fstat(fp2)
  127. return samestat(s1, s2)
  128. # Are two stat buffers (obtained from stat, fstat or lstat)
  129. # describing the same file?
  130. def samestat(s1, s2):
  131. """Test whether two stat buffers reference the same file"""
  132. return s1.st_ino == s2.st_ino and \
  133. s1.st_dev == s2.st_dev
  134. # Is a path a mount point?
  135. # (Does this work for all UNIXes? Is it even guaranteed to work by Posix?)
  136. def ismount(path):
  137. """Test whether a path is a mount point"""
  138. if islink(path):
  139. # A symlink can never be a mount point
  140. return False
  141. try:
  142. s1 = os.lstat(path)
  143. s2 = os.lstat(join(path, '..'))
  144. except os.error:
  145. return False # It doesn't exist -- so not a mount point :-)
  146. dev1 = s1.st_dev
  147. dev2 = s2.st_dev
  148. if dev1 != dev2:
  149. return True # path/.. on a different device as path
  150. ino1 = s1.st_ino
  151. ino2 = s2.st_ino
  152. if ino1 == ino2:
  153. return True # path/.. is the same i-node as path
  154. return False
  155. # Directory tree walk.
  156. # For each directory under top (including top itself, but excluding
  157. # '.' and '..'), func(arg, dirname, filenames) is called, where
  158. # dirname is the name of the directory and filenames is the list
  159. # of files (and subdirectories etc.) in the directory.
  160. # The func may modify the filenames list, to implement a filter,
  161. # or to impose a different order of visiting.
  162. def walk(top, func, arg):
  163. """Directory tree walk with callback function.
  164. For each directory in the directory tree rooted at top (including top
  165. itself, but excluding '.' and '..'), call func(arg, dirname, fnames).
  166. dirname is the name of the directory, and fnames a list of the names of
  167. the files and subdirectories in dirname (excluding '.' and '..'). func
  168. may modify the fnames list in-place (e.g. via del or slice assignment),
  169. and walk will only recurse into the subdirectories whose names remain in
  170. fnames; this can be used to implement a filter, or to impose a specific
  171. order of visiting. No semantics are defined for, or required of, arg,
  172. beyond that arg is always passed to func. It can be used, e.g., to pass
  173. a filename pattern, or a mutable object designed to accumulate
  174. statistics. Passing None for arg is common."""
  175. warnings.warnpy3k("In 3.x, os.path.walk is removed in favor of os.walk.",
  176. stacklevel=2)
  177. try:
  178. names = os.listdir(top)
  179. except os.error:
  180. return
  181. func(arg, top, names)
  182. for name in names:
  183. name = join(top, name)
  184. try:
  185. st = os.lstat(name)
  186. except os.error:
  187. continue
  188. if stat.S_ISDIR(st.st_mode):
  189. walk(name, func, arg)
  190. # Expand paths beginning with '~' or '~user'.
  191. # '~' means $HOME; '~user' means that user's home directory.
  192. # If the path doesn't begin with '~', or if the user or $HOME is unknown,
  193. # the path is returned unchanged (leaving error reporting to whatever
  194. # function is called with the expanded path as argument).
  195. # See also module 'glob' for expansion of *, ? and [...] in pathnames.
  196. # (A function should also be defined to do full *sh-style environment
  197. # variable expansion.)
  198. def expanduser(path):
  199. """Expand ~ and ~user constructions. If user or $HOME is unknown,
  200. do nothing."""
  201. if not path.startswith('~'):
  202. return path
  203. i = path.find('/', 1)
  204. if i < 0:
  205. i = len(path)
  206. if i == 1:
  207. if 'HOME' not in os.environ:
  208. import pwd
  209. userhome = pwd.getpwuid(os.getuid()).pw_dir
  210. else:
  211. userhome = os.environ['HOME']
  212. else:
  213. import pwd
  214. try:
  215. pwent = pwd.getpwnam(path[1:i])
  216. except KeyError:
  217. return path
  218. userhome = pwent.pw_dir
  219. userhome = userhome.rstrip('/') or userhome
  220. return userhome + path[i:]
  221. # Expand paths containing shell variable substitutions.
  222. # This expands the forms $variable and ${variable} only.
  223. # Non-existent variables are left unchanged.
  224. _varprog = None
  225. def expandvars(path):
  226. """Expand shell variables of form $var and ${var}. Unknown variables
  227. are left unchanged."""
  228. global _varprog
  229. if '$' not in path:
  230. return path
  231. if not _varprog:
  232. import re
  233. _varprog = re.compile(r'\$(\w+|\{[^}]*\})')
  234. i = 0
  235. while True:
  236. m = _varprog.search(path, i)
  237. if not m:
  238. break
  239. i, j = m.span(0)
  240. name = m.group(1)
  241. if name.startswith('{') and name.endswith('}'):
  242. name = name[1:-1]
  243. if name in os.environ:
  244. tail = path[j:]
  245. path = path[:i] + os.environ[name]
  246. i = len(path)
  247. path += tail
  248. else:
  249. i = j
  250. return path
  251. # Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A/B.
  252. # It should be understood that this may change the meaning of the path
  253. # if it contains symbolic links!
  254. def normpath(path):
  255. """Normalize path, eliminating double slashes, etc."""
  256. # Preserve unicode (if path is unicode)
  257. slash, dot = (u'/', u'.') if isinstance(path, unicode) else ('/', '.')
  258. if path == '':
  259. return dot
  260. initial_slashes = path.startswith('/')
  261. # POSIX allows one or two initial slashes, but treats three or more
  262. # as single slash.
  263. if (initial_slashes and
  264. path.startswith('//') and not path.startswith('///')):
  265. initial_slashes = 2
  266. comps = path.split('/')
  267. new_comps = []
  268. for comp in comps:
  269. if comp in ('', '.'):
  270. continue
  271. if (comp != '..' or (not initial_slashes and not new_comps) or
  272. (new_comps and new_comps[-1] == '..')):
  273. new_comps.append(comp)
  274. elif new_comps:
  275. new_comps.pop()
  276. comps = new_comps
  277. path = slash.join(comps)
  278. if initial_slashes:
  279. path = slash*initial_slashes + path
  280. return path or dot
  281. def abspath(path):
  282. """Return an absolute path."""
  283. if not isabs(path):
  284. if isinstance(path, unicode):
  285. cwd = os.getcwdu()
  286. else:
  287. cwd = os.getcwd()
  288. path = join(cwd, path)
  289. return normpath(path)
  290. # Return a canonical path (i.e. the absolute location of a file on the
  291. # filesystem).
  292. def realpath(filename):
  293. """Return the canonical path of the specified filename, eliminating any
  294. symbolic links encountered in the path."""
  295. if isabs(filename):
  296. bits = ['/'] + filename.split('/')[1:]
  297. else:
  298. bits = [''] + filename.split('/')
  299. for i in range(2, len(bits)+1):
  300. component = join(*bits[0:i])
  301. # Resolve symbolic links.
  302. if islink(component):
  303. resolved = _resolve_link(component)
  304. if resolved is None:
  305. # Infinite loop -- return original component + rest of the path
  306. return abspath(join(*([component] + bits[i:])))
  307. else:
  308. newpath = join(*([resolved] + bits[i:]))
  309. return realpath(newpath)
  310. return abspath(filename)
  311. def _resolve_link(path):
  312. """Internal helper function. Takes a path and follows symlinks
  313. until we either arrive at something that isn't a symlink, or
  314. encounter a path we've seen before (meaning that there's a loop).
  315. """
  316. paths_seen = set()
  317. while islink(path):
  318. if path in paths_seen:
  319. # Already seen this path, so we must have a symlink loop
  320. return None
  321. paths_seen.add(path)
  322. # Resolve where the link points to
  323. resolved = os.readlink(path)
  324. if not isabs(resolved):
  325. dir = dirname(path)
  326. path = normpath(join(dir, resolved))
  327. else:
  328. path = normpath(resolved)
  329. return path
  330. supports_unicode_filenames = (sys.platform == 'darwin')
  331. def relpath(path, start=curdir):
  332. """Return a relative version of a path"""
  333. if not path:
  334. raise ValueError("no path specified")
  335. start_list = [x for x in abspath(start).split(sep) if x]
  336. path_list = [x for x in abspath(path).split(sep) if x]
  337. # Work out how much of the filepath is shared by start and path.
  338. i = len(commonprefix([start_list, path_list]))
  339. rel_list = [pardir] * (len(start_list)-i) + path_list[i:]
  340. if not rel_list:
  341. return curdir
  342. return join(*rel_list)