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