blob: 3a793819c642676beaed4d4ba8320300cb668af0 [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:
Andrew M. Kuchling83e879d2003-02-06 19:38:45 +00007 cmp(f1, f2, shallow=1) -> int
Guido van Rossum63b08ac2000-06-29 14:13:28 +00008 cmpfiles(a, b, common) -> ([], [], [])
9
10"""
11
12import os
13import stat
Raymond Hettingereeca37e2003-09-02 05:42:02 +000014from itertools import ifilter, ifilterfalse, imap, izip
Guido van Rossum2d726871999-10-26 14:02:01 +000015
Skip Montanaroeccd02a2001-01-20 23:34:12 +000016__all__ = ["cmp","dircmp","cmpfiles"]
17
Guido van Rossum2d726871999-10-26 14:02:01 +000018_cache = {}
19BUFSIZE=8*1024
20
Raymond Hettingerf3fa9462004-12-05 01:58:09 +000021def cmp(f1, f2, shallow=1):
Guido van Rossum63b08ac2000-06-29 14:13:28 +000022 """Compare two files.
Guido van Rossum2d726871999-10-26 14:02:01 +000023
Guido van Rossum63b08ac2000-06-29 14:13:28 +000024 Arguments:
Guido van Rossum2d726871999-10-26 14:02:01 +000025
Guido van Rossum63b08ac2000-06-29 14:13:28 +000026 f1 -- First file name
Guido van Rossum2d726871999-10-26 14:02:01 +000027
Guido van Rossum63b08ac2000-06-29 14:13:28 +000028 f2 -- Second file name
Guido van Rossum2d726871999-10-26 14:02:01 +000029
Guido van Rossum63b08ac2000-06-29 14:13:28 +000030 shallow -- Just check stat signature (do not read the files).
31 defaults to 1.
Guido van Rossum2d726871999-10-26 14:02:01 +000032
Guido van Rossum63b08ac2000-06-29 14:13:28 +000033 Return value:
Guido van Rossum2d726871999-10-26 14:02:01 +000034
Tim Petersbc0e9102002-04-04 22:55:58 +000035 True if the files are the same, False otherwise.
Guido van Rossum2d726871999-10-26 14:02:01 +000036
Guido van Rossum63b08ac2000-06-29 14:13:28 +000037 This function uses a cache for past comparisons and the results,
38 with a cache invalidation mechanism relying on stale signatures.
Guido van Rossum2d726871999-10-26 14:02:01 +000039
Guido van Rossum63b08ac2000-06-29 14:13:28 +000040 """
Andrew M. Kuchling83e879d2003-02-06 19:38:45 +000041
Andrew M. Kuchling8eb40442003-02-06 17:50:01 +000042 s1 = _sig(os.stat(f1))
43 s2 = _sig(os.stat(f2))
Guido van Rossum63b08ac2000-06-29 14:13:28 +000044 if s1[0] != stat.S_IFREG or s2[0] != stat.S_IFREG:
Tim Petersbc0e9102002-04-04 22:55:58 +000045 return False
Guido van Rossum63b08ac2000-06-29 14:13:28 +000046 if shallow and s1 == s2:
Tim Petersbc0e9102002-04-04 22:55:58 +000047 return True
Guido van Rossum63b08ac2000-06-29 14:13:28 +000048 if s1[1] != s2[1]:
Tim Petersbc0e9102002-04-04 22:55:58 +000049 return False
Guido van Rossum2d726871999-10-26 14:02:01 +000050
Raymond Hettinger2c316a32011-06-25 17:14:53 +020051 outcome = _cache.get((f1, f2, s1, s2))
52 if outcome is None:
53 outcome = _do_cmp(f1, f2)
54 if len(_cache) > 100: # limit the maximum size of the cache
55 _cache.clear()
56 _cache[f1, f2, s1, s2] = outcome
Guido van Rossum63b08ac2000-06-29 14:13:28 +000057 return outcome
Guido van Rossum2d726871999-10-26 14:02:01 +000058
59def _sig(st):
Raymond Hettinger32200ae2002-06-01 19:51:15 +000060 return (stat.S_IFMT(st.st_mode),
61 st.st_size,
62 st.st_mtime)
Guido van Rossum2d726871999-10-26 14:02:01 +000063
64def _do_cmp(f1, f2):
Guido van Rossum63b08ac2000-06-29 14:13:28 +000065 bufsize = BUFSIZE
Benjamin Peterson3bca5232009-06-11 17:51:17 +000066 with open(f1, 'rb') as fp1, open(f2, 'rb') as fp2:
Benjamin Petersonfcfa7ea2009-03-19 03:04:31 +000067 while True:
68 b1 = fp1.read(bufsize)
69 b2 = fp2.read(bufsize)
70 if b1 != b2:
71 return False
72 if not b1:
73 return True
Guido van Rossum63b08ac2000-06-29 14:13:28 +000074
75# Directory comparison class.
76#
77class dircmp:
78 """A class that manages the comparison of 2 directories.
79
80 dircmp(a,b,ignore=None,hide=None)
81 A and B are directories.
82 IGNORE is a list of names to ignore,
83 defaults to ['RCS', 'CVS', 'tags'].
84 HIDE is a list of names to hide,
85 defaults to [os.curdir, os.pardir].
86
87 High level usage:
88 x = dircmp(dir1, dir2)
89 x.report() -> prints a report on the differences between dir1 and dir2
90 or
91 x.report_partial_closure() -> prints report on differences between dir1
92 and dir2, and reports on common immediate subdirectories.
93 x.report_full_closure() -> like report_partial_closure,
94 but fully recursive.
95
96 Attributes:
97 left_list, right_list: The files in dir1 and dir2,
98 filtered by hide and ignore.
99 common: a list of names in both dir1 and dir2.
100 left_only, right_only: names only in dir1, dir2.
101 common_dirs: subdirectories in both dir1 and dir2.
102 common_files: files in both dir1 and dir2.
103 common_funny: names in both dir1 and dir2 where the type differs between
104 dir1 and dir2, or the name is not stat-able.
105 same_files: list of identical files.
106 diff_files: list of filenames which differ.
107 funny_files: list of files which could not be compared.
108 subdirs: a dictionary of dircmp objects, keyed by names in common_dirs.
109 """
110
111 def __init__(self, a, b, ignore=None, hide=None): # Initialize
112 self.left = a
113 self.right = b
114 if hide is None:
115 self.hide = [os.curdir, os.pardir] # Names never to be shown
116 else:
117 self.hide = hide
118 if ignore is None:
119 self.ignore = ['RCS', 'CVS', 'tags'] # Names ignored in comparison
120 else:
121 self.ignore = ignore
122
123 def phase0(self): # Compare everything except common subdirectories
124 self.left_list = _filter(os.listdir(self.left),
125 self.hide+self.ignore)
126 self.right_list = _filter(os.listdir(self.right),
127 self.hide+self.ignore)
128 self.left_list.sort()
129 self.right_list.sort()
130
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000131 def phase1(self): # Compute common names
Raymond Hettingereeca37e2003-09-02 05:42:02 +0000132 a = dict(izip(imap(os.path.normcase, self.left_list), self.left_list))
133 b = dict(izip(imap(os.path.normcase, self.right_list), self.right_list))
Brett Cannonc66b03a2008-08-03 23:46:46 +0000134 self.common = map(a.__getitem__, ifilter(b.__contains__, a))
135 self.left_only = map(a.__getitem__, ifilterfalse(b.__contains__, a))
136 self.right_only = map(b.__getitem__, ifilterfalse(a.__contains__, b))
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000137
138 def phase2(self): # Distinguish files, directories, funnies
139 self.common_dirs = []
140 self.common_files = []
141 self.common_funny = []
142
143 for x in self.common:
144 a_path = os.path.join(self.left, x)
145 b_path = os.path.join(self.right, x)
146
147 ok = 1
148 try:
Andrew M. Kuchling8eb40442003-02-06 17:50:01 +0000149 a_stat = os.stat(a_path)
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000150 except os.error, why:
151 # print 'Can\'t stat', a_path, ':', why[1]
152 ok = 0
153 try:
Andrew M. Kuchling8eb40442003-02-06 17:50:01 +0000154 b_stat = os.stat(b_path)
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000155 except os.error, why:
156 # print 'Can\'t stat', b_path, ':', why[1]
157 ok = 0
158
159 if ok:
Raymond Hettinger32200ae2002-06-01 19:51:15 +0000160 a_type = stat.S_IFMT(a_stat.st_mode)
161 b_type = stat.S_IFMT(b_stat.st_mode)
Fred Drake8152d322000-12-12 23:20:45 +0000162 if a_type != b_type:
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000163 self.common_funny.append(x)
164 elif stat.S_ISDIR(a_type):
165 self.common_dirs.append(x)
166 elif stat.S_ISREG(a_type):
167 self.common_files.append(x)
168 else:
169 self.common_funny.append(x)
170 else:
171 self.common_funny.append(x)
172
173 def phase3(self): # Find out differences between common files
174 xx = cmpfiles(self.left, self.right, self.common_files)
175 self.same_files, self.diff_files, self.funny_files = xx
176
177 def phase4(self): # Find out differences between common subdirectories
178 # A new dircmp object is created for each common subdirectory,
179 # these are stored in a dictionary indexed by filename.
180 # The hide and ignore properties are inherited from the parent
181 self.subdirs = {}
182 for x in self.common_dirs:
183 a_x = os.path.join(self.left, x)
184 b_x = os.path.join(self.right, x)
185 self.subdirs[x] = dircmp(a_x, b_x, self.ignore, self.hide)
186
187 def phase4_closure(self): # Recursively call phase4() on subdirectories
188 self.phase4()
Raymond Hettingere0d49722002-06-02 18:55:56 +0000189 for sd in self.subdirs.itervalues():
190 sd.phase4_closure()
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000191
192 def report(self): # Print a report on the differences between a and b
193 # Output format is purposely lousy
194 print 'diff', self.left, self.right
195 if self.left_only:
196 self.left_only.sort()
197 print 'Only in', self.left, ':', self.left_only
198 if self.right_only:
199 self.right_only.sort()
200 print 'Only in', self.right, ':', self.right_only
201 if self.same_files:
202 self.same_files.sort()
203 print 'Identical files :', self.same_files
204 if self.diff_files:
205 self.diff_files.sort()
206 print 'Differing files :', self.diff_files
207 if self.funny_files:
208 self.funny_files.sort()
209 print 'Trouble with common files :', self.funny_files
210 if self.common_dirs:
211 self.common_dirs.sort()
212 print 'Common subdirectories :', self.common_dirs
213 if self.common_funny:
214 self.common_funny.sort()
215 print 'Common funny cases :', self.common_funny
216
217 def report_partial_closure(self): # Print reports on self and on subdirs
218 self.report()
Raymond Hettingere0d49722002-06-02 18:55:56 +0000219 for sd in self.subdirs.itervalues():
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000220 print
Raymond Hettingere0d49722002-06-02 18:55:56 +0000221 sd.report()
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000222
223 def report_full_closure(self): # Report on self and subdirs recursively
224 self.report()
Raymond Hettingere0d49722002-06-02 18:55:56 +0000225 for sd in self.subdirs.itervalues():
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000226 print
Raymond Hettingere0d49722002-06-02 18:55:56 +0000227 sd.report_full_closure()
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000228
Raymond Hettinger05595e92003-02-27 00:05:31 +0000229 methodmap = dict(subdirs=phase4,
230 same_files=phase3, diff_files=phase3, funny_files=phase3,
231 common_dirs = phase2, common_files=phase2, common_funny=phase2,
232 common=phase1, left_only=phase1, right_only=phase1,
233 left_list=phase0, right_list=phase0)
234
235 def __getattr__(self, attr):
236 if attr not in self.methodmap:
237 raise AttributeError, attr
238 self.methodmap[attr](self)
239 return getattr(self, attr)
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000240
Raymond Hettingerf3fa9462004-12-05 01:58:09 +0000241def cmpfiles(a, b, common, shallow=1):
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000242 """Compare common files in two directories.
243
Fred Drake2b0d98b2000-07-03 08:18:47 +0000244 a, b -- directory names
245 common -- list of file names found in both directories
246 shallow -- if true, do comparison based solely on stat() information
Fred Drake2b0d98b2000-07-03 08:18:47 +0000247
248 Returns a tuple of three lists:
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000249 files that compare equal
250 files that are different
Fred Drake2b0d98b2000-07-03 08:18:47 +0000251 filenames that aren't regular files.
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000252
Fred Drake2b0d98b2000-07-03 08:18:47 +0000253 """
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000254 res = ([], [], [])
255 for x in common:
Fred Drake2b0d98b2000-07-03 08:18:47 +0000256 ax = os.path.join(a, x)
257 bx = os.path.join(b, x)
Andrew M. Kuchling8eb40442003-02-06 17:50:01 +0000258 res[_cmp(ax, bx, shallow)].append(x)
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000259 return res
260
261
262# Compare two files.
263# Return:
Tim Peters88869f92001-01-14 23:36:06 +0000264# 0 for equal
265# 1 for different
266# 2 for funny cases (can't stat, etc.)
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000267#
Raymond Hettinger05595e92003-02-27 00:05:31 +0000268def _cmp(a, b, sh, abs=abs, cmp=cmp):
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000269 try:
Andrew M. Kuchling8eb40442003-02-06 17:50:01 +0000270 return not abs(cmp(a, b, sh))
Terry Jan Reedy673770c2013-05-08 23:42:41 -0400271 except (os.error, IOError):
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000272 return 2
273
274
275# Return a copy with items that occur in skip removed.
276#
Raymond Hettinger05595e92003-02-27 00:05:31 +0000277def _filter(flist, skip):
278 return list(ifilterfalse(skip.__contains__, flist))
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000279
280
281# Demonstration and testing.
282#
283def demo():
284 import sys
285 import getopt
286 options, args = getopt.getopt(sys.argv[1:], 'r')
Fred Drake8152d322000-12-12 23:20:45 +0000287 if len(args) != 2:
Andrew M. Kuchling83e879d2003-02-06 19:38:45 +0000288 raise getopt.GetoptError('need exactly two args', None)
Guido van Rossum63b08ac2000-06-29 14:13:28 +0000289 dd = dircmp(args[0], args[1])
290 if ('-r', '') in options:
291 dd.report_full_closure()
292 else:
293 dd.report()
294
295if __name__ == '__main__':
296 demo()