blob: e5ad8397e4c53956c1503d8abba134015da0a24f [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
Guido van Rossum2d726871999-10-26 14:02:01 +000016
Ned Deily7bff3cb2013-06-14 15:19:11 -070017__all__ = ['clear_cache', 'cmp', 'dircmp', 'cmpfiles', 'DEFAULT_IGNORES']
Skip Montanaroeccd02a2001-01-20 23:34:12 +000018
Guido van Rossum2d726871999-10-26 14:02:01 +000019_cache = {}
Georg Brandl55689c92009-05-17 12:19:44 +000020BUFSIZE = 8*1024
Guido van Rossum2d726871999-10-26 14:02:01 +000021
Eli Benderskyeb2884a2013-01-12 06:13:32 -080022DEFAULT_IGNORES = [
23 'RCS', 'CVS', 'tags', '.git', '.hg', '.bzr', '_darcs', '__pycache__']
24
Ned Deily7bff3cb2013-06-14 15:19:11 -070025def clear_cache():
26 """Clear the filecmp cache."""
27 _cache.clear()
Eli Benderskyeb2884a2013-01-12 06:13:32 -080028
Georg Brandl55689c92009-05-17 12:19:44 +000029def cmp(f1, f2, shallow=True):
Guido van Rossum63b08ac2000-06-29 14:13:28 +000030 """Compare two files.
Guido van Rossum2d726871999-10-26 14:02:01 +000031
Guido van Rossum63b08ac2000-06-29 14:13:28 +000032 Arguments:
Guido van Rossum2d726871999-10-26 14:02:01 +000033
Guido van Rossum63b08ac2000-06-29 14:13:28 +000034 f1 -- First file name
Guido van Rossum2d726871999-10-26 14:02:01 +000035
Guido van Rossum63b08ac2000-06-29 14:13:28 +000036 f2 -- Second file name
Guido van Rossum2d726871999-10-26 14:02:01 +000037
Guido van Rossum63b08ac2000-06-29 14:13:28 +000038 shallow -- Just check stat signature (do not read the files).
Benjamin Petersond4992dc2014-04-26 13:36:21 -040039 defaults to True.
Guido van Rossum2d726871999-10-26 14:02:01 +000040
Guido van Rossum63b08ac2000-06-29 14:13:28 +000041 Return value:
Guido van Rossum2d726871999-10-26 14:02:01 +000042
Tim Petersbc0e9102002-04-04 22:55:58 +000043 True if the files are the same, False otherwise.
Guido van Rossum2d726871999-10-26 14:02:01 +000044
Guido van Rossum63b08ac2000-06-29 14:13:28 +000045 This function uses a cache for past comparisons and the results,
R David Murray4885f492014-02-02 11:11:01 -050046 with cache entries invalidated if their stat information
47 changes. The cache may be cleared by calling clear_cache().
Guido van Rossum2d726871999-10-26 14:02:01 +000048
Guido van Rossum63b08ac2000-06-29 14:13:28 +000049 """
Andrew M. Kuchling83e879d2003-02-06 19:38:45 +000050
Andrew M. Kuchling8eb40442003-02-06 17:50:01 +000051 s1 = _sig(os.stat(f1))
52 s2 = _sig(os.stat(f2))
Guido van Rossum63b08ac2000-06-29 14:13:28 +000053 if s1[0] != stat.S_IFREG or s2[0] != stat.S_IFREG:
Tim Petersbc0e9102002-04-04 22:55:58 +000054 return False
Guido van Rossum63b08ac2000-06-29 14:13:28 +000055 if shallow and s1 == s2:
Tim Petersbc0e9102002-04-04 22:55:58 +000056 return True
Guido van Rossum63b08ac2000-06-29 14:13:28 +000057 if s1[1] != s2[1]:
Tim Petersbc0e9102002-04-04 22:55:58 +000058 return False
Guido van Rossum2d726871999-10-26 14:02:01 +000059
Raymond Hettinger70797192011-06-25 17:20:21 +020060 outcome = _cache.get((f1, f2, s1, s2))
61 if outcome is None:
62 outcome = _do_cmp(f1, f2)
63 if len(_cache) > 100: # limit the maximum size of the cache
Ned Deily7bff3cb2013-06-14 15:19:11 -070064 clear_cache()
Raymond Hettinger70797192011-06-25 17:20:21 +020065 _cache[f1, f2, s1, s2] = outcome
Guido van Rossum63b08ac2000-06-29 14:13:28 +000066 return outcome
Guido van Rossum2d726871999-10-26 14:02:01 +000067
68def _sig(st):
Raymond Hettinger32200ae2002-06-01 19:51:15 +000069 return (stat.S_IFMT(st.st_mode),
70 st.st_size,
71 st.st_mtime)
Guido van Rossum2d726871999-10-26 14:02:01 +000072
73def _do_cmp(f1, f2):
Guido van Rossum63b08ac2000-06-29 14:13:28 +000074 bufsize = BUFSIZE
Raymond Hettinger686057b2009-06-04 00:11:54 +000075 with open(f1, 'rb') as fp1, open(f2, 'rb') as fp2:
Benjamin Petersonf07d0022009-03-21 17:31:58 +000076 while True:
77 b1 = fp1.read(bufsize)
78 b2 = fp2.read(bufsize)
79 if b1 != b2:
80 return False
81 if not b1:
82 return True
Guido van Rossum63b08ac2000-06-29 14:13:28 +000083
84# Directory comparison class.
85#
86class dircmp:
87 """A class that manages the comparison of 2 directories.
88
Georg Brandl55689c92009-05-17 12:19:44 +000089 dircmp(a, b, ignore=None, hide=None)
Guido van Rossum63b08ac2000-06-29 14:13:28 +000090 A and B are directories.
91 IGNORE is a list of names to ignore,
Eli Benderskyeb2884a2013-01-12 06:13:32 -080092 defaults to DEFAULT_IGNORES.
Guido van Rossum63b08ac2000-06-29 14:13:28 +000093 HIDE is a list of names to hide,
94 defaults to [os.curdir, os.pardir].
95
96 High level usage:
97 x = dircmp(dir1, dir2)
98 x.report() -> prints a report on the differences between dir1 and dir2
99 or
100 x.report_partial_closure() -> prints report on differences between dir1
101 and dir2, and reports on common immediate subdirectories.
102 x.report_full_closure() -> like report_partial_closure,
103 but fully recursive.
104
105 Attributes:
106 left_list, right_list: The files in dir1 and dir2,
107 filtered by hide and ignore.
108 common: a list of names in both dir1 and dir2.
109 left_only, right_only: names only in dir1, dir2.
110 common_dirs: subdirectories in both dir1 and dir2.
111 common_files: files in both dir1 and dir2.
112 common_funny: names in both dir1 and dir2 where the type differs between
113 dir1 and dir2, or the name is not stat-able.
114 same_files: list of identical files.
115 diff_files: list of filenames which differ.
116 funny_files: list of files which could not be compared.
117 subdirs: a dictionary of dircmp objects, keyed by names in common_dirs.
118 """
119
120 def __init__(self, a, b, ignore=None, hide=None): # Initialize
121 self.left = a
122 self.right = b
123 if hide is None:
124 self.hide = [os.curdir, os.pardir] # Names never to be shown
125 else:
126 self.hide = hide
127 if ignore is None:
Eli Benderskyeb2884a2013-01-12 06:13:32 -0800128 self.ignore = DEFAULT_IGNORES
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000129 else:
130 self.ignore = ignore
131
132 def phase0(self): # Compare everything except common subdirectories
133 self.left_list = _filter(os.listdir(self.left),
134 self.hide+self.ignore)
135 self.right_list = _filter(os.listdir(self.right),
136 self.hide+self.ignore)
137 self.left_list.sort()
138 self.right_list.sort()
139
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000140 def phase1(self): # Compute common names
Raymond Hettinger736c0ab2008-03-13 02:09:15 +0000141 a = dict(zip(map(os.path.normcase, self.left_list), self.left_list))
142 b = dict(zip(map(os.path.normcase, self.right_list), self.right_list))
Raymond Hettinger17301e92008-03-13 00:19:26 +0000143 self.common = list(map(a.__getitem__, filter(b.__contains__, a)))
Raymond Hettingerb0002d22008-03-13 01:41:43 +0000144 self.left_only = list(map(a.__getitem__, filterfalse(b.__contains__, a)))
145 self.right_only = list(map(b.__getitem__, filterfalse(a.__contains__, b)))
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000146
147 def phase2(self): # Distinguish files, directories, funnies
148 self.common_dirs = []
149 self.common_files = []
150 self.common_funny = []
151
152 for x in self.common:
153 a_path = os.path.join(self.left, x)
154 b_path = os.path.join(self.right, x)
155
156 ok = 1
157 try:
Andrew M. Kuchling8eb40442003-02-06 17:50:01 +0000158 a_stat = os.stat(a_path)
Andrew Svetlov22f36ee2012-12-14 18:02:27 +0200159 except OSError as why:
Georg Brandld11b68a2008-01-06 21:13:42 +0000160 # print('Can\'t stat', a_path, ':', why.args[1])
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000161 ok = 0
162 try:
Andrew M. Kuchling8eb40442003-02-06 17:50:01 +0000163 b_stat = os.stat(b_path)
Andrew Svetlov22f36ee2012-12-14 18:02:27 +0200164 except OSError as why:
Georg Brandld11b68a2008-01-06 21:13:42 +0000165 # print('Can\'t stat', b_path, ':', why.args[1])
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000166 ok = 0
167
168 if ok:
Raymond Hettinger32200ae2002-06-01 19:51:15 +0000169 a_type = stat.S_IFMT(a_stat.st_mode)
170 b_type = stat.S_IFMT(b_stat.st_mode)
Fred Drake8152d322000-12-12 23:20:45 +0000171 if a_type != b_type:
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000172 self.common_funny.append(x)
173 elif stat.S_ISDIR(a_type):
174 self.common_dirs.append(x)
175 elif stat.S_ISREG(a_type):
176 self.common_files.append(x)
177 else:
178 self.common_funny.append(x)
179 else:
180 self.common_funny.append(x)
181
182 def phase3(self): # Find out differences between common files
183 xx = cmpfiles(self.left, self.right, self.common_files)
184 self.same_files, self.diff_files, self.funny_files = xx
185
186 def phase4(self): # Find out differences between common subdirectories
187 # A new dircmp object is created for each common subdirectory,
188 # these are stored in a dictionary indexed by filename.
189 # The hide and ignore properties are inherited from the parent
190 self.subdirs = {}
191 for x in self.common_dirs:
192 a_x = os.path.join(self.left, x)
193 b_x = os.path.join(self.right, x)
194 self.subdirs[x] = dircmp(a_x, b_x, self.ignore, self.hide)
195
196 def phase4_closure(self): # Recursively call phase4() on subdirectories
197 self.phase4()
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000198 for sd in self.subdirs.values():
Raymond Hettingere0d49722002-06-02 18:55:56 +0000199 sd.phase4_closure()
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000200
201 def report(self): # Print a report on the differences between a and b
202 # Output format is purposely lousy
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000203 print('diff', self.left, self.right)
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000204 if self.left_only:
205 self.left_only.sort()
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000206 print('Only in', self.left, ':', self.left_only)
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000207 if self.right_only:
208 self.right_only.sort()
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000209 print('Only in', self.right, ':', self.right_only)
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000210 if self.same_files:
211 self.same_files.sort()
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000212 print('Identical files :', self.same_files)
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000213 if self.diff_files:
214 self.diff_files.sort()
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000215 print('Differing files :', self.diff_files)
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000216 if self.funny_files:
217 self.funny_files.sort()
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000218 print('Trouble with common files :', self.funny_files)
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000219 if self.common_dirs:
220 self.common_dirs.sort()
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000221 print('Common subdirectories :', self.common_dirs)
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000222 if self.common_funny:
223 self.common_funny.sort()
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000224 print('Common funny cases :', self.common_funny)
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000225
226 def report_partial_closure(self): # Print reports on self and on subdirs
227 self.report()
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000228 for sd in self.subdirs.values():
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000229 print()
Raymond Hettingere0d49722002-06-02 18:55:56 +0000230 sd.report()
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000231
232 def report_full_closure(self): # Report on self and subdirs recursively
233 self.report()
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000234 for sd in self.subdirs.values():
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000235 print()
Raymond Hettingere0d49722002-06-02 18:55:56 +0000236 sd.report_full_closure()
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000237
Raymond Hettinger05595e92003-02-27 00:05:31 +0000238 methodmap = dict(subdirs=phase4,
239 same_files=phase3, diff_files=phase3, funny_files=phase3,
240 common_dirs = phase2, common_files=phase2, common_funny=phase2,
241 common=phase1, left_only=phase1, right_only=phase1,
242 left_list=phase0, right_list=phase0)
243
244 def __getattr__(self, attr):
245 if attr not in self.methodmap:
Collin Winterce36ad82007-08-30 01:19:48 +0000246 raise AttributeError(attr)
Raymond Hettinger05595e92003-02-27 00:05:31 +0000247 self.methodmap[attr](self)
248 return getattr(self, attr)
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000249
Georg Brandl55689c92009-05-17 12:19:44 +0000250def cmpfiles(a, b, common, shallow=True):
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000251 """Compare common files in two directories.
252
Fred Drake2b0d98b2000-07-03 08:18:47 +0000253 a, b -- directory names
254 common -- list of file names found in both directories
255 shallow -- if true, do comparison based solely on stat() information
Fred Drake2b0d98b2000-07-03 08:18:47 +0000256
257 Returns a tuple of three lists:
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000258 files that compare equal
259 files that are different
Fred Drake2b0d98b2000-07-03 08:18:47 +0000260 filenames that aren't regular files.
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000261
Fred Drake2b0d98b2000-07-03 08:18:47 +0000262 """
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000263 res = ([], [], [])
264 for x in common:
Fred Drake2b0d98b2000-07-03 08:18:47 +0000265 ax = os.path.join(a, x)
266 bx = os.path.join(b, x)
Andrew M. Kuchling8eb40442003-02-06 17:50:01 +0000267 res[_cmp(ax, bx, shallow)].append(x)
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000268 return res
269
270
271# Compare two files.
272# Return:
Tim Peters88869f92001-01-14 23:36:06 +0000273# 0 for equal
274# 1 for different
275# 2 for funny cases (can't stat, etc.)
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000276#
Raymond Hettinger05595e92003-02-27 00:05:31 +0000277def _cmp(a, b, sh, abs=abs, cmp=cmp):
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000278 try:
Andrew M. Kuchling8eb40442003-02-06 17:50:01 +0000279 return not abs(cmp(a, b, sh))
Andrew Svetlov22f36ee2012-12-14 18:02:27 +0200280 except OSError:
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000281 return 2
282
283
284# Return a copy with items that occur in skip removed.
285#
Raymond Hettinger05595e92003-02-27 00:05:31 +0000286def _filter(flist, skip):
Raymond Hettingerb0002d22008-03-13 01:41:43 +0000287 return list(filterfalse(skip.__contains__, flist))
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000288
289
290# Demonstration and testing.
291#
292def demo():
293 import sys
294 import getopt
295 options, args = getopt.getopt(sys.argv[1:], 'r')
Fred Drake8152d322000-12-12 23:20:45 +0000296 if len(args) != 2:
Andrew M. Kuchling83e879d2003-02-06 19:38:45 +0000297 raise getopt.GetoptError('need exactly two args', None)
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000298 dd = dircmp(args[0], args[1])
299 if ('-r', '') in options:
300 dd.report_full_closure()
301 else:
302 dd.report()
303
304if __name__ == '__main__':
305 demo()