ยปCore Development>Code coverage>Lib/filecmp.py

Python code coverage for Lib/filecmp.py

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