/Hosts/Silverlight/Tests/pylib/ntpath.py

http://github.com/IronLanguages/main · Python · 497 lines · 333 code · 53 blank · 111 comment · 83 complexity · 8619147cbe8bf33c5ec12aeb8afb337f MD5 · raw file

  1. # Module 'ntpath' -- common operations on WinNT/Win95 pathnames
  2. """Common pathname manipulations, WindowsNT/95 version.
  3. Instead of importing this module directly, import os and refer to this
  4. module as os.path.
  5. """
  6. import os
  7. import sys
  8. import stat
  9. import genericpath
  10. import warnings
  11. from genericpath import *
  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. "splitunc","curdir","pardir","sep","pathsep","defpath","altsep",
  17. "extsep","devnull","realpath","supports_unicode_filenames","relpath"]
  18. # strings representing various path-related bits and pieces
  19. curdir = '.'
  20. pardir = '..'
  21. extsep = '.'
  22. sep = '\\'
  23. pathsep = ';'
  24. altsep = '/'
  25. defpath = '.;C:\\bin'
  26. if 'ce' in sys.builtin_module_names:
  27. defpath = '\\Windows'
  28. elif 'os2' in sys.builtin_module_names:
  29. # OS/2 w/ VACPP
  30. altsep = '/'
  31. devnull = 'nul'
  32. # Normalize the case of a pathname and map slashes to backslashes.
  33. # Other normalizations (such as optimizing '../' away) are not done
  34. # (this is done by normpath).
  35. def normcase(s):
  36. """Normalize case of pathname.
  37. Makes all characters lowercase and all slashes into backslashes."""
  38. return s.replace("/", "\\").lower()
  39. # Return whether a path is absolute.
  40. # Trivial in Posix, harder on the Mac or MS-DOS.
  41. # For DOS it is absolute if it starts with a slash or backslash (current
  42. # volume), or if a pathname after the volume letter and colon / UNC resource
  43. # starts with a slash or backslash.
  44. def isabs(s):
  45. """Test whether a path is absolute"""
  46. s = splitdrive(s)[1]
  47. return s != '' and s[:1] in '/\\'
  48. # Join two (or more) paths.
  49. def join(a, *p):
  50. """Join two or more pathname components, inserting "\\" as needed.
  51. If any component is an absolute path, all previous path components
  52. will be discarded."""
  53. path = a
  54. for b in p:
  55. b_wins = 0 # set to 1 iff b makes path irrelevant
  56. if path == "":
  57. b_wins = 1
  58. elif isabs(b):
  59. # This probably wipes out path so far. However, it's more
  60. # complicated if path begins with a drive letter:
  61. # 1. join('c:', '/a') == 'c:/a'
  62. # 2. join('c:/', '/a') == 'c:/a'
  63. # But
  64. # 3. join('c:/a', '/b') == '/b'
  65. # 4. join('c:', 'd:/') = 'd:/'
  66. # 5. join('c:/', 'd:/') = 'd:/'
  67. if path[1:2] != ":" or b[1:2] == ":":
  68. # Path doesn't start with a drive letter, or cases 4 and 5.
  69. b_wins = 1
  70. # Else path has a drive letter, and b doesn't but is absolute.
  71. elif len(path) > 3 or (len(path) == 3 and
  72. path[-1] not in "/\\"):
  73. # case 3
  74. b_wins = 1
  75. if b_wins:
  76. path = b
  77. else:
  78. # Join, and ensure there's a separator.
  79. assert len(path) > 0
  80. if path[-1] in "/\\":
  81. if b and b[0] in "/\\":
  82. path += b[1:]
  83. else:
  84. path += b
  85. elif path[-1] == ":":
  86. path += b
  87. elif b:
  88. if b[0] in "/\\":
  89. path += b
  90. else:
  91. path += "\\" + b
  92. else:
  93. # path is not empty and does not end with a backslash,
  94. # but b is empty; since, e.g., split('a/') produces
  95. # ('a', ''), it's best if join() adds a backslash in
  96. # this case.
  97. path += '\\'
  98. return path
  99. # Split a path in a drive specification (a drive letter followed by a
  100. # colon) and the path specification.
  101. # It is always true that drivespec + pathspec == p
  102. def splitdrive(p):
  103. """Split a pathname into drive and path specifiers. Returns a 2-tuple
  104. "(drive,path)"; either part may be empty"""
  105. if p[1:2] == ':':
  106. return p[0:2], p[2:]
  107. return '', p
  108. # Parse UNC paths
  109. def splitunc(p):
  110. """Split a pathname into UNC mount point and relative path specifiers.
  111. Return a 2-tuple (unc, rest); either part may be empty.
  112. If unc is not empty, it has the form '//host/mount' (or similar
  113. using backslashes). unc+rest is always the input path.
  114. Paths containing drive letters never have an UNC part.
  115. """
  116. if p[1:2] == ':':
  117. return '', p # Drive letter present
  118. firstTwo = p[0:2]
  119. if firstTwo == '//' or firstTwo == '\\\\':
  120. # is a UNC path:
  121. # vvvvvvvvvvvvvvvvvvvv equivalent to drive letter
  122. # \\machine\mountpoint\directories...
  123. # directory ^^^^^^^^^^^^^^^
  124. normp = normcase(p)
  125. index = normp.find('\\', 2)
  126. if index == -1:
  127. ##raise RuntimeError, 'illegal UNC path: "' + p + '"'
  128. return ("", p)
  129. index = normp.find('\\', index + 1)
  130. if index == -1:
  131. index = len(p)
  132. return p[:index], p[index:]
  133. return '', p
  134. # Split a path in head (everything up to the last '/') and tail (the
  135. # rest). After the trailing '/' is stripped, the invariant
  136. # join(head, tail) == p holds.
  137. # The resulting head won't end in '/' unless it is the root.
  138. def split(p):
  139. """Split a pathname.
  140. Return tuple (head, tail) where tail is everything after the final slash.
  141. Either part may be empty."""
  142. d, p = splitdrive(p)
  143. # set i to index beyond p's last slash
  144. i = len(p)
  145. while i and p[i-1] not in '/\\':
  146. i = i - 1
  147. head, tail = p[:i], p[i:] # now tail has no slashes
  148. # remove trailing slashes from head, unless it's all slashes
  149. head2 = head
  150. while head2 and head2[-1] in '/\\':
  151. head2 = head2[:-1]
  152. head = head2 or head
  153. return d + head, tail
  154. # Split a path in root and extension.
  155. # The extension is everything starting at the last dot in the last
  156. # pathname component; the root is everything before that.
  157. # It is always true that root + ext == p.
  158. def splitext(p):
  159. return genericpath._splitext(p, sep, altsep, extsep)
  160. splitext.__doc__ = genericpath._splitext.__doc__
  161. # Return the tail (basename) part of a path.
  162. def basename(p):
  163. """Returns the final component of a pathname"""
  164. return split(p)[1]
  165. # Return the head (dirname) part of a path.
  166. def dirname(p):
  167. """Returns the directory component of a pathname"""
  168. return split(p)[0]
  169. # Is a path a symbolic link?
  170. # This will always return false on systems where posix.lstat doesn't exist.
  171. def islink(path):
  172. """Test for symbolic link.
  173. On WindowsNT/95 and OS/2 always returns false
  174. """
  175. return False
  176. # alias exists to lexists
  177. lexists = exists
  178. # Is a path a mount point? Either a root (with or without drive letter)
  179. # or an UNC path with at most a / or \ after the mount point.
  180. def ismount(path):
  181. """Test whether a path is a mount point (defined as root of drive)"""
  182. unc, rest = splitunc(path)
  183. if unc:
  184. return rest in ("", "/", "\\")
  185. p = splitdrive(path)[1]
  186. return len(p) == 1 and p[0] in '/\\'
  187. # Directory tree walk.
  188. # For each directory under top (including top itself, but excluding
  189. # '.' and '..'), func(arg, dirname, filenames) is called, where
  190. # dirname is the name of the directory and filenames is the list
  191. # of files (and subdirectories etc.) in the directory.
  192. # The func may modify the filenames list, to implement a filter,
  193. # or to impose a different order of visiting.
  194. def walk(top, func, arg):
  195. """Directory tree walk with callback function.
  196. For each directory in the directory tree rooted at top (including top
  197. itself, but excluding '.' and '..'), call func(arg, dirname, fnames).
  198. dirname is the name of the directory, and fnames a list of the names of
  199. the files and subdirectories in dirname (excluding '.' and '..'). func
  200. may modify the fnames list in-place (e.g. via del or slice assignment),
  201. and walk will only recurse into the subdirectories whose names remain in
  202. fnames; this can be used to implement a filter, or to impose a specific
  203. order of visiting. No semantics are defined for, or required of, arg,
  204. beyond that arg is always passed to func. It can be used, e.g., to pass
  205. a filename pattern, or a mutable object designed to accumulate
  206. statistics. Passing None for arg is common."""
  207. warnings.warnpy3k("In 3.x, os.path.walk is removed in favor of os.walk.")
  208. try:
  209. names = os.listdir(top)
  210. except os.error:
  211. return
  212. func(arg, top, names)
  213. for name in names:
  214. name = join(top, name)
  215. if isdir(name):
  216. walk(name, func, arg)
  217. # Expand paths beginning with '~' or '~user'.
  218. # '~' means $HOME; '~user' means that user's home directory.
  219. # If the path doesn't begin with '~', or if the user or $HOME is unknown,
  220. # the path is returned unchanged (leaving error reporting to whatever
  221. # function is called with the expanded path as argument).
  222. # See also module 'glob' for expansion of *, ? and [...] in pathnames.
  223. # (A function should also be defined to do full *sh-style environment
  224. # variable expansion.)
  225. def expanduser(path):
  226. """Expand ~ and ~user constructs.
  227. If user or $HOME is unknown, do nothing."""
  228. if path[:1] != '~':
  229. return path
  230. i, n = 1, len(path)
  231. while i < n and path[i] not in '/\\':
  232. i = i + 1
  233. if 'HOME' in os.environ:
  234. userhome = os.environ['HOME']
  235. elif 'USERPROFILE' in os.environ:
  236. userhome = os.environ['USERPROFILE']
  237. elif not 'HOMEPATH' in os.environ:
  238. return path
  239. else:
  240. try:
  241. drive = os.environ['HOMEDRIVE']
  242. except KeyError:
  243. drive = ''
  244. userhome = join(drive, os.environ['HOMEPATH'])
  245. if i != 1: #~user
  246. userhome = join(dirname(userhome), path[1:i])
  247. return userhome + path[i:]
  248. # Expand paths containing shell variable substitutions.
  249. # The following rules apply:
  250. # - no expansion within single quotes
  251. # - '$$' is translated into '$'
  252. # - '%%' is translated into '%' if '%%' are not seen in %var1%%var2%
  253. # - ${varname} is accepted.
  254. # - $varname is accepted.
  255. # - %varname% is accepted.
  256. # - varnames can be made out of letters, digits and the characters '_-'
  257. # (though is not verifed in the ${varname} and %varname% cases)
  258. # XXX With COMMAND.COM you can use any characters in a variable name,
  259. # XXX except '^|<>='.
  260. def expandvars(path):
  261. """Expand shell variables of the forms $var, ${var} and %var%.
  262. Unknown variables are left unchanged."""
  263. if '$' not in path and '%' not in path:
  264. return path
  265. import string
  266. varchars = string.ascii_letters + string.digits + '_-'
  267. res = ''
  268. index = 0
  269. pathlen = len(path)
  270. while index < pathlen:
  271. c = path[index]
  272. if c == '\'': # no expansion within single quotes
  273. path = path[index + 1:]
  274. pathlen = len(path)
  275. try:
  276. index = path.index('\'')
  277. res = res + '\'' + path[:index + 1]
  278. except ValueError:
  279. res = res + path
  280. index = pathlen - 1
  281. elif c == '%': # variable or '%'
  282. if path[index + 1:index + 2] == '%':
  283. res = res + c
  284. index = index + 1
  285. else:
  286. path = path[index+1:]
  287. pathlen = len(path)
  288. try:
  289. index = path.index('%')
  290. except ValueError:
  291. res = res + '%' + path
  292. index = pathlen - 1
  293. else:
  294. var = path[:index]
  295. if var in os.environ:
  296. res = res + os.environ[var]
  297. else:
  298. res = res + '%' + var + '%'
  299. elif c == '$': # variable or '$$'
  300. if path[index + 1:index + 2] == '$':
  301. res = res + c
  302. index = index + 1
  303. elif path[index + 1:index + 2] == '{':
  304. path = path[index+2:]
  305. pathlen = len(path)
  306. try:
  307. index = path.index('}')
  308. var = path[:index]
  309. if var in os.environ:
  310. res = res + os.environ[var]
  311. else:
  312. res = res + '${' + var + '}'
  313. except ValueError:
  314. res = res + '${' + path
  315. index = pathlen - 1
  316. else:
  317. var = ''
  318. index = index + 1
  319. c = path[index:index + 1]
  320. while c != '' and c in varchars:
  321. var = var + c
  322. index = index + 1
  323. c = path[index:index + 1]
  324. if var in os.environ:
  325. res = res + os.environ[var]
  326. else:
  327. res = res + '$' + var
  328. if c != '':
  329. index = index - 1
  330. else:
  331. res = res + c
  332. index = index + 1
  333. return res
  334. # Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A\B.
  335. # Previously, this function also truncated pathnames to 8+3 format,
  336. # but as this module is called "ntpath", that's obviously wrong!
  337. def normpath(path):
  338. """Normalize path, eliminating double slashes, etc."""
  339. path = path.replace("/", "\\")
  340. prefix, path = splitdrive(path)
  341. # We need to be careful here. If the prefix is empty, and the path starts
  342. # with a backslash, it could either be an absolute path on the current
  343. # drive (\dir1\dir2\file) or a UNC filename (\\server\mount\dir1\file). It
  344. # is therefore imperative NOT to collapse multiple backslashes blindly in
  345. # that case.
  346. # The code below preserves multiple backslashes when there is no drive
  347. # letter. This means that the invalid filename \\\a\b is preserved
  348. # unchanged, where a\\\b is normalised to a\b. It's not clear that there
  349. # is any better behaviour for such edge cases.
  350. if prefix == '':
  351. # No drive letter - preserve initial backslashes
  352. while path[:1] == "\\":
  353. prefix = prefix + "\\"
  354. path = path[1:]
  355. else:
  356. # We have a drive letter - collapse initial backslashes
  357. if path.startswith("\\"):
  358. prefix = prefix + "\\"
  359. path = path.lstrip("\\")
  360. comps = path.split("\\")
  361. i = 0
  362. while i < len(comps):
  363. if comps[i] in ('.', ''):
  364. del comps[i]
  365. elif comps[i] == '..':
  366. if i > 0 and comps[i-1] != '..':
  367. del comps[i-1:i+1]
  368. i -= 1
  369. elif i == 0 and prefix.endswith("\\"):
  370. del comps[i]
  371. else:
  372. i += 1
  373. else:
  374. i += 1
  375. # If the path is now empty, substitute '.'
  376. if not prefix and not comps:
  377. comps.append('.')
  378. return prefix + "\\".join(comps)
  379. # Return an absolute path.
  380. try:
  381. from nt import _getfullpathname
  382. except ImportError: # not running on Windows - mock up something sensible
  383. def abspath(path):
  384. """Return the absolute version of a path."""
  385. if not isabs(path):
  386. path = join(os.getcwd(), path)
  387. return normpath(path)
  388. else: # use native Windows method on Windows
  389. def abspath(path):
  390. """Return the absolute version of a path."""
  391. if path: # Empty path must return current working directory.
  392. try:
  393. path = _getfullpathname(path)
  394. except WindowsError:
  395. pass # Bad path - return unchanged.
  396. else:
  397. path = os.getcwd()
  398. return normpath(path)
  399. # realpath is a no-op on systems without islink support
  400. realpath = abspath
  401. # Win9x family and earlier have no Unicode filename support.
  402. supports_unicode_filenames = (hasattr(sys, "getwindowsversion") and
  403. sys.getwindowsversion()[3] >= 2)
  404. def relpath(path, start=curdir):
  405. """Return a relative version of a path"""
  406. if not path:
  407. raise ValueError("no path specified")
  408. start_list = abspath(start).split(sep)
  409. path_list = abspath(path).split(sep)
  410. if start_list[0].lower() != path_list[0].lower():
  411. unc_path, rest = splitunc(path)
  412. unc_start, rest = splitunc(start)
  413. if bool(unc_path) ^ bool(unc_start):
  414. raise ValueError("Cannot mix UNC and non-UNC paths (%s and %s)"
  415. % (path, start))
  416. else:
  417. raise ValueError("path is on drive %s, start on drive %s"
  418. % (path_list[0], start_list[0]))
  419. # Work out how much of the filepath is shared by start and path.
  420. for i in range(min(len(start_list), len(path_list))):
  421. if start_list[i].lower() != path_list[i].lower():
  422. break
  423. else:
  424. i += 1
  425. rel_list = [pardir] * (len(start_list)-i) + path_list[i:]
  426. if not rel_list:
  427. return curdir
  428. return join(*rel_list)