there is no itertools.imap in py3k
[~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 lzma
15 import yaml
16
17 from dedup.arreader import ArReader
18 from dedup.debpkg import process_control, get_tar_hashes
19 from dedup.hashing import DecompressedHash, SuppressingHash, HashedStream, \
20         HashBlacklistContent
21 from dedup.compression import GzipDecompressor, DecompressedStream
22 from dedup.image import GIFHash, PNGHash
23
24 boring_content = set(("", "\n"))
25
26 def sha512_nontrivial():
27     return HashBlacklistContent(hashlib.sha512(), boring_content)
28
29 def gziphash():
30     hashobj = DecompressedHash(GzipDecompressor(), hashlib.sha512())
31     hashobj = SuppressingHash(hashobj, (ValueError, zlib.error))
32     hashobj.name = "gzip_sha512"
33     return HashBlacklistContent(hashobj, boring_content)
34
35 def pnghash():
36     hashobj = PNGHash(hashlib.sha512())
37     hashobj = SuppressingHash(hashobj, (ValueError,))
38     hashobj.name = "png_sha512"
39     return hashobj
40
41 def gifhash():
42     hashobj = GIFHash(hashlib.sha512())
43     hashobj = SuppressingHash(hashobj, (ValueError,))
44     hashobj.name = "gif_sha512"
45     return hashobj
46
47 def decompress_tar(filelike, extension):
48     if extension in (b".lzma", b".xz"):
49         filelike = DecompressedStream(filelike, lzma.LZMADecompressor())
50         extension = b""
51     if extension not in (b"", b".gz", b".bz2"):
52         raise ValueError("unknown compression format with extension %r" %
53                          extension)
54     return tarfile.open(fileobj=filelike,
55                         mode="r|" + extension[1:].decode("ascii"))
56
57 def process_package(filelike, hash_functions):
58     af = ArReader(filelike)
59     af.read_magic()
60     state = "start"
61     while True:
62         try:
63             name = af.read_entry()
64         except EOFError:
65             raise ValueError("data.tar not found")
66         if name.startswith(b"control.tar"):
67             if state != "start":
68                 raise ValueError("unexpected control.tar")
69             state = "control"
70             tf = decompress_tar(af, name[11:])
71             for elem in tf:
72                 if elem.name not in ("./control", "control"):
73                     continue
74                 if state != "control":
75                     raise ValueError("duplicate control file")
76                 state = "control_file"
77                 yield process_control(tf.extractfile(elem).read())
78                 break
79             continue
80         elif name.startswith(b"data.tar"):
81             if state != "control_file":
82                 raise ValueError("missing control file")
83             state = "data"
84             tf = decompress_tar(af, name[8:])
85             for name, size, hashes in get_tar_hashes(tf, hash_functions):
86                 try:
87                     name = name.decode("utf8")
88                 except UnicodeDecodeError:
89                     print("warning: skipping filename with encoding error")
90                     continue # skip files with non-utf8 encoding for now
91                 yield dict(name=name, size=size, hashes=hashes)
92             yield "commit"
93             break
94
95 def process_package_with_hash(filelike, hash_functions, sha256hash):
96     hstream = HashedStream(filelike, hashlib.sha256())
97     for elem in process_package(hstream, hash_functions):
98         if elem == "commit":
99             while hstream.read(4096):
100                 pass
101             if hstream.hexdigest() != sha256hash:
102                 raise ValueError("hash sum mismatch")
103             yield elem
104             break
105         yield elem
106
107 def main():
108     parser = optparse.OptionParser()
109     parser.add_option("-H", "--hash", action="store",
110                       help="verify that stdin hash given sha256 hash")
111     options, args = parser.parse_args()
112     hash_functions = [sha512_nontrivial, gziphash, pnghash, gifhash]
113     try:
114         stdin = sys.stdin.buffer
115     except AttributeError: # python2
116         stdin = sys.stdin
117     if options.hash:
118         gen = process_package_with_hash(stdin, hash_functions, options.hash)
119     else:
120         gen = process_package(stdin, hash_functions)
121     yaml.safe_dump_all(gen, sys.stdout)
122
123 if __name__ == "__main__":
124     main()