filecmp.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  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 instances (or MyDirCmp instances if this
  95. object is of type MyDirCmp, a subclass of dircmp), keyed by names
  96. in common_dirs.
  97. """
  98. def __init__(self, a, b, ignore=None, hide=None): # Initialize
  99. self.left = a
  100. self.right = b
  101. if hide is None:
  102. self.hide = [os.curdir, os.pardir] # Names never to be shown
  103. else:
  104. self.hide = hide
  105. if ignore is None:
  106. self.ignore = DEFAULT_IGNORES
  107. else:
  108. self.ignore = ignore
  109. def phase0(self): # Compare everything except common subdirectories
  110. self.left_list = _filter(os.listdir(self.left),
  111. self.hide+self.ignore)
  112. self.right_list = _filter(os.listdir(self.right),
  113. self.hide+self.ignore)
  114. self.left_list.sort()
  115. self.right_list.sort()
  116. def phase1(self): # Compute common names
  117. a = dict(zip(map(os.path.normcase, self.left_list), self.left_list))
  118. b = dict(zip(map(os.path.normcase, self.right_list), self.right_list))
  119. self.common = list(map(a.__getitem__, filter(b.__contains__, a)))
  120. self.left_only = list(map(a.__getitem__, filterfalse(b.__contains__, a)))
  121. self.right_only = list(map(b.__getitem__, filterfalse(a.__contains__, b)))
  122. def phase2(self): # Distinguish files, directories, funnies
  123. self.common_dirs = []
  124. self.common_files = []
  125. self.common_funny = []
  126. for x in self.common:
  127. a_path = os.path.join(self.left, x)
  128. b_path = os.path.join(self.right, x)
  129. ok = True
  130. try:
  131. a_stat = os.stat(a_path)
  132. except (OSError, ValueError):
  133. # See https://github.com/python/cpython/issues/122400
  134. # for the rationale for protecting against ValueError.
  135. # print('Can\'t stat', a_path, ':', why.args[1])
  136. ok = False
  137. try:
  138. b_stat = os.stat(b_path)
  139. except (OSError, ValueError):
  140. # print('Can\'t stat', b_path, ':', why.args[1])
  141. ok = False
  142. if ok:
  143. a_type = stat.S_IFMT(a_stat.st_mode)
  144. b_type = stat.S_IFMT(b_stat.st_mode)
  145. if a_type != b_type:
  146. self.common_funny.append(x)
  147. elif stat.S_ISDIR(a_type):
  148. self.common_dirs.append(x)
  149. elif stat.S_ISREG(a_type):
  150. self.common_files.append(x)
  151. else:
  152. self.common_funny.append(x)
  153. else:
  154. self.common_funny.append(x)
  155. def phase3(self): # Find out differences between common files
  156. xx = cmpfiles(self.left, self.right, self.common_files)
  157. self.same_files, self.diff_files, self.funny_files = xx
  158. def phase4(self): # Find out differences between common subdirectories
  159. # A new dircmp (or MyDirCmp if dircmp was subclassed) object is created
  160. # for each common subdirectory,
  161. # these are stored in a dictionary indexed by filename.
  162. # The hide and ignore properties are inherited from the parent
  163. self.subdirs = {}
  164. for x in self.common_dirs:
  165. a_x = os.path.join(self.left, x)
  166. b_x = os.path.join(self.right, x)
  167. self.subdirs[x] = self.__class__(a_x, b_x, self.ignore, self.hide)
  168. def phase4_closure(self): # Recursively call phase4() on subdirectories
  169. self.phase4()
  170. for sd in self.subdirs.values():
  171. sd.phase4_closure()
  172. def report(self): # Print a report on the differences between a and b
  173. # Output format is purposely lousy
  174. print('diff', self.left, self.right)
  175. if self.left_only:
  176. self.left_only.sort()
  177. print('Only in', self.left, ':', self.left_only)
  178. if self.right_only:
  179. self.right_only.sort()
  180. print('Only in', self.right, ':', self.right_only)
  181. if self.same_files:
  182. self.same_files.sort()
  183. print('Identical files :', self.same_files)
  184. if self.diff_files:
  185. self.diff_files.sort()
  186. print('Differing files :', self.diff_files)
  187. if self.funny_files:
  188. self.funny_files.sort()
  189. print('Trouble with common files :', self.funny_files)
  190. if self.common_dirs:
  191. self.common_dirs.sort()
  192. print('Common subdirectories :', self.common_dirs)
  193. if self.common_funny:
  194. self.common_funny.sort()
  195. print('Common funny cases :', self.common_funny)
  196. def report_partial_closure(self): # Print reports on self and on subdirs
  197. self.report()
  198. for sd in self.subdirs.values():
  199. print()
  200. sd.report()
  201. def report_full_closure(self): # Report on self and subdirs recursively
  202. self.report()
  203. for sd in self.subdirs.values():
  204. print()
  205. sd.report_full_closure()
  206. methodmap = dict(subdirs=phase4,
  207. same_files=phase3, diff_files=phase3, funny_files=phase3,
  208. common_dirs=phase2, common_files=phase2, common_funny=phase2,
  209. common=phase1, left_only=phase1, right_only=phase1,
  210. left_list=phase0, right_list=phase0)
  211. def __getattr__(self, attr):
  212. if attr not in self.methodmap:
  213. raise AttributeError(attr)
  214. self.methodmap[attr](self)
  215. return getattr(self, attr)
  216. __class_getitem__ = classmethod(GenericAlias)
  217. def cmpfiles(a, b, common, shallow=True):
  218. """Compare common files in two directories.
  219. a, b -- directory names
  220. common -- list of file names found in both directories
  221. shallow -- if true, do comparison based solely on stat() information
  222. Returns a tuple of three lists:
  223. files that compare equal
  224. files that are different
  225. filenames that aren't regular files.
  226. """
  227. res = ([], [], [])
  228. for x in common:
  229. ax = os.path.join(a, x)
  230. bx = os.path.join(b, x)
  231. res[_cmp(ax, bx, shallow)].append(x)
  232. return res
  233. # Compare two files.
  234. # Return:
  235. # 0 for equal
  236. # 1 for different
  237. # 2 for funny cases (can't stat, NUL bytes, etc.)
  238. #
  239. def _cmp(a, b, sh, abs=abs, cmp=cmp):
  240. try:
  241. return not abs(cmp(a, b, sh))
  242. except (OSError, ValueError):
  243. return 2
  244. # Return a copy with items that occur in skip removed.
  245. #
  246. def _filter(flist, skip):
  247. return list(filterfalse(skip.__contains__, flist))
  248. # Demonstration and testing.
  249. #
  250. def demo():
  251. import sys
  252. import getopt
  253. options, args = getopt.getopt(sys.argv[1:], 'r')
  254. if len(args) != 2:
  255. raise getopt.GetoptError('need exactly two args', None)
  256. dd = dircmp(args[0], args[1])
  257. if ('-r', '') in options:
  258. dd.report_full_closure()
  259. else:
  260. dd.report()
  261. if __name__ == '__main__':
  262. demo()