PageRenderTime 111ms CodeModel.GetById 31ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/python2.4/posixpath.py

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