filecmp.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. """Utilities for comparing files and directories.
  2. Classes:
  3. dircmp
  4. Functions:
  5. cmp(f1, f2, shallow=1) -> int
  6. cmpfiles(a, b, common) -> ([], [], [])
  7. """
  8. import os
  9. import stat
  10. from itertools import ifilter, ifilterfalse, imap, izip
  11. __all__ = ["cmp","dircmp","cmpfiles"]
  12. _cache = {}
  13. BUFSIZE=8*1024
  14. def cmp(f1, f2, shallow=1):
  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(izip(imap(os.path.normcase, self.left_list), self.left_list))
  107. b = dict(izip(imap(os.path.normcase, self.right_list), self.right_list))
  108. self.common = map(a.__getitem__, ifilter(b.__contains__, a))
  109. self.left_only = map(a.__getitem__, ifilterfalse(b.__contains__, a))
  110. self.right_only = map(b.__getitem__, ifilterfalse(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, why:
  122. # print 'Can\'t stat', a_path, ':', why[1]
  123. ok = 0
  124. try:
  125. b_stat = os.stat(b_path)
  126. except os.error, why:
  127. # print 'Can\'t stat', b_path, ':', why[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.itervalues():
  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.itervalues():
  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.itervalues():
  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=1):
  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, IOError):
  228. return 2
  229. # Return a copy with items that occur in skip removed.
  230. #
  231. def _filter(flist, skip):
  232. return list(ifilterfalse(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()