added a base template to the webapp
[~helmut/debian-dedup.git] / webapp.py
1 #!/usr/bin/python
2
3 import sqlite3
4 from wsgiref.simple_server import make_server
5
6 import jinja2
7 from werkzeug.exceptions import HTTPException, NotFound
8 from werkzeug.routing import Map, Rule, RequestRedirect
9 from werkzeug.wrappers import Request, Response
10
11 jinjaenv = jinja2.Environment(loader=jinja2.FileSystemLoader("."))
12
13 def format_size(size):
14     assert isinstance(size, int)
15     size = float(size)
16     fmt = "%d B"
17     if size >= 1024:
18         size /= 1024
19         fmt = "%.1f KB"
20     if size >= 1024:
21         size /= 1024
22         fmt = "%.1f MB"
23     if size >= 1024:
24         size /= 1024
25         fmt = "%.1f GB"
26     return fmt % size
27
28 jinjaenv.filters["format_size"] = format_size
29
30 base_template = jinjaenv.get_template("base.html")
31
32 package_template = jinjaenv.from_string(
33 """{% extends "base.html" %}
34 {% block title %}duplication of {{ package|e }}{% endblock %}
35 {% block header %}<style type="text/css">.dependency { background-color: yellow; } </style>{% endblock %}
36 {% block content %}<h1>{{ package|e }}</h1>
37 <p>Version: {{ version|e }}</p>
38 <p>Architecture: {{ architecture|e }}</p>
39 <p>Number of files: {{ num_files }}</p>
40 <p>Total size: {{ total_size|format_size }}</p>
41 {%- if shared -%}
42     {%- for function, sharing in shared.items() -%}
43         <h3>sharing with respect to {{ function }}</h3>
44         <table border='1'><tr><th>package</th><th>files shared</th><th>data shared</th></tr>
45         {%- for entry in sharing|sort(attribute="savable", reverse=true) -%}
46             <tr><td{% if not entry.package or entry.package in dependencies %} class="dependency"{% endif %}>
47                 {%- if entry.package %}<a href="{{ entry.package|e }}">{{ entry.package|e }}</a>{% else %}self{% endif %}
48                 <a href="../compare/{{ package|e }}/{{ entry.package|default(package, true)|e }}">compare</a></td>
49             <td>{{ entry.duplicate }} ({{ (100 * entry.duplicate / num_files)|int }}%)</td>
50             <td>{{ entry.savable|format_size }} ({{ (100 * entry.savable / total_size)|int }}%)</td></tr>
51         {%- endfor -%}
52         </table>
53     {%- endfor -%}
54 {%- endif -%}
55 {% endblock %}""")
56
57 detail_template = jinjaenv.from_string(
58 """{% extends "base.html" %}
59 {% block title %}sharing between {{ details1.package|e }} and {{ details2.package|e }}{% endblock%}
60 {% block content %}
61 <h1><a href="../../binary/{{ details1.package|e }}">{{ details1.package|e }}</a> &lt;-&gt; <a href="../../binary/{{ details2.package|e }}">{{ details2.package|e }}</a></h1>
62 {%- if shared -%}
63 <table border='1'><tr><th>size</th><th>filename in {{ details1.package|e }}</th><th>filename in {{ details2.package|e }}</th><th>hash functions</th></tr>
64     {%- for entry in shared|sort(attribute="size", reverse=true) -%}
65         <tr><td>{{ entry.size|format_size }}</td><td>{{ entry.filename1 }}</td><td>{{ entry.filename2 }}</td><td>
66         {%- for function, hashvalue in entry.functions.items() %}<a href="../../hash/{{ function|e }}/{{ hashvalue|e }}">{{ function|e }}</a> {% endfor %}</td></tr>
67     {%- endfor -%}
68 </table>
69 {%- endif -%}
70 {% endblock %}""")
71
72 hash_template = jinjaenv.from_string(
73 """{% extends "base.html" %}
74 {% block title %}information on {{ function|e }} hash {{ hashvalue|e }}{% endblock %}
75 {% block content %}
76 <h1>{{ function|e }} {{ hashvalue|e }}</h1>
77 <table border='1'><tr><th>package</th><th>filename</th><th>size</th></tr>
78 {%- for entry in entries -%}
79     <tr><td><a href="../../binary/{{ entry.package|e }}">{{ entry.package|e }}</a></td>
80     <td>{{ entry.filename|e }}</td><td>{{ entry.size|format_size }}</td></tr>
81 {%- endfor -%}
82 </table>
83 {% endblock %}""")
84
85 index_template = jinjaenv.from_string(
86 """{% extends "base.html" %}
87 {% block title %}Debian duplication detector{% endblock %}
88 {% block content %}
89 <h1>Debian duplication detector</h1>
90 <ul>
91 <li>To inspect a particlar binary package, go to <pre>binary/&lt;packagename&gt;</pre> Example: <a href="binary/git">binary/git</a></li>
92 <li>To inspect a combination of binary packages go to <pre>compare/&lt;firstpackage&gt;/&lt;secondpackage&gt;</pre> Example: <a href="compare/git/git">compare/git/git</a></li>
93 <li>To discover package shipping a particular file go to <pre>hash/sha512/&lt;hashvalue&gt;</pre> Example: <a href="hash/sha512/ed94df7781793f06f9426a600c1bde86397afc7b35cb3aa11b60214bd31e35ad893b53a04a2cf4676154982d7c204c4aa165d6ccdaac0170031364a05dbab3bc">hash/sha512/ed94df7781793f06f9426a600c1bde86397afc7b35cb3aa11b60214bd31e35ad893b53a04a2cf4676154982d7c204c4aa165d6ccdaac0170031364a05dbab3bc</a></li>
94 <ul>
95 {% endblock %}""")
96
97 class Application(object):
98     def __init__(self):
99         self.db = sqlite3.connect("test.sqlite3")
100         self.cur = self.db.cursor()
101         self.routingmap = Map([
102             Rule("/", methods=("GET",), endpoint="index"),
103             Rule("/binary/<package>", methods=("GET",), endpoint="package"),
104             Rule("/compare/<package1>/<package2>", methods=("GET",), endpoint="detail"),
105             Rule("/hash/<function>/<hashvalue>", methods=("GET",), endpoint="hash"),
106         ])
107
108     @Request.application
109     def __call__(self, request):
110         mapadapter = self.routingmap.bind_to_environ(request.environ)
111         try:
112             endpoint, args = mapadapter.match()
113             if endpoint == "package":
114                 return self.show_package(args["package"])
115             elif endpoint == "detail":
116                 return self.show_detail(args["package1"], args["package2"])
117             elif endpoint == "hash":
118                 return self.show_hash(args["function"], args["hashvalue"])
119             elif endpoint == "index":
120                 if not request.environ["PATH_INFO"]:
121                     raise RequestRedirect(request.environ["SCRIPT_NAME"] + "/")
122                 return Response(index_template.render().encode("utf8"),
123                                 content_type="text/html")
124             raise NotFound()
125         except HTTPException as e:
126             return e
127
128     def get_details(self, package):
129         self.cur.execute("SELECT version, architecture FROM package WHERE package = ?;",
130                          (package,))
131         row = self.cur.fetchone()
132         if not row:
133             raise NotFound()
134         version, architecture = row
135         details = dict(package=package,
136                        version=version,
137                        architecture=architecture)
138         self.cur.execute("SELECT count(filename), sum(size) FROM content WHERE package = ?;",
139                          (package,))
140         num_files, total_size = self.cur.fetchone()
141         details.update(dict(num_files=num_files, total_size=total_size))
142         return details
143
144     def get_dependencies(self, package):
145         self.cur.execute("SELECT required FROM dependency WHERE package = ?;",
146                          (package,))
147         return set(row[0] for row in self.cur.fetchall())
148
149     def show_package(self, package):
150         params = self.get_details(package)
151         params["dependencies"] = self.get_dependencies(package)
152
153         shared = dict()
154         self.cur.execute("SELECT a.filename, a.function, a.hash, a.size, b.package FROM content AS a JOIN content AS b ON a.function = b.function AND a.hash = b.hash WHERE a.package = ? AND (a.filename != b.filename OR b.package != ?);",
155                          (package, package))
156         for afile, function, hashval, size, bpkg in self.cur.fetchall():
157             pkgdict = shared.setdefault(function, dict())
158             hashdict = pkgdict.setdefault(bpkg, dict())
159             fileset = hashdict.setdefault(hashval, (size, set()))[1]
160             fileset.add(afile)
161         sharedstats = {}
162         if shared:
163             for function, sharing in shared.items():
164                 sharedstats[function] = list()
165                 mapping = sharing.pop(package, dict())
166                 if mapping:
167                     duplicate = sum(len(files) for _, files in mapping.values())
168                     savable = sum(size * (len(files) - 1) for size, files in mapping.values())
169                     sharedstats[function].append(dict(package=None, duplicate=duplicate, savable=savable))
170                 for pkg, mapping in sharing.items():
171                     duplicate = sum(len(files) for _, files in mapping.values())
172                     savable = sum(size * len(files) for size, files in mapping.values())
173                     sharedstats[function].append(dict(package=pkg, duplicate=duplicate, savable=savable))
174
175         params["shared"] = sharedstats
176         return Response(package_template.render(**params).encode("utf8"),
177                         content_type="text/html")
178
179     def show_detail(self, package1, package2):
180         if package1 == package2:
181             details1 = details2 = self.get_details(package1)
182
183             self.cur.execute("SELECT a.filename, b.filename, a.size, a.function, a.hash FROM content AS a JOIN content AS b ON a.function = b.function AND a.hash = b.hash WHERE a.package = ? AND b.package = ? AND a.filename != b.filename;",
184                              (package1, package1))
185         else:
186             details1 = self.get_details(package1)
187             details2 = self.get_details(package2)
188
189             self.cur.execute("SELECT a.filename, b.filename, a.size, a.function, a.hash FROM content AS a JOIN content AS b ON a.function = b.function AND a.hash = b.hash WHERE a.package = ? AND b.package = ?;",
190                              (package1, package2))
191
192         shared = dict()
193         for filename1, filename2, size, function, hashvalue in self.cur.fetchall():
194             shared.setdefault((filename1, filename2, size), dict())[function] = hashvalue
195         shared = [dict(filename1=filename1, filename2=filename2, size=size,
196                        functions=functions)
197                   for (filename1, filename2, size), functions in shared.items()]
198         params = dict(
199             details1=details1,
200             details2=details2,
201             shared=shared)
202         return Response(detail_template.render(**params).encode("utf8"),
203                         content_type="text/html")
204
205     def show_hash(self, function, hashvalue):
206         self.cur.execute("SELECT package, filename, size FROM content WHERE function = ? AND hash = ?;",
207                          (function, hashvalue))
208         entries = [dict(package=package, filename=filename, size=size)
209                    for package, filename, size in self.cur.fetchall()]
210         if not entries:
211             raise NotFound()
212         params = dict(function=function, hashvalue=hashvalue, entries=entries)
213         return Response(hash_template.render(**params).encode("utf8"),
214                         content_type="text/html")
215
216 def main():
217     app = Application()
218     #app = DebuggedApplication(app, evalex=True)
219     make_server("0.0.0.0", 8800, app).serve_forever()
220
221 if __name__ == "__main__":
222     main()