blob: 81b175edf3e60b863460c8f1d88e6a32a99f69ff [file] [log] [blame]
Tor Norbye3a2425a2013-11-04 10:16:08 -08001"""Utilities for comparing files and directories.
2
3Classes:
4 dircmp
5
6Functions:
7 cmp(f1, f2, shallow=1) -> int
8 cmpfiles(a, b, common) -> ([], [], [])
9
10"""
11
12import os
13import stat
14import warnings
15from itertools import ifilter, ifilterfalse, imap, izip
16
17__all__ = ["cmp","dircmp","cmpfiles"]
18
19_cache = {}
20BUFSIZE=8*1024
21
22def cmp(f1, f2, shallow=1):
23 """Compare two files.
24
25 Arguments:
26
27 f1 -- First file name
28
29 f2 -- Second file name
30
31 shallow -- Just check stat signature (do not read the files).
32 defaults to 1.
33
34 Return value:
35
36 True if the files are the same, False otherwise.
37
38 This function uses a cache for past comparisons and the results,
39 with a cache invalidation mechanism relying on stale signatures.
40
41 """
42
43 s1 = _sig(os.stat(f1))
44 s2 = _sig(os.stat(f2))
45 if s1[0] != stat.S_IFREG or s2[0] != stat.S_IFREG:
46 return False
47 if shallow and s1 == s2:
48 return True
49 if s1[1] != s2[1]:
50 return False
51
52 result = _cache.get((f1, f2))
53 if result and (s1, s2) == result[:2]:
54 return result[2]
55 outcome = _do_cmp(f1, f2)
56 _cache[f1, f2] = s1, s2, outcome
57 return outcome
58
59def _sig(st):
60 return (stat.S_IFMT(st.st_mode),
61 st.st_size,
62 st.st_mtime)
63
64def _do_cmp(f1, f2):
65 bufsize = BUFSIZE
66 fp1 = open(f1, 'rb')
67 fp2 = open(f2, 'rb')
68 try:
69 while True:
70 b1 = fp1.read(bufsize)
71 b2 = fp2.read(bufsize)
72 if b1 != b2:
73 return False
74 if not b1:
75 return True
76 finally:
77 fp1.close()
78 fp2.close()
79
80# Directory comparison class.
81#
82class dircmp:
83 """A class that manages the comparison of 2 directories.
84
85 dircmp(a,b,ignore=None,hide=None)
86 A and B are directories.
87 IGNORE is a list of names to ignore,
88 defaults to ['RCS', 'CVS', 'tags'].
89 HIDE is a list of names to hide,
90 defaults to [os.curdir, os.pardir].
91
92 High level usage:
93 x = dircmp(dir1, dir2)
94 x.report() -> prints a report on the differences between dir1 and dir2
95 or
96 x.report_partial_closure() -> prints report on differences between dir1
97 and dir2, and reports on common immediate subdirectories.
98 x.report_full_closure() -> like report_partial_closure,
99 but fully recursive.
100
101 Attributes:
102 left_list, right_list: The files in dir1 and dir2,
103 filtered by hide and ignore.
104 common: a list of names in both dir1 and dir2.
105 left_only, right_only: names only in dir1, dir2.
106 common_dirs: subdirectories in both dir1 and dir2.
107 common_files: files in both dir1 and dir2.
108 common_funny: names in both dir1 and dir2 where the type differs between
109 dir1 and dir2, or the name is not stat-able.
110 same_files: list of identical files.
111 diff_files: list of filenames which differ.
112 funny_files: list of files which could not be compared.
113 subdirs: a dictionary of dircmp objects, keyed by names in common_dirs.
114 """
115
116 def __init__(self, a, b, ignore=None, hide=None): # Initialize
117 self.left = a
118 self.right = b
119 if hide is None:
120 self.hide = [os.curdir, os.pardir] # Names never to be shown
121 else:
122 self.hide = hide
123 if ignore is None:
124 self.ignore = ['RCS', 'CVS', 'tags'] # Names ignored in comparison
125 else:
126 self.ignore = ignore
127
128 def phase0(self): # Compare everything except common subdirectories
129 self.left_list = _filter(os.listdir(self.left),
130 self.hide+self.ignore)
131 self.right_list = _filter(os.listdir(self.right),
132 self.hide+self.ignore)
133 self.left_list.sort()
134 self.right_list.sort()
135
136 def phase1(self): # Compute common names
137 a = dict(izip(imap(os.path.normcase, self.left_list), self.left_list))
138 b = dict(izip(imap(os.path.normcase, self.right_list), self.right_list))
139 self.common = map(a.__getitem__, ifilter(b.has_key, a))
140 self.left_only = map(a.__getitem__, ifilterfalse(b.has_key, a))
141 self.right_only = map(b.__getitem__, ifilterfalse(a.has_key, b))
142
143 def phase2(self): # Distinguish files, directories, funnies
144 self.common_dirs = []
145 self.common_files = []
146 self.common_funny = []
147
148 for x in self.common:
149 a_path = os.path.join(self.left, x)
150 b_path = os.path.join(self.right, x)
151
152 ok = 1
153 try:
154 a_stat = os.stat(a_path)
155 except os.error, why:
156 # print 'Can\'t stat', a_path, ':', why[1]
157 ok = 0
158 try:
159 b_stat = os.stat(b_path)
160 except os.error, why:
161 # print 'Can\'t stat', b_path, ':', why[1]
162 ok = 0
163
164 if ok:
165 a_type = stat.S_IFMT(a_stat.st_mode)
166 b_type = stat.S_IFMT(b_stat.st_mode)
167 if a_type != b_type:
168 self.common_funny.append(x)
169 elif stat.S_ISDIR(a_type):
170 self.common_dirs.append(x)
171 elif stat.S_ISREG(a_type):
172 self.common_files.append(x)
173 else:
174 self.common_funny.append(x)
175 else:
176 self.common_funny.append(x)
177
178 def phase3(self): # Find out differences between common files
179 xx = cmpfiles(self.left, self.right, self.common_files)
180 self.same_files, self.diff_files, self.funny_files = xx
181
182 def phase4(self): # Find out differences between common subdirectories
183 # A new dircmp object is created for each common subdirectory,
184 # these are stored in a dictionary indexed by filename.
185 # The hide and ignore properties are inherited from the parent
186 self.subdirs = {}
187 for x in self.common_dirs:
188 a_x = os.path.join(self.left, x)
189 b_x = os.path.join(self.right, x)
190 self.subdirs[x] = dircmp(a_x, b_x, self.ignore, self.hide)
191
192 def phase4_closure(self): # Recursively call phase4() on subdirectories
193 self.phase4()
194 for sd in self.subdirs.itervalues():
195 sd.phase4_closure()
196
197 def report(self): # Print a report on the differences between a and b
198 # Output format is purposely lousy
199 print 'diff', self.left, self.right
200 if self.left_only:
201 self.left_only.sort()
202 print 'Only in', self.left, ':', self.left_only
203 if self.right_only:
204 self.right_only.sort()
205 print 'Only in', self.right, ':', self.right_only
206 if self.same_files:
207 self.same_files.sort()
208 print 'Identical files :', self.same_files
209 if self.diff_files:
210 self.diff_files.sort()
211 print 'Differing files :', self.diff_files
212 if self.funny_files:
213 self.funny_files.sort()
214 print 'Trouble with common files :', self.funny_files
215 if self.common_dirs:
216 self.common_dirs.sort()
217 print 'Common subdirectories :', self.common_dirs
218 if self.common_funny:
219 self.common_funny.sort()
220 print 'Common funny cases :', self.common_funny
221
222 def report_partial_closure(self): # Print reports on self and on subdirs
223 self.report()
224 for sd in self.subdirs.itervalues():
225 print
226 sd.report()
227
228 def report_full_closure(self): # Report on self and subdirs recursively
229 self.report()
230 for sd in self.subdirs.itervalues():
231 print
232 sd.report_full_closure()
233
234 methodmap = dict(subdirs=phase4,
235 same_files=phase3, diff_files=phase3, funny_files=phase3,
236 common_dirs = phase2, common_files=phase2, common_funny=phase2,
237 common=phase1, left_only=phase1, right_only=phase1,
238 left_list=phase0, right_list=phase0)
239
240 def __getattr__(self, attr):
241 if attr not in self.methodmap:
242 raise AttributeError, attr
243 self.methodmap[attr](self)
244 return getattr(self, attr)
245
246def cmpfiles(a, b, common, shallow=1):
247 """Compare common files in two directories.
248
249 a, b -- directory names
250 common -- list of file names found in both directories
251 shallow -- if true, do comparison based solely on stat() information
252
253 Returns a tuple of three lists:
254 files that compare equal
255 files that are different
256 filenames that aren't regular files.
257
258 """
259 res = ([], [], [])
260 for x in common:
261 ax = os.path.join(a, x)
262 bx = os.path.join(b, x)
263 res[_cmp(ax, bx, shallow)].append(x)
264 return res
265
266
267# Compare two files.
268# Return:
269# 0 for equal
270# 1 for different
271# 2 for funny cases (can't stat, etc.)
272#
273def _cmp(a, b, sh, abs=abs, cmp=cmp):
274 try:
275 return not abs(cmp(a, b, sh))
276 except os.error:
277 return 2
278
279
280# Return a copy with items that occur in skip removed.
281#
282def _filter(flist, skip):
283 return list(ifilterfalse(skip.__contains__, flist))
284
285
286# Demonstration and testing.
287#
288def demo():
289 import sys
290 import getopt
291 options, args = getopt.getopt(sys.argv[1:], 'r')
292 if len(args) != 2:
293 raise getopt.GetoptError('need exactly two args', None)
294 dd = dircmp(args[0], args[1])
295 if ('-r', '') in options:
296 dd.report_full_closure()
297 else:
298 dd.report()
299
300if __name__ == '__main__':
301 demo()