blob: 70a4b23c982205d4e68d3aab5c7277fe1cbfdaae [file] [log] [blame]
Guido van Rossum63b08ac2000-06-29 14:13:28 +00001"""Utilities for comparing files and directories.
Guido van Rossum2d726871999-10-26 14:02:01 +00002
Guido van Rossum63b08ac2000-06-29 14:13:28 +00003Classes:
4 dircmp
5
6Functions:
Georg Brandl55689c92009-05-17 12:19:44 +00007 cmp(f1, f2, shallow=True) -> int
Guido van Rossum63b08ac2000-06-29 14:13:28 +00008 cmpfiles(a, b, common) -> ([], [], [])
Ned Deily7bff3cb2013-06-14 15:19:11 -07009 clear_cache()
Guido van Rossum63b08ac2000-06-29 14:13:28 +000010
11"""
12
13import os
14import stat
Raymond Hettinger736c0ab2008-03-13 02:09:15 +000015from itertools import filterfalse
Ethan Smithe3ec44d2020-04-09 21:47:31 -070016from types import GenericAlias
Guido van Rossum2d726871999-10-26 14:02:01 +000017
Ned Deily7bff3cb2013-06-14 15:19:11 -070018__all__ = ['clear_cache', 'cmp', 'dircmp', 'cmpfiles', 'DEFAULT_IGNORES']
Skip Montanaroeccd02a2001-01-20 23:34:12 +000019
Guido van Rossum2d726871999-10-26 14:02:01 +000020_cache = {}
Georg Brandl55689c92009-05-17 12:19:44 +000021BUFSIZE = 8*1024
Guido van Rossum2d726871999-10-26 14:02:01 +000022
Eli Benderskyeb2884a2013-01-12 06:13:32 -080023DEFAULT_IGNORES = [
24 'RCS', 'CVS', 'tags', '.git', '.hg', '.bzr', '_darcs', '__pycache__']
25
Ned Deily7bff3cb2013-06-14 15:19:11 -070026def clear_cache():
27 """Clear the filecmp cache."""
28 _cache.clear()
Eli Benderskyeb2884a2013-01-12 06:13:32 -080029
Georg Brandl55689c92009-05-17 12:19:44 +000030def cmp(f1, f2, shallow=True):
Guido van Rossum63b08ac2000-06-29 14:13:28 +000031 """Compare two files.
Guido van Rossum2d726871999-10-26 14:02:01 +000032
Guido van Rossum63b08ac2000-06-29 14:13:28 +000033 Arguments:
Guido van Rossum2d726871999-10-26 14:02:01 +000034
Guido van Rossum63b08ac2000-06-29 14:13:28 +000035 f1 -- First file name
Guido van Rossum2d726871999-10-26 14:02:01 +000036
Guido van Rossum63b08ac2000-06-29 14:13:28 +000037 f2 -- Second file name
Guido van Rossum2d726871999-10-26 14:02:01 +000038
Miss Islington (bot)c2593b42021-08-04 13:03:33 -070039 shallow -- treat files as identical if their stat signatures (type, size,
40 mtime) are identical. Otherwise, files are considered different
41 if their sizes or contents differ. [default: True]
Guido van Rossum2d726871999-10-26 14:02:01 +000042
Guido van Rossum63b08ac2000-06-29 14:13:28 +000043 Return value:
Guido van Rossum2d726871999-10-26 14:02:01 +000044
Tim Petersbc0e9102002-04-04 22:55:58 +000045 True if the files are the same, False otherwise.
Guido van Rossum2d726871999-10-26 14:02:01 +000046
Guido van Rossum63b08ac2000-06-29 14:13:28 +000047 This function uses a cache for past comparisons and the results,
R David Murray4885f492014-02-02 11:11:01 -050048 with cache entries invalidated if their stat information
49 changes. The cache may be cleared by calling clear_cache().
Guido van Rossum2d726871999-10-26 14:02:01 +000050
Guido van Rossum63b08ac2000-06-29 14:13:28 +000051 """
Andrew M. Kuchling83e879d2003-02-06 19:38:45 +000052
Andrew M. Kuchling8eb40442003-02-06 17:50:01 +000053 s1 = _sig(os.stat(f1))
54 s2 = _sig(os.stat(f2))
Guido van Rossum63b08ac2000-06-29 14:13:28 +000055 if s1[0] != stat.S_IFREG or s2[0] != stat.S_IFREG:
Tim Petersbc0e9102002-04-04 22:55:58 +000056 return False
Guido van Rossum63b08ac2000-06-29 14:13:28 +000057 if shallow and s1 == s2:
Tim Petersbc0e9102002-04-04 22:55:58 +000058 return True
Guido van Rossum63b08ac2000-06-29 14:13:28 +000059 if s1[1] != s2[1]:
Tim Petersbc0e9102002-04-04 22:55:58 +000060 return False
Guido van Rossum2d726871999-10-26 14:02:01 +000061
Raymond Hettinger70797192011-06-25 17:20:21 +020062 outcome = _cache.get((f1, f2, s1, s2))
63 if outcome is None:
64 outcome = _do_cmp(f1, f2)
65 if len(_cache) > 100: # limit the maximum size of the cache
Ned Deily7bff3cb2013-06-14 15:19:11 -070066 clear_cache()
Raymond Hettinger70797192011-06-25 17:20:21 +020067 _cache[f1, f2, s1, s2] = outcome
Guido van Rossum63b08ac2000-06-29 14:13:28 +000068 return outcome
Guido van Rossum2d726871999-10-26 14:02:01 +000069
70def _sig(st):
Raymond Hettinger32200ae2002-06-01 19:51:15 +000071 return (stat.S_IFMT(st.st_mode),
72 st.st_size,
73 st.st_mtime)
Guido van Rossum2d726871999-10-26 14:02:01 +000074
75def _do_cmp(f1, f2):
Guido van Rossum63b08ac2000-06-29 14:13:28 +000076 bufsize = BUFSIZE
Raymond Hettinger686057b2009-06-04 00:11:54 +000077 with open(f1, 'rb') as fp1, open(f2, 'rb') as fp2:
Benjamin Petersonf07d0022009-03-21 17:31:58 +000078 while True:
79 b1 = fp1.read(bufsize)
80 b2 = fp2.read(bufsize)
81 if b1 != b2:
82 return False
83 if not b1:
84 return True
Guido van Rossum63b08ac2000-06-29 14:13:28 +000085
86# Directory comparison class.
87#
88class dircmp:
89 """A class that manages the comparison of 2 directories.
90
Georg Brandl55689c92009-05-17 12:19:44 +000091 dircmp(a, b, ignore=None, hide=None)
Guido van Rossum63b08ac2000-06-29 14:13:28 +000092 A and B are directories.
93 IGNORE is a list of names to ignore,
Eli Benderskyeb2884a2013-01-12 06:13:32 -080094 defaults to DEFAULT_IGNORES.
Guido van Rossum63b08ac2000-06-29 14:13:28 +000095 HIDE is a list of names to hide,
96 defaults to [os.curdir, os.pardir].
97
98 High level usage:
99 x = dircmp(dir1, dir2)
100 x.report() -> prints a report on the differences between dir1 and dir2
101 or
102 x.report_partial_closure() -> prints report on differences between dir1
103 and dir2, and reports on common immediate subdirectories.
104 x.report_full_closure() -> like report_partial_closure,
105 but fully recursive.
106
107 Attributes:
108 left_list, right_list: The files in dir1 and dir2,
109 filtered by hide and ignore.
110 common: a list of names in both dir1 and dir2.
111 left_only, right_only: names only in dir1, dir2.
112 common_dirs: subdirectories in both dir1 and dir2.
113 common_files: files in both dir1 and dir2.
114 common_funny: names in both dir1 and dir2 where the type differs between
115 dir1 and dir2, or the name is not stat-able.
116 same_files: list of identical files.
117 diff_files: list of filenames which differ.
118 funny_files: list of files which could not be compared.
Nick Crews2f2f9d02020-11-23 09:29:37 -0700119 subdirs: a dictionary of dircmp instances (or MyDirCmp instances if this
120 object is of type MyDirCmp, a subclass of dircmp), keyed by names
121 in common_dirs.
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000122 """
123
124 def __init__(self, a, b, ignore=None, hide=None): # Initialize
125 self.left = a
126 self.right = b
127 if hide is None:
128 self.hide = [os.curdir, os.pardir] # Names never to be shown
129 else:
130 self.hide = hide
131 if ignore is None:
Eli Benderskyeb2884a2013-01-12 06:13:32 -0800132 self.ignore = DEFAULT_IGNORES
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000133 else:
134 self.ignore = ignore
135
136 def phase0(self): # Compare everything except common subdirectories
137 self.left_list = _filter(os.listdir(self.left),
138 self.hide+self.ignore)
139 self.right_list = _filter(os.listdir(self.right),
140 self.hide+self.ignore)
141 self.left_list.sort()
142 self.right_list.sort()
143
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000144 def phase1(self): # Compute common names
Raymond Hettinger736c0ab2008-03-13 02:09:15 +0000145 a = dict(zip(map(os.path.normcase, self.left_list), self.left_list))
146 b = dict(zip(map(os.path.normcase, self.right_list), self.right_list))
Raymond Hettinger17301e92008-03-13 00:19:26 +0000147 self.common = list(map(a.__getitem__, filter(b.__contains__, a)))
Raymond Hettingerb0002d22008-03-13 01:41:43 +0000148 self.left_only = list(map(a.__getitem__, filterfalse(b.__contains__, a)))
149 self.right_only = list(map(b.__getitem__, filterfalse(a.__contains__, b)))
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000150
151 def phase2(self): # Distinguish files, directories, funnies
152 self.common_dirs = []
153 self.common_files = []
154 self.common_funny = []
155
156 for x in self.common:
157 a_path = os.path.join(self.left, x)
158 b_path = os.path.join(self.right, x)
159
160 ok = 1
161 try:
Andrew M. Kuchling8eb40442003-02-06 17:50:01 +0000162 a_stat = os.stat(a_path)
Pablo Galindo293dd232019-11-19 21:34:03 +0000163 except OSError:
Georg Brandld11b68a2008-01-06 21:13:42 +0000164 # print('Can\'t stat', a_path, ':', why.args[1])
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000165 ok = 0
166 try:
Andrew M. Kuchling8eb40442003-02-06 17:50:01 +0000167 b_stat = os.stat(b_path)
Pablo Galindo293dd232019-11-19 21:34:03 +0000168 except OSError:
Georg Brandld11b68a2008-01-06 21:13:42 +0000169 # print('Can\'t stat', b_path, ':', why.args[1])
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000170 ok = 0
171
172 if ok:
Raymond Hettinger32200ae2002-06-01 19:51:15 +0000173 a_type = stat.S_IFMT(a_stat.st_mode)
174 b_type = stat.S_IFMT(b_stat.st_mode)
Fred Drake8152d322000-12-12 23:20:45 +0000175 if a_type != b_type:
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000176 self.common_funny.append(x)
177 elif stat.S_ISDIR(a_type):
178 self.common_dirs.append(x)
179 elif stat.S_ISREG(a_type):
180 self.common_files.append(x)
181 else:
182 self.common_funny.append(x)
183 else:
184 self.common_funny.append(x)
185
186 def phase3(self): # Find out differences between common files
187 xx = cmpfiles(self.left, self.right, self.common_files)
188 self.same_files, self.diff_files, self.funny_files = xx
189
190 def phase4(self): # Find out differences between common subdirectories
Nick Crews2f2f9d02020-11-23 09:29:37 -0700191 # A new dircmp (or MyDirCmp if dircmp was subclassed) object is created
192 # for each common subdirectory,
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000193 # these are stored in a dictionary indexed by filename.
194 # The hide and ignore properties are inherited from the parent
195 self.subdirs = {}
196 for x in self.common_dirs:
197 a_x = os.path.join(self.left, x)
198 b_x = os.path.join(self.right, x)
Nick Crews2f2f9d02020-11-23 09:29:37 -0700199 self.subdirs[x] = self.__class__(a_x, b_x, self.ignore, self.hide)
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000200
201 def phase4_closure(self): # Recursively call phase4() on subdirectories
202 self.phase4()
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000203 for sd in self.subdirs.values():
Raymond Hettingere0d49722002-06-02 18:55:56 +0000204 sd.phase4_closure()
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000205
206 def report(self): # Print a report on the differences between a and b
207 # Output format is purposely lousy
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000208 print('diff', self.left, self.right)
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000209 if self.left_only:
210 self.left_only.sort()
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000211 print('Only in', self.left, ':', self.left_only)
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000212 if self.right_only:
213 self.right_only.sort()
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000214 print('Only in', self.right, ':', self.right_only)
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000215 if self.same_files:
216 self.same_files.sort()
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000217 print('Identical files :', self.same_files)
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000218 if self.diff_files:
219 self.diff_files.sort()
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000220 print('Differing files :', self.diff_files)
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000221 if self.funny_files:
222 self.funny_files.sort()
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000223 print('Trouble with common files :', self.funny_files)
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000224 if self.common_dirs:
225 self.common_dirs.sort()
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000226 print('Common subdirectories :', self.common_dirs)
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000227 if self.common_funny:
228 self.common_funny.sort()
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000229 print('Common funny cases :', self.common_funny)
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000230
231 def report_partial_closure(self): # Print reports on self and on subdirs
232 self.report()
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000233 for sd in self.subdirs.values():
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000234 print()
Raymond Hettingere0d49722002-06-02 18:55:56 +0000235 sd.report()
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000236
237 def report_full_closure(self): # Report on self and subdirs recursively
238 self.report()
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000239 for sd in self.subdirs.values():
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000240 print()
Raymond Hettingere0d49722002-06-02 18:55:56 +0000241 sd.report_full_closure()
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000242
Raymond Hettinger05595e92003-02-27 00:05:31 +0000243 methodmap = dict(subdirs=phase4,
244 same_files=phase3, diff_files=phase3, funny_files=phase3,
245 common_dirs = phase2, common_files=phase2, common_funny=phase2,
246 common=phase1, left_only=phase1, right_only=phase1,
247 left_list=phase0, right_list=phase0)
248
249 def __getattr__(self, attr):
250 if attr not in self.methodmap:
Collin Winterce36ad82007-08-30 01:19:48 +0000251 raise AttributeError(attr)
Raymond Hettinger05595e92003-02-27 00:05:31 +0000252 self.methodmap[attr](self)
253 return getattr(self, attr)
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000254
Ethan Smithe3ec44d2020-04-09 21:47:31 -0700255 __class_getitem__ = classmethod(GenericAlias)
256
257
Georg Brandl55689c92009-05-17 12:19:44 +0000258def cmpfiles(a, b, common, shallow=True):
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000259 """Compare common files in two directories.
260
Fred Drake2b0d98b2000-07-03 08:18:47 +0000261 a, b -- directory names
262 common -- list of file names found in both directories
263 shallow -- if true, do comparison based solely on stat() information
Fred Drake2b0d98b2000-07-03 08:18:47 +0000264
265 Returns a tuple of three lists:
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000266 files that compare equal
267 files that are different
Fred Drake2b0d98b2000-07-03 08:18:47 +0000268 filenames that aren't regular files.
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000269
Fred Drake2b0d98b2000-07-03 08:18:47 +0000270 """
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000271 res = ([], [], [])
272 for x in common:
Fred Drake2b0d98b2000-07-03 08:18:47 +0000273 ax = os.path.join(a, x)
274 bx = os.path.join(b, x)
Andrew M. Kuchling8eb40442003-02-06 17:50:01 +0000275 res[_cmp(ax, bx, shallow)].append(x)
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000276 return res
277
278
279# Compare two files.
280# Return:
Tim Peters88869f92001-01-14 23:36:06 +0000281# 0 for equal
282# 1 for different
283# 2 for funny cases (can't stat, etc.)
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000284#
Raymond Hettinger05595e92003-02-27 00:05:31 +0000285def _cmp(a, b, sh, abs=abs, cmp=cmp):
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000286 try:
Andrew M. Kuchling8eb40442003-02-06 17:50:01 +0000287 return not abs(cmp(a, b, sh))
Andrew Svetlov22f36ee2012-12-14 18:02:27 +0200288 except OSError:
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000289 return 2
290
291
292# Return a copy with items that occur in skip removed.
293#
Raymond Hettinger05595e92003-02-27 00:05:31 +0000294def _filter(flist, skip):
Raymond Hettingerb0002d22008-03-13 01:41:43 +0000295 return list(filterfalse(skip.__contains__, flist))
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000296
297
298# Demonstration and testing.
299#
300def demo():
301 import sys
302 import getopt
303 options, args = getopt.getopt(sys.argv[1:], 'r')
Fred Drake8152d322000-12-12 23:20:45 +0000304 if len(args) != 2:
Andrew M. Kuchling83e879d2003-02-06 19:38:45 +0000305 raise getopt.GetoptError('need exactly two args', None)
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000306 dd = dircmp(args[0], args[1])
307 if ('-r', '') in options:
308 dd.report_full_closure()
309 else:
310 dd.report()
311
312if __name__ == '__main__':
313 demo()