filecmp.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  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. clear_cache()
  8. """
  9. import os
  10. import stat
  11. from itertools import filterfalse
  12. from types import GenericAlias
  13. __all__ = ['clear_cache', 'cmp', 'dircmp', 'cmpfiles', 'DEFAULT_IGNORES']
  14. _cache = {}
  15. BUFSIZE = 8*1024
  16. DEFAULT_IGNORES = [
  17. 'RCS', 'CVS', 'tags', '.git', '.hg', '.bzr', '_darcs', '__pycache__']
  18. def clear_cache():
  19. """Clear the filecmp cache."""
  20. _cache.clear()
  21. def cmp(f1, f2, shallow=True):
  22. """Compare two files.
  23. Arguments:
  24. f1 -- First file name
  25. f2 -- Second file name
  26. shallow -- treat files as identical if their stat signatures (type, size,
  27. mtime) are identical. Otherwise, files are considered different
  28. if their sizes or contents differ. [default: True]
  29. Return value:
  30. True if the files are the same, False otherwise.
  31. This function uses a cache for past comparisons and the results,
  32. with cache entries invalidated if their stat information
  33. changes. The cache may be cleared by calling clear_cache().
  34. """
  35. s1 = _sig(os.stat(f1))
  36. s2 = _sig(os.stat(f2))
  37. if s1[0] != stat.S_IFREG or s2[0] != stat.S_IFREG:
  38. return False
  39. if shallow and s1 == s2:
  40. return True
  41. if s1[1] != s2[1]:
  42. return False
  43. outcome = _cache.get((f1, f2, s1, s2))
  44. if outcome is None:
  45. outcome = _do_cmp(f1, f2)
  46. if len(_cache) > 100: # limit the maximum size of the cache
  47. clear_cache()
  48. _cache[f1, f2, s1, s2] = outcome
  49. return outcome
  50. def _sig(st):
  51. return (stat.S_IFMT(st.st_mode),
  52. st.st_size,
  53. st.st_mtime)
  54. def _do_cmp(f1, f2):
  55. bufsize = BUFSIZE
  56. with open(f1, 'rb') as fp1, open(f2, 'rb') as fp2:
  57. while True:
  58. b1 = fp1.read(bufsize)
  59. b2 = fp2.read(bufsize)
  60. if b1 != b2:
  61. return False
  62. if not b1:
  63. return True
  64. # Directory comparison class.
  65. #
  66. class dircmp:
  67. """A class that manages the comparison of 2 directories.
  68. dircmp(a, b, ignore=None, hide=None)
  69. A and B are directories.
  70. IGNORE is a list of names to ignore,
  71. defaults to DEFAULT_IGNORES.
  72. HIDE is a list of names to hide,
  73. defaults to [os.curdir, os.pardir].
  74. High level usage:
  75. x = dircmp(dir1, dir2)
  76. x.report() -> prints a report on the differences between dir1 and dir2
  77. or
  78. x.report_partial_closure() -> prints report on differences between dir1
  79. and dir2, and reports on common immediate subdirectories.
  80. x.report_full_closure() -> like report_partial_closure,
  81. but fully recursive.
  82. Attributes:
  83. left_list, right_list: The files in dir1 and dir2,
  84. filtered by hide and ignore.
  85. common: a list of names in both dir1 and dir2.
  86. left_only, right_only: names only in dir1, dir2.
  87. common_dirs: subdirectories in both dir1 and dir2.
  88. common_files: files in both dir1 and dir2.
  89. common_funny: names in both dir1 and dir2 where the type differs between
  90. dir1 and dir2, or the name is not stat-able.
  91. same_files: list of identical files.
  92. diff_files: list of filenames which differ.
  93. funny_files: list of files which could not be compared.
  94. subdirs: a dictionary of dircmp objects, keyed by names in common_dirs.
  95. """
  96. def __init__(self, a, b, ignore=None, hide=None): # Initialize
  97. self.left = a
  98. self.right = b
  99. if hide is None:
  100. self.hide = [os.curdir, os.pardir] # Names never to be shown
  101. else:
  102. self.hide = hide
  103. if ignore is None:
  104. self.ignore = DEFAULT_IGNORES
  105. else:
  106. self.ignore = ignore
  107. def phase0(self): # Compare everything except common subdirectories
  108. self.left_list = _filter(os.listdir(self.left),
  109. self.hide+self.ignore)
  110. self.right_list = _filter(os.listdir(self.right),
  111. self.hide+self.ignore)
  112. self.left_list.sort()
  113. self.right_list.sort()
  114. def phase1(self): # Compute common names
  115. a = dict(zip(map(os.path.normcase, self.left_list), self.left_list))
  116. b = dict(zip(map(os.path.normcase, self.right_list), self.right_list))
  117. self.common = list(map(a.__getitem__, filter(b.__contains__, a)))
  118. self.left_only = list(map(a.__getitem__, filterfalse(b.__contains__, a)))
  119. self.right_only = list(map(b.__getitem__, filterfalse(a.__contains__, b)))
  120. def phase2(self): # Distinguish files, directories, funnies
  121. self.common_dirs = []
  122. self.common_files = []
  123. self.common_funny = []
  124. for x in self.common:
  125. a_path = os.path.join(self.left, x)
  126. b_path = os.path.join(self.right, x)
  127. ok = 1
  128. try:
  129. a_stat = os.stat(a_path)
  130. except OSError:
  131. # print('Can\'t stat', a_path, ':', why.args[1])
  132. ok = 0
  133. try:
  134. b_stat = os.stat(b_path)
  135. except OSError:
  136. # print('Can\'t stat', b_path, ':', why.args[1])
  137. ok = 0
  138. if ok:
  139. a_type = stat.S_IFMT(a_stat.st_mode)
  140. b_type = stat.S_IFMT(b_stat.st_mode)
  141. if a_type != b_type:
  142. self.common_funny.append(x)
  143. elif stat.S_ISDIR(a_type):
  144. self.common_dirs.append(x)
  145. elif stat.S_ISREG(a_type):
  146. self.common_files.append(x)
  147. else:
  148. self.common_funny.append(x)
  149. else:
  150. self.common_funny.append(x)
  151. def phase3(self): # Find out differences between common files
  152. xx = cmpfiles(self.left, self.right, self.common_files)
  153. self.same_files, self.diff_files, self.funny_files = xx
  154. def phase4(self): # Find out differences between common subdirectories
  155. # A new dircmp object is created for each common subdirectory,
  156. # these are stored in a dictionary indexed by filename.
  157. # The hide and ignore properties are inherited from the parent
  158. self.subdirs = {}
  159. for x in self.common_dirs:
  160. a_x = os.path.join(self.left, x)
  161. b_x = os.path.join(self.right, x)
  162. self.subdirs[x] = dircmp(a_x, b_x, self.ignore, self.hide)
  163. def phase4_closure(self): # Recursively call phase4() on subdirectories
  164. self.phase4()
  165. for sd in self.subdirs.values():
  166. sd.phase4_closure()
  167. def report(self): # Print a report on the differences between a and b
  168. # Output format is purposely lousy
  169. print('diff', self.left, self.right)
  170. if self.left_only:
  171. self.left_only.sort()
  172. print('Only in', self.left, ':', self.left_only)
  173. if self.right_only:
  174. self.right_only.sort()
  175. print('Only in', self.right, ':', self.right_only)
  176. if self.same_files:
  177. self.same_files.sort()
  178. print('Identical files :', self.same_files)
  179. if self.diff_files:
  180. self.diff_files.sort()
  181. print('Differing files :', self.diff_files)
  182. if self.funny_files:
  183. self.funny_files.sort()
  184. print('Trouble with common files :', self.funny_files)
  185. if self.common_dirs:
  186. self.common_dirs.sort()
  187. print('Common subdirectories :', self.common_dirs)
  188. if self.common_funny:
  189. self.common_funny.sort()
  190. print('Common funny cases :', self.common_funny)
  191. def report_partial_closure(self): # Print reports on self and on subdirs
  192. self.report()
  193. for sd in self.subdirs.values():
  194. print()
  195. sd.report()
  196. def report_full_closure(self): # Report on self and subdirs recursively
  197. self.report()
  198. for sd in self.subdirs.values():
  199. print()
  200. sd.report_full_closure()
  201. methodmap = dict(subdirs=phase4,
  202. same_files=phase3, diff_files=phase3, funny_files=phase3,
  203. common_dirs = phase2, common_files=phase2, common_funny=phase2,
  204. common=phase1, left_only=phase1, right_only=phase1,
  205. left_list=phase0, right_list=phase0)
  206. def __getattr__(self, attr):
  207. if attr not in self.methodmap:
  208. raise AttributeError(attr)
  209. self.methodmap[attr](self)
  210. return getattr(self, attr)
  211. __class_getitem__ = classmethod(GenericAlias)
  212. def cmpfiles(a, b, common, shallow=True):
  213. """Compare common files in two directories.
  214. a, b -- directory names
  215. common -- list of file names found in both directories
  216. shallow -- if true, do comparison based solely on stat() information
  217. Returns a tuple of three lists:
  218. files that compare equal
  219. files that are different
  220. filenames that aren't regular files.
  221. """
  222. res = ([], [], [])
  223. for x in common:
  224. ax = os.path.join(a, x)
  225. bx = os.path.join(b, x)
  226. res[_cmp(ax, bx, shallow)].append(x)
  227. return res
  228. # Compare two files.
  229. # Return:
  230. # 0 for equal
  231. # 1 for different
  232. # 2 for funny cases (can't stat, etc.)
  233. #
  234. def _cmp(a, b, sh, abs=abs, cmp=cmp):
  235. try:
  236. return not abs(cmp(a, b, sh))
  237. except OSError:
  238. return 2
  239. # Return a copy with items that occur in skip removed.
  240. #
  241. def _filter(flist, skip):
  242. return list(filterfalse(skip.__contains__, flist))
  243. # Demonstration and testing.
  244. #
  245. def demo():
  246. import sys
  247. import getopt
  248. options, args = getopt.getopt(sys.argv[1:], 'r')
  249. if len(args) != 2:
  250. raise getopt.GetoptError('need exactly two args', None)
  251. dd = dircmp(args[0], args[1])
  252. if ('-r', '') in options:
  253. dd.report_full_closure()
  254. else:
  255. dd.report()
  256. if __name__ == '__main__':
  257. demo()