3 # Efficiently compare files, boolean outcome only (equal / not equal).
5 # Tricks (used in this order):
6 # - Use the statcache module to avoid statting files more than once
7 # - Files with identical type, size & mtime are assumed to be clones
8 # - Files with different type or size cannot be identical
9 # - We keep a cache of outcomes of earlier comparisons
10 # - We don't fork a process to run 'cmp' but read the files ourselves
22 # Compare two files, use the cache if possible.
23 # May raise os.error if a stat or open of either fails.
26 # Return 1 for identical files, 0 for different.
27 # Raise exceptions if either file could not be statted, read, etc.
28 s1
, s2
= sig(statcache
.stat(f1
)), sig(statcache
.stat(f2
))
29 if not S_ISREG(s1
[0]) or not S_ISREG(s2
[0]):
30 # Either is a not a plain file -- always report as different
33 # type, size & mtime match -- report same
35 if s1
[:2] <> s2
[:2]: # Types or sizes differ, don't bother
36 # types or sizes differ -- report different
38 # same type and size -- look in the cache
40 if cache
.has_key(key
):
41 cs1
, cs2
, outcome
= cache
[key
]
43 if s1
== cs1
and s2
== cs2
:
44 # cached signatures match
46 # stale cached signature(s)
48 outcome
= do_cmp(f1
, f2
)
49 cache
[key
] = s1
, s2
, outcome
52 # Return signature (i.e., type, size, mtime) from raw stat data.
55 return S_IFMT(st
[ST_MODE
]), st
[ST_SIZE
], st
[ST_MTIME
]
57 # Compare two files, really.
60 #print ' cmp', f1, f2 # XXX remove when debugged
61 bufsize
= 8*1024 # Could be tuned
65 b1
= fp1
.read(bufsize
)
66 b2
= fp2
.read(bufsize
)