You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

296 lines
9.4 KiB

Merged revisions 70342,70385-70387,70389-70390,70392-70393,70395,70400,70405-70406,70418,70438,70464,70468 via svnmerge from svn+ssh://pythondev@svn.python.org/python/trunk ........ r70342 | georg.brandl | 2009-03-13 14:03:58 -0500 (Fri, 13 Mar 2009) | 1 line #5486: typos. ........ r70385 | benjamin.peterson | 2009-03-15 09:38:55 -0500 (Sun, 15 Mar 2009) | 1 line fix tuple.index() error message #5495 ........ r70386 | georg.brandl | 2009-03-15 16:32:06 -0500 (Sun, 15 Mar 2009) | 1 line #5496: fix docstring of lookup(). ........ r70387 | georg.brandl | 2009-03-15 16:37:16 -0500 (Sun, 15 Mar 2009) | 1 line #5493: clarify __nonzero__ docs. ........ r70389 | georg.brandl | 2009-03-15 16:43:38 -0500 (Sun, 15 Mar 2009) | 1 line Fix a small nit in the error message if bool() falls back on __len__ and it returns the wrong type: it would tell the user that __nonzero__ should return bool or int. ........ r70390 | georg.brandl | 2009-03-15 16:44:43 -0500 (Sun, 15 Mar 2009) | 1 line #5491: clarify nested() semantics. ........ r70392 | georg.brandl | 2009-03-15 16:46:00 -0500 (Sun, 15 Mar 2009) | 1 line #5488: add missing struct member. ........ r70393 | georg.brandl | 2009-03-15 16:47:42 -0500 (Sun, 15 Mar 2009) | 1 line #5478: fix copy-paste oversight in function signature. ........ r70395 | georg.brandl | 2009-03-15 16:51:48 -0500 (Sun, 15 Mar 2009) | 1 line #5276: document IDLESTARTUP and .Idle.py. ........ r70400 | georg.brandl | 2009-03-15 16:59:37 -0500 (Sun, 15 Mar 2009) | 3 lines Fix markup in re docs and give a mail address in regex howto, so that the recommendation to send suggestions to the author can be followed. ........ r70405 | georg.brandl | 2009-03-15 17:11:07 -0500 (Sun, 15 Mar 2009) | 7 lines Move the previously local import of threading to module level. This is cleaner and avoids lockups in obscure cases where a Queue is instantiated while the import lock is already held by another thread. OKed by Tim Peters. ........ r70406 | hirokazu.yamamoto | 2009-03-15 17:43:14 -0500 (Sun, 15 Mar 2009) | 1 line Added skip for old MSVC. ........ r70418 | georg.brandl | 2009-03-16 14:42:03 -0500 (Mon, 16 Mar 2009) | 1 line Add token markup. ........ r70438 | benjamin.peterson | 2009-03-17 15:29:51 -0500 (Tue, 17 Mar 2009) | 1 line I thought this was begging for an example ........ r70464 | benjamin.peterson | 2009-03-18 15:58:09 -0500 (Wed, 18 Mar 2009) | 1 line a much better example ........ r70468 | benjamin.peterson | 2009-03-18 22:04:31 -0500 (Wed, 18 Mar 2009) | 1 line close files after comparing them ........
17 years ago
  1. """Utilities for comparing files and directories.
  2. Classes:
  3. dircmp
  4. Functions:
  5. cmp(f1, f2, shallow=True) -> int
  6. cmpfiles(a, b, common) -> ([], [], [])
  7. """
  8. import os
  9. import stat
  10. from itertools import filterfalse
  11. __all__ = ["cmp", "dircmp", "cmpfiles"]
  12. _cache = {}
  13. BUFSIZE = 8*1024
  14. def cmp(f1, f2, shallow=True):
  15. """Compare two files.
  16. Arguments:
  17. f1 -- First file name
  18. f2 -- Second file name
  19. shallow -- Just check stat signature (do not read the files).
  20. defaults to 1.
  21. Return value:
  22. True if the files are the same, False otherwise.
  23. This function uses a cache for past comparisons and the results,
  24. with a cache invalidation mechanism relying on stale signatures.
  25. """
  26. s1 = _sig(os.stat(f1))
  27. s2 = _sig(os.stat(f2))
  28. if s1[0] != stat.S_IFREG or s2[0] != stat.S_IFREG:
  29. return False
  30. if shallow and s1 == s2:
  31. return True
  32. if s1[1] != s2[1]:
  33. return False
  34. outcome = _cache.get((f1, f2, s1, s2))
  35. if outcome is None:
  36. outcome = _do_cmp(f1, f2)
  37. if len(_cache) > 100: # limit the maximum size of the cache
  38. _cache.clear()
  39. _cache[f1, f2, s1, s2] = outcome
  40. return outcome
  41. def _sig(st):
  42. return (stat.S_IFMT(st.st_mode),
  43. st.st_size,
  44. st.st_mtime)
  45. def _do_cmp(f1, f2):
  46. bufsize = BUFSIZE
  47. with open(f1, 'rb') as fp1, open(f2, 'rb') as fp2:
  48. while True:
  49. b1 = fp1.read(bufsize)
  50. b2 = fp2.read(bufsize)
  51. if b1 != b2:
  52. return False
  53. if not b1:
  54. return True
  55. # Directory comparison class.
  56. #
  57. class dircmp:
  58. """A class that manages the comparison of 2 directories.
  59. dircmp(a, b, ignore=None, hide=None)
  60. A and B are directories.
  61. IGNORE is a list of names to ignore,
  62. defaults to ['RCS', 'CVS', 'tags'].
  63. HIDE is a list of names to hide,
  64. defaults to [os.curdir, os.pardir].
  65. High level usage:
  66. x = dircmp(dir1, dir2)
  67. x.report() -> prints a report on the differences between dir1 and dir2
  68. or
  69. x.report_partial_closure() -> prints report on differences between dir1
  70. and dir2, and reports on common immediate subdirectories.
  71. x.report_full_closure() -> like report_partial_closure,
  72. but fully recursive.
  73. Attributes:
  74. left_list, right_list: The files in dir1 and dir2,
  75. filtered by hide and ignore.
  76. common: a list of names in both dir1 and dir2.
  77. left_only, right_only: names only in dir1, dir2.
  78. common_dirs: subdirectories in both dir1 and dir2.
  79. common_files: files in both dir1 and dir2.
  80. common_funny: names in both dir1 and dir2 where the type differs between
  81. dir1 and dir2, or the name is not stat-able.
  82. same_files: list of identical files.
  83. diff_files: list of filenames which differ.
  84. funny_files: list of files which could not be compared.
  85. subdirs: a dictionary of dircmp objects, keyed by names in common_dirs.
  86. """
  87. def __init__(self, a, b, ignore=None, hide=None): # Initialize
  88. self.left = a
  89. self.right = b
  90. if hide is None:
  91. self.hide = [os.curdir, os.pardir] # Names never to be shown
  92. else:
  93. self.hide = hide
  94. if ignore is None:
  95. self.ignore = ['RCS', 'CVS', 'tags'] # Names ignored in comparison
  96. else:
  97. self.ignore = ignore
  98. def phase0(self): # Compare everything except common subdirectories
  99. self.left_list = _filter(os.listdir(self.left),
  100. self.hide+self.ignore)
  101. self.right_list = _filter(os.listdir(self.right),
  102. self.hide+self.ignore)
  103. self.left_list.sort()
  104. self.right_list.sort()
  105. def phase1(self): # Compute common names
  106. a = dict(zip(map(os.path.normcase, self.left_list), self.left_list))
  107. b = dict(zip(map(os.path.normcase, self.right_list), self.right_list))
  108. self.common = list(map(a.__getitem__, filter(b.__contains__, a)))
  109. self.left_only = list(map(a.__getitem__, filterfalse(b.__contains__, a)))
  110. self.right_only = list(map(b.__getitem__, filterfalse(a.__contains__, b)))
  111. def phase2(self): # Distinguish files, directories, funnies
  112. self.common_dirs = []
  113. self.common_files = []
  114. self.common_funny = []
  115. for x in self.common:
  116. a_path = os.path.join(self.left, x)
  117. b_path = os.path.join(self.right, x)
  118. ok = 1
  119. try:
  120. a_stat = os.stat(a_path)
  121. except os.error as why:
  122. # print('Can\'t stat', a_path, ':', why.args[1])
  123. ok = 0
  124. try:
  125. b_stat = os.stat(b_path)
  126. except os.error as why:
  127. # print('Can\'t stat', b_path, ':', why.args[1])
  128. ok = 0
  129. if ok:
  130. a_type = stat.S_IFMT(a_stat.st_mode)
  131. b_type = stat.S_IFMT(b_stat.st_mode)
  132. if a_type != b_type:
  133. self.common_funny.append(x)
  134. elif stat.S_ISDIR(a_type):
  135. self.common_dirs.append(x)
  136. elif stat.S_ISREG(a_type):
  137. self.common_files.append(x)
  138. else:
  139. self.common_funny.append(x)
  140. else:
  141. self.common_funny.append(x)
  142. def phase3(self): # Find out differences between common files
  143. xx = cmpfiles(self.left, self.right, self.common_files)
  144. self.same_files, self.diff_files, self.funny_files = xx
  145. def phase4(self): # Find out differences between common subdirectories
  146. # A new dircmp object is created for each common subdirectory,
  147. # these are stored in a dictionary indexed by filename.
  148. # The hide and ignore properties are inherited from the parent
  149. self.subdirs = {}
  150. for x in self.common_dirs:
  151. a_x = os.path.join(self.left, x)
  152. b_x = os.path.join(self.right, x)
  153. self.subdirs[x] = dircmp(a_x, b_x, self.ignore, self.hide)
  154. def phase4_closure(self): # Recursively call phase4() on subdirectories
  155. self.phase4()
  156. for sd in self.subdirs.values():
  157. sd.phase4_closure()
  158. def report(self): # Print a report on the differences between a and b
  159. # Output format is purposely lousy
  160. print('diff', self.left, self.right)
  161. if self.left_only:
  162. self.left_only.sort()
  163. print('Only in', self.left, ':', self.left_only)
  164. if self.right_only:
  165. self.right_only.sort()
  166. print('Only in', self.right, ':', self.right_only)
  167. if self.same_files:
  168. self.same_files.sort()
  169. print('Identical files :', self.same_files)
  170. if self.diff_files:
  171. self.diff_files.sort()
  172. print('Differing files :', self.diff_files)
  173. if self.funny_files:
  174. self.funny_files.sort()
  175. print('Trouble with common files :', self.funny_files)
  176. if self.common_dirs:
  177. self.common_dirs.sort()
  178. print('Common subdirectories :', self.common_dirs)
  179. if self.common_funny:
  180. self.common_funny.sort()
  181. print('Common funny cases :', self.common_funny)
  182. def report_partial_closure(self): # Print reports on self and on subdirs
  183. self.report()
  184. for sd in self.subdirs.values():
  185. print()
  186. sd.report()
  187. def report_full_closure(self): # Report on self and subdirs recursively
  188. self.report()
  189. for sd in self.subdirs.values():
  190. print()
  191. sd.report_full_closure()
  192. methodmap = dict(subdirs=phase4,
  193. same_files=phase3, diff_files=phase3, funny_files=phase3,
  194. common_dirs = phase2, common_files=phase2, common_funny=phase2,
  195. common=phase1, left_only=phase1, right_only=phase1,
  196. left_list=phase0, right_list=phase0)
  197. def __getattr__(self, attr):
  198. if attr not in self.methodmap:
  199. raise AttributeError(attr)
  200. self.methodmap[attr](self)
  201. return getattr(self, attr)
  202. def cmpfiles(a, b, common, shallow=True):
  203. """Compare common files in two directories.
  204. a, b -- directory names
  205. common -- list of file names found in both directories
  206. shallow -- if true, do comparison based solely on stat() information
  207. Returns a tuple of three lists:
  208. files that compare equal
  209. files that are different
  210. filenames that aren't regular files.
  211. """
  212. res = ([], [], [])
  213. for x in common:
  214. ax = os.path.join(a, x)
  215. bx = os.path.join(b, x)
  216. res[_cmp(ax, bx, shallow)].append(x)
  217. return res
  218. # Compare two files.
  219. # Return:
  220. # 0 for equal
  221. # 1 for different
  222. # 2 for funny cases (can't stat, etc.)
  223. #
  224. def _cmp(a, b, sh, abs=abs, cmp=cmp):
  225. try:
  226. return not abs(cmp(a, b, sh))
  227. except os.error:
  228. return 2
  229. # Return a copy with items that occur in skip removed.
  230. #
  231. def _filter(flist, skip):
  232. return list(filterfalse(skip.__contains__, flist))
  233. # Demonstration and testing.
  234. #
  235. def demo():
  236. import sys
  237. import getopt
  238. options, args = getopt.getopt(sys.argv[1:], 'r')
  239. if len(args) != 2:
  240. raise getopt.GetoptError('need exactly two args', None)
  241. dd = dircmp(args[0], args[1])
  242. if ('-r', '') in options:
  243. dd.report_full_closure()
  244. else:
  245. dd.report()
  246. if __name__ == '__main__':
  247. demo()