filecmp.py 9.9 KB

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