autoimport: support processing individual files
[~helmut/debian-dedup.git] / autoimport.py
1 #!/usr/bin/python
2 """This scrip takes a directory or a http base url to a mirror and imports all
3 packages contained. It has rather strong assumptions on the working directory.
4 """
5
6 import gzip
7 import io
8 import multiprocessing
9 import optparse
10 import os
11 import sqlite3
12 import subprocess
13 import urllib
14
15 import concurrent.futures
16 from debian import deb822
17 from debian.debian_support import version_compare
18
19 def process_http(pkgs, url):
20     pkglist = urllib.urlopen(url + "/dists/sid/main/binary-amd64/Packages.gz").read()
21     pkglist = gzip.GzipFile(fileobj=io.BytesIO(pkglist)).read()
22     pkglist = io.BytesIO(pkglist)
23     pkglist = deb822.Packages.iter_paragraphs(pkglist)
24     for pkg in pkglist:
25         name = pkg["Package"]
26         if name in pkgs and \
27                 version_compare(pkgs[name]["version"], pkg["Version"]) > 0:
28             continue
29         pkgs[name] = dict(version=pkg["Version"],
30                           filename="%s/%s" % (url, pkg["Filename"]))
31
32 def process_file(pkgs, filename):
33     base = os.path.basename(filename)
34     if not base.endswith(".deb"):
35         raise ValueError("filename does not end in .deb")
36     parts = base.split("_")
37     if len(parts) != 3:
38         raise ValueError("filename not in form name_version_arch.deb")
39     name, version, _ = parts
40     version = urllib.unquote(version)
41     if name in pkgs and version_compare(pkgs[name]["version"], version) > 0:
42         return
43     pkgs[name] = dict(version=version, filename=filename)
44
45 def process_dir(pkgs, d):
46     for entry in os.listdir(d):
47         try:
48             process_file(pkgs, os.path.join(d, entry))
49         except ValueError:
50             pass
51
52 def process_pkg(name, filename):
53     print("importing %s" % filename)
54     if filename.startswith("http://"):
55         with open(os.path.join("tmp", name), "w") as outp:
56             dl = subprocess.Popen(["curl", "-s", filename],
57                                   stdout=subprocess.PIPE, close_fds=True)
58             imp = subprocess.Popen(["python", "importpkg.py"], stdin=dl.stdout,
59                                    stdout=outp, close_fds=True)
60             if imp.wait():
61                 raise ValueError("importpkg failed")
62             if dl.wait():
63                 raise ValueError("curl failed")
64     else:
65         with open(filename) as inp:
66             with open(os.path.join("tmp", name), "w") as outp:
67                 subprocess.check_call(["python", "importpkg.py"], stdin=inp,
68                                       stdout=outp, close_fds=True)
69     print("preprocessed %s" % name)
70
71 def main():
72     parser = optparse.OptionParser()
73     parser.add_option("-n", "--new", action="store_true",
74                       help="avoid reimporting same versions")
75     parser.add_option("-p", "--prune", action="store_true",
76                       help="prune packages old packages")
77     options, args = parser.parse_args()
78     subprocess.check_call(["mkdir", "-p", "tmp"])
79     db = sqlite3.connect("test.sqlite3")
80     cur = db.cursor()
81     cur.execute("PRAGMA foreign_keys = ON;")
82     e = concurrent.futures.ThreadPoolExecutor(multiprocessing.cpu_count())
83     pkgs = {}
84     for d in args:
85         print("processing %s" % d)
86         if d.startswith("http://"):
87             process_http(pkgs, d)
88         elif os.path.isdir(d):
89             process_dir(pkgs, d)
90         else:
91             process_file(pkgs, d)
92
93     print("reading database")
94     cur.execute("SELECT package, version FROM package;")
95     knownpkgs = dict((row[0], row[1]) for row in cur.fetchall())
96     distpkgs = set(pkgs.keys())
97     if options.new:
98         for name in distpkgs:
99             if name in knownpkgs and version_compare(pkgs[name]["version"],
100                     knownpkgs[name]) <= 0:
101                 del pkgs[name]
102     knownpkgs = set(knownpkgs)
103
104     with e:
105         fs = {}
106         for name, pkg in pkgs.items():
107             fs[e.submit(process_pkg, name, pkg["filename"])] = name
108
109         for f in concurrent.futures.as_completed(fs.keys()):
110             name = fs[f]
111             if f.exception():
112                 print("%s failed to import: %r" % (name, f.exception()))
113                 continue
114             inf = os.path.join("tmp", name)
115             print("sqlimporting %s" % name)
116             with open(inf) as inp:
117                 try:
118                     subprocess.check_call(["python", "readyaml.py"], stdin=inp)
119                 except subprocess.CalledProcessError:
120                     print("%s failed sql" % name)
121                 else:
122                     os.unlink(inf)
123
124     if options.prune:
125         delpkgs = knownpkgs - distpkgs
126         print("clearing packages %s" % " ".join(delpkgs))
127         cur.executemany("DELETE FROM package WHERE package = ?;",
128                         ((pkg,) for pkg in delpkgs))
129         # Tables content, dependency and sharing will also be pruned
130         # due to ON DELETE CASCADE clauses.
131         db.commit()
132
133 if __name__ == "__main__":
134     main()