PageRenderTime 82ms CodeModel.GetById 38ms RepoModel.GetById 0ms app.codeStats 0ms

/client/bower_components/brython/www/src/Lib/posixpath.py

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