]> git.phdru.name Git - ppu.git/blob - scripts/cmp.py
Feat(cmp): Use argparse
[ppu.git] / scripts / cmp.py
1 #! /usr/bin/env python
2 """cmp.py: compare two files. Portable replacement for cmp."""
3
4 import argparse
5 import os
6 import sys
7
8
9 def report():
10     if show_pbar:
11         global pbar
12         del pbar
13     sys.stderr.write("Files differ at %d megabayte block\n" % count)
14     global diff
15     diff = True
16
17
18 if __name__ == '__main__':
19     parser = argparse.ArgumentParser(description='Remove old files')
20     parser.add_argument('-i', '--inhibit-progress-bar', action='store_true',
21                         help='inhibit progress bar')
22     parser.add_argument('fname1', help='the first file name')
23     parser.add_argument('fname2', help='the second file name')
24     args = parser.parse_args()
25
26     show_pbar = not args.inhibit_progress_bar and sys.stderr.isatty()
27
28     if show_pbar:
29         try:
30             from m_lib.pbar.tty_pbar import ttyProgressBar
31         except ImportError:
32             show_pbar = False
33
34     if show_pbar:
35         try:
36             size = os.path.getsize(args.fname1)
37         except Exception:
38             print(args.fname1, ": no such file")
39             sys.exit(1)
40
41     if show_pbar:
42         pbar = ttyProgressBar(0, size)
43
44     file1 = open(args.fname1, 'rb')
45     file2 = open(args.fname2, 'rb')
46
47     M = 1024*1024
48     diff = False
49     count = 0
50
51     while True:
52         block1 = file1.read(M)
53         block2 = file2.read(M)
54
55         if show_pbar:
56             pbar.display(file1.tell())
57
58         if block1 and block2:
59             if len(block1) != len(block2):
60                 report()
61                 break
62         elif block1:
63             report()
64             break
65         elif block2:
66             report()
67             break
68         else:
69             break
70
71         if block1 != block2:
72             report()
73             break
74
75         count += 1
76
77     if show_pbar and not diff:
78         del pbar
79
80     file1.close()
81     file2.close()
82
83     if diff:
84         sys.exit(1)