PageRenderTime 26ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/flask/Lib/posixpath.py

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