decouple a function decompress out of decompress_tar
[~helmut/debian-dedup.git] / importpkg.py
1 #!/usr/bin/python
2 """This tool reads a Debian package from stdin and emits a yaml stream on
3 stdout.  It does not access a database. Therefore it can be run in parallel and
4 on multiple machines. The generated yaml contains multiple documents. The first
5 document contains package metadata. Then a document is emitted for each file.
6 And finally a document consisting of the string "commit" is emitted."""
7
8 import hashlib
9 import optparse
10 import sys
11 import tarfile
12 import zlib
13
14 import yaml
15
16 from dedup.debpkg import DebExtractor, process_control, get_tar_hashes
17 from dedup.hashing import DecompressedHash, SuppressingHash, HashedStream, \
18         HashBlacklistContent
19 from dedup.compression import GzipDecompressor, decompress
20 from dedup.image import GIFHash, PNGHash
21
22 boring_content = set(("", "\n"))
23
24 def sha512_nontrivial():
25     return HashBlacklistContent(hashlib.sha512(), boring_content)
26
27 def gziphash():
28     hashobj = DecompressedHash(GzipDecompressor(), hashlib.sha512())
29     hashobj = SuppressingHash(hashobj, (ValueError, zlib.error))
30     hashobj.name = "gzip_sha512"
31     return HashBlacklistContent(hashobj, boring_content)
32
33 def pnghash():
34     hashobj = PNGHash(hashlib.sha512())
35     hashobj = SuppressingHash(hashobj, (ValueError,))
36     hashobj.name = "png_sha512"
37     return hashobj
38
39 def gifhash():
40     hashobj = GIFHash(hashlib.sha512())
41     hashobj = SuppressingHash(hashobj, (ValueError,))
42     hashobj.name = "gif_sha512"
43     return hashobj
44
45 def decompress_tar(filelike, extension):
46     filelike = decompress(filelike, extension.decode("ascii"))
47     return tarfile.open(fileobj=filelike, mode="r|")
48
49 class ProcessingFinished(Exception):
50     pass
51
52 class ImportpkgExtractor(DebExtractor):
53     hash_functions = [sha512_nontrivial, gziphash, pnghash, gifhash]
54
55     def __init__(self, callback):
56         self.state = "start"
57         self.callback = callback
58
59     def handle_ar_member(self, name, filelike):
60         if name.startswith(b"control.tar"):
61             if self.state != "start":
62                 raise ValueError("unexpected control.tar")
63             self.state = "control"
64             tf = decompress_tar(filelike, name[11:])
65             for elem in tf:
66                 if elem.name not in ("./control", "control"):
67                     continue
68                 if self.state != "control":
69                     raise ValueError("duplicate control file")
70                 self.state = "control_file"
71                 self.callback(process_control(tf.extractfile(elem).read()))
72                 break
73         elif name.startswith(b"data.tar"):
74             if self.state != "control_file":
75                 raise ValueError("missing control file")
76             self.state = "data"
77             tf = decompress_tar(filelike, name[8:])
78             for name, size, hashes in get_tar_hashes(tf, self.hash_functions):
79                 try:
80                     name = name.decode("utf8")
81                 except UnicodeDecodeError:
82                     print("warning: skipping filename with encoding error")
83                     continue # skip files with non-utf8 encoding for now
84                 self.callback(dict(name=name, size=size, hashes=hashes))
85             raise ProcessingFinished()
86
87     def handle_ar_end(self):
88         if self.state != "data":
89             raise ValueError("data.tar not found")
90
91 def main():
92     parser = optparse.OptionParser()
93     parser.add_option("-H", "--hash", action="store",
94                       help="verify that stdin hash given sha256 hash")
95     options, args = parser.parse_args()
96     try:
97         stdin = sys.stdin.buffer
98     except AttributeError: # python2
99         stdin = sys.stdin
100     dumper = yaml.SafeDumper(sys.stdout)
101     dumper.open()
102     if options.hash:
103         stdin = HashedStream(stdin, hashlib.sha256())
104     try:
105         ImportpkgExtractor(dumper.represent).process(stdin)
106     except ProcessingFinished:
107         pass
108     else:
109         raise RuntimeError("unexpected termination of extractor")
110     if options.hash:
111         stdin.validate(options.hash)
112     dumper.represent("commit")
113     dumper.close()
114
115 if __name__ == "__main__":
116     main()