blob: 7c47eb022cc8c0939c5a49264462afa8e9a149b2 [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
Guido van Rossum63b08ac2000-06-29 14:13:28 +000039 shallow -- Just check stat signature (do not read the files).
Benjamin Petersond4992dc2014-04-26 13:36:21 -040040 defaults to True.
Guido van Rossum2d726871999-10-26 14:02:01 +000041
Guido van Rossum63b08ac2000-06-29 14:13:28 +000042 Return value:
Guido van Rossum2d726871999-10-26 14:02:01 +000043
Tim Petersbc0e9102002-04-04 22:55:58 +000044 True if the files are the same, False otherwise.
Guido van Rossum2d726871999-10-26 14:02:01 +000045
Guido van Rossum63b08ac2000-06-29 14:13:28 +000046 This function uses a cache for past comparisons and the results,
R David Murray4885f492014-02-02 11:11:01 -050047 with cache entries invalidated if their stat information
48 changes. The cache may be cleared by calling clear_cache().
Guido van Rossum2d726871999-10-26 14:02:01 +000049
Guido van Rossum63b08ac2000-06-29 14:13:28 +000050 """
Andrew M. Kuchling83e879d2003-02-06 19:38:45 +000051
Andrew M. Kuchling8eb40442003-02-06 17:50:01 +000052 s1 = _sig(os.stat(f1))
53 s2 = _sig(os.stat(f2))
Guido van Rossum63b08ac2000-06-29 14:13:28 +000054 if s1[0] != stat.S_IFREG or s2[0] != stat.S_IFREG:
Tim Petersbc0e9102002-04-04 22:55:58 +000055 return False
Guido van Rossum63b08ac2000-06-29 14:13:28 +000056 if shallow and s1 == s2:
Tim Petersbc0e9102002-04-04 22:55:58 +000057 return True
Guido van Rossum63b08ac2000-06-29 14:13:28 +000058 if s1[1] != s2[1]:
Tim Petersbc0e9102002-04-04 22:55:58 +000059 return False
Guido van Rossum2d726871999-10-26 14:02:01 +000060
Raymond Hettinger70797192011-06-25 17:20:21 +020061 outcome = _cache.get((f1, f2, s1, s2))
62 if outcome is None:
63 outcome = _do_cmp(f1, f2)
64 if len(_cache) > 100: # limit the maximum size of the cache
Ned Deily7bff3cb2013-06-14 15:19:11 -070065 clear_cache()
Raymond Hettinger70797192011-06-25 17:20:21 +020066 _cache[f1, f2, s1, s2] = outcome
Guido van Rossum63b08ac2000-06-29 14:13:28 +000067 return outcome
Guido van Rossum2d726871999-10-26 14:02:01 +000068
69def _sig(st):
Raymond Hettinger32200ae2002-06-01 19:51:15 +000070 return (stat.S_IFMT(st.st_mode),
71 st.st_size,
72 st.st_mtime)
Guido van Rossum2d726871999-10-26 14:02:01 +000073
74def _do_cmp(f1, f2):
Guido van Rossum63b08ac2000-06-29 14:13:28 +000075 bufsize = BUFSIZE
Raymond Hettinger686057b2009-06-04 00:11:54 +000076 with open(f1, 'rb') as fp1, open(f2, 'rb') as fp2:
Benjamin Petersonf07d0022009-03-21 17:31:58 +000077 while True:
78 b1 = fp1.read(bufsize)
79 b2 = fp2.read(bufsize)
80 if b1 != b2:
81 return False
82 if not b1:
83 return True
Guido van Rossum63b08ac2000-06-29 14:13:28 +000084
85# Directory comparison class.
86#
87class dircmp:
88 """A class that manages the comparison of 2 directories.
89
Georg Brandl55689c92009-05-17 12:19:44 +000090 dircmp(a, b, ignore=None, hide=None)
Guido van Rossum63b08ac2000-06-29 14:13:28 +000091 A and B are directories.
92 IGNORE is a list of names to ignore,
Eli Benderskyeb2884a2013-01-12 06:13:32 -080093 defaults to DEFAULT_IGNORES.
Guido van Rossum63b08ac2000-06-29 14:13:28 +000094 HIDE is a list of names to hide,
95 defaults to [os.curdir, os.pardir].
96
97 High level usage:
98 x = dircmp(dir1, dir2)
99 x.report() -> prints a report on the differences between dir1 and dir2
100 or
101 x.report_partial_closure() -> prints report on differences between dir1
102 and dir2, and reports on common immediate subdirectories.
103 x.report_full_closure() -> like report_partial_closure,
104 but fully recursive.
105
106 Attributes:
107 left_list, right_list: The files in dir1 and dir2,
108 filtered by hide and ignore.
109 common: a list of names in both dir1 and dir2.
110 left_only, right_only: names only in dir1, dir2.
111 common_dirs: subdirectories in both dir1 and dir2.
112 common_files: files in both dir1 and dir2.
113 common_funny: names in both dir1 and dir2 where the type differs between
114 dir1 and dir2, or the name is not stat-able.
115 same_files: list of identical files.
116 diff_files: list of filenames which differ.
117 funny_files: list of files which could not be compared.
Nick Crews2f2f9d02020-11-23 09:29:37 -0700118 subdirs: a dictionary of dircmp instances (or MyDirCmp instances if this
119 object is of type MyDirCmp, a subclass of dircmp), keyed by names
120 in common_dirs.
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000121 """
122
123 def __init__(self, a, b, ignore=None, hide=None): # Initialize
124 self.left = a
125 self.right = b
126 if hide is None:
127 self.hide = [os.curdir, os.pardir] # Names never to be shown
128 else:
129 self.hide = hide
130 if ignore is None:
Eli Benderskyeb2884a2013-01-12 06:13:32 -0800131 self.ignore = DEFAULT_IGNORES
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000132 else:
133 self.ignore = ignore
134
135 def phase0(self): # Compare everything except common subdirectories
136 self.left_list = _filter(os.listdir(self.left),
137 self.hide+self.ignore)
138 self.right_list = _filter(os.listdir(self.right),
139 self.hide+self.ignore)
140 self.left_list.sort()
141 self.right_list.sort()
142
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000143 def phase1(self): # Compute common names
Raymond Hettinger736c0ab2008-03-13 02:09:15 +0000144 a = dict(zip(map(os.path.normcase, self.left_list), self.left_list))
145 b = dict(zip(map(os.path.normcase, self.right_list), self.right_list))
Raymond Hettinger17301e92008-03-13 00:19:26 +0000146 self.common = list(map(a.__getitem__, filter(b.__contains__, a)))
Raymond Hettingerb0002d22008-03-13 01:41:43 +0000147 self.left_only = list(map(a.__getitem__, filterfalse(b.__contains__, a)))
148 self.right_only = list(map(b.__getitem__, filterfalse(a.__contains__, b)))
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000149
150 def phase2(self): # Distinguish files, directories, funnies
151 self.common_dirs = []
152 self.common_files = []
153 self.common_funny = []
154
155 for x in self.common:
156 a_path = os.path.join(self.left, x)
157 b_path = os.path.join(self.right, x)
158
159 ok = 1
160 try:
Andrew M. Kuchling8eb40442003-02-06 17:50:01 +0000161 a_stat = os.stat(a_path)
Pablo Galindo293dd232019-11-19 21:34:03 +0000162 except OSError:
Georg Brandld11b68a2008-01-06 21:13:42 +0000163 # print('Can\'t stat', a_path, ':', why.args[1])
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000164 ok = 0
165 try:
Andrew M. Kuchling8eb40442003-02-06 17:50:01 +0000166 b_stat = os.stat(b_path)
Pablo Galindo293dd232019-11-19 21:34:03 +0000167 except OSError:
Georg Brandld11b68a2008-01-06 21:13:42 +0000168 # print('Can\'t stat', b_path, ':', why.args[1])
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000169 ok = 0
170
171 if ok:
Raymond Hettinger32200ae2002-06-01 19:51:15 +0000172 a_type = stat.S_IFMT(a_stat.st_mode)
173 b_type = stat.S_IFMT(b_stat.st_mode)
Fred Drake8152d322000-12-12 23:20:45 +0000174 if a_type != b_type:
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000175 self.common_funny.append(x)
176 elif stat.S_ISDIR(a_type):
177 self.common_dirs.append(x)
178 elif stat.S_ISREG(a_type):
179 self.common_files.append(x)
180 else:
181 self.common_funny.append(x)
182 else:
183 self.common_funny.append(x)
184
185 def phase3(self): # Find out differences between common files
186 xx = cmpfiles(self.left, self.right, self.common_files)
187 self.same_files, self.diff_files, self.funny_files = xx
188
189 def phase4(self): # Find out differences between common subdirectories
Nick Crews2f2f9d02020-11-23 09:29:37 -0700190 # A new dircmp (or MyDirCmp if dircmp was subclassed) object is created
191 # for each common subdirectory,
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000192 # these are stored in a dictionary indexed by filename.
193 # The hide and ignore properties are inherited from the parent
194 self.subdirs = {}
195 for x in self.common_dirs:
196 a_x = os.path.join(self.left, x)
197 b_x = os.path.join(self.right, x)
Nick Crews2f2f9d02020-11-23 09:29:37 -0700198 self.subdirs[x] = self.__class__(a_x, b_x, self.ignore, self.hide)
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000199
200 def phase4_closure(self): # Recursively call phase4() on subdirectories
201 self.phase4()
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000202 for sd in self.subdirs.values():
Raymond Hettingere0d49722002-06-02 18:55:56 +0000203 sd.phase4_closure()
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000204
205 def report(self): # Print a report on the differences between a and b
206 # Output format is purposely lousy
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000207 print('diff', self.left, self.right)
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000208 if self.left_only:
209 self.left_only.sort()
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000210 print('Only in', self.left, ':', self.left_only)
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000211 if self.right_only:
212 self.right_only.sort()
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000213 print('Only in', self.right, ':', self.right_only)
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000214 if self.same_files:
215 self.same_files.sort()
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000216 print('Identical files :', self.same_files)
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000217 if self.diff_files:
218 self.diff_files.sort()
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000219 print('Differing files :', self.diff_files)
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000220 if self.funny_files:
221 self.funny_files.sort()
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000222 print('Trouble with common files :', self.funny_files)
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000223 if self.common_dirs:
224 self.common_dirs.sort()
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000225 print('Common subdirectories :', self.common_dirs)
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000226 if self.common_funny:
227 self.common_funny.sort()
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000228 print('Common funny cases :', self.common_funny)
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000229
230 def report_partial_closure(self): # Print reports on self and on subdirs
231 self.report()
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000232 for sd in self.subdirs.values():
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000233 print()
Raymond Hettingere0d49722002-06-02 18:55:56 +0000234 sd.report()
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000235
236 def report_full_closure(self): # Report on self and subdirs recursively
237 self.report()
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000238 for sd in self.subdirs.values():
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000239 print()
Raymond Hettingere0d49722002-06-02 18:55:56 +0000240 sd.report_full_closure()
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000241
Raymond Hettinger05595e92003-02-27 00:05:31 +0000242 methodmap = dict(subdirs=phase4,
243 same_files=phase3, diff_files=phase3, funny_files=phase3,
244 common_dirs = phase2, common_files=phase2, common_funny=phase2,
245 common=phase1, left_only=phase1, right_only=phase1,
246 left_list=phase0, right_list=phase0)
247
248 def __getattr__(self, attr):
249 if attr not in self.methodmap:
Collin Winterce36ad82007-08-30 01:19:48 +0000250 raise AttributeError(attr)
Raymond Hettinger05595e92003-02-27 00:05:31 +0000251 self.methodmap[attr](self)
252 return getattr(self, attr)
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000253
Ethan Smithe3ec44d2020-04-09 21:47:31 -0700254 __class_getitem__ = classmethod(GenericAlias)
255
256
Georg Brandl55689c92009-05-17 12:19:44 +0000257def cmpfiles(a, b, common, shallow=True):
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000258 """Compare common files in two directories.
259
Fred Drake2b0d98b2000-07-03 08:18:47 +0000260 a, b -- directory names
261 common -- list of file names found in both directories
262 shallow -- if true, do comparison based solely on stat() information
Fred Drake2b0d98b2000-07-03 08:18:47 +0000263
264 Returns a tuple of three lists:
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000265 files that compare equal
266 files that are different
Fred Drake2b0d98b2000-07-03 08:18:47 +0000267 filenames that aren't regular files.
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000268
Fred Drake2b0d98b2000-07-03 08:18:47 +0000269 """
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000270 res = ([], [], [])
271 for x in common:
Fred Drake2b0d98b2000-07-03 08:18:47 +0000272 ax = os.path.join(a, x)
273 bx = os.path.join(b, x)
Andrew M. Kuchling8eb40442003-02-06 17:50:01 +0000274 res[_cmp(ax, bx, shallow)].append(x)
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000275 return res
276
277
278# Compare two files.
279# Return:
Tim Peters88869f92001-01-14 23:36:06 +0000280# 0 for equal
281# 1 for different
282# 2 for funny cases (can't stat, etc.)
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000283#
Raymond Hettinger05595e92003-02-27 00:05:31 +0000284def _cmp(a, b, sh, abs=abs, cmp=cmp):
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000285 try:
Andrew M. Kuchling8eb40442003-02-06 17:50:01 +0000286 return not abs(cmp(a, b, sh))
Andrew Svetlov22f36ee2012-12-14 18:02:27 +0200287 except OSError:
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000288 return 2
289
290
291# Return a copy with items that occur in skip removed.
292#
Raymond Hettinger05595e92003-02-27 00:05:31 +0000293def _filter(flist, skip):
Raymond Hettingerb0002d22008-03-13 01:41:43 +0000294 return list(filterfalse(skip.__contains__, flist))
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000295
296
297# Demonstration and testing.
298#
299def demo():
300 import sys
301 import getopt
302 options, args = getopt.getopt(sys.argv[1:], 'r')
Fred Drake8152d322000-12-12 23:20:45 +0000303 if len(args) != 2:
Andrew M. Kuchling83e879d2003-02-06 19:38:45 +0000304 raise getopt.GetoptError('need exactly two args', None)
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000305 dd = dircmp(args[0], args[1])
306 if ('-r', '') in options:
307 dd.report_full_closure()
308 else:
309 dd.report()
310
311if __name__ == '__main__':
312 demo()