]> git.decadent.org.uk Git - dak.git/blob - dak/queue_report.py
Merge commit 'dak-master/master' into dm_upload_allowed
[dak.git] / dak / queue_report.py
1 #!/usr/bin/env python
2
3 # Produces a report on NEW and BYHAND packages
4 # Copyright (C) 2001, 2002, 2003, 2005, 2006  James Troup <james@nocrew.org>
5
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
10
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU General Public License for more details.
15
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19
20 ################################################################################
21
22 # <o-o> XP runs GCC, XFREE86, SSH etc etc,.,, I feel almost like linux....
23 # <o-o> I am very confident that I can replicate any Linux application on XP
24 # <willy> o-o: *boggle*
25 # <o-o> building from source.
26 # <o-o> Viiru: I already run GIMP under XP
27 # <willy> o-o: why do you capitalise the names of all pieces of software?
28 # <o-o> willy: because I want the EMPHASIZE them....
29 # <o-o> grr s/the/to/
30 # <willy> o-o: it makes you look like ZIPPY the PINHEAD
31 # <o-o> willy: no idea what you are talking about.
32 # <willy> o-o: do some research
33 # <o-o> willy: for what reason?
34
35 ################################################################################
36
37 import copy, glob, os, stat, sys, time
38 import apt_pkg
39 import cgi
40 from daklib import queue
41 from daklib import utils
42 from daklib.dak_exceptions import *
43
44 Cnf = None
45 Upload = None
46 direction = []
47 row_number = 0
48
49 ################################################################################
50
51 def usage(exit_code=0):
52     print """Usage: dak queue-report
53 Prints a report of packages in queue directories (usually new and byhand).
54
55   -h, --help                show this help and exit.
56   -8, --822                 writes 822 formated output to the location set in dak.conf
57   -n, --new                 produce html-output
58   -s, --sort=key            sort output according to key, see below.
59   -a, --age=key             if using sort by age, how should time be treated?
60                             If not given a default of hours will be used.
61
62      Sorting Keys: ao=age,   oldest first.   an=age,   newest first.
63                    na=name,  ascending       nd=name,  descending
64                    nf=notes, first           nl=notes, last
65
66      Age Keys: m=minutes, h=hours, d=days, w=weeks, o=months, y=years
67
68 """
69     sys.exit(exit_code)
70
71 ################################################################################
72
73 def plural(x):
74     if x > 1:
75         return "s"
76     else:
77         return ""
78
79 ################################################################################
80
81 def time_pp(x):
82     if x < 60:
83         unit="second"
84     elif x < 3600:
85         x /= 60
86         unit="minute"
87     elif x < 86400:
88         x /= 3600
89         unit="hour"
90     elif x < 604800:
91         x /= 86400
92         unit="day"
93     elif x < 2419200:
94         x /= 604800
95         unit="week"
96     elif x < 29030400:
97         x /= 2419200
98         unit="month"
99     else:
100         x /= 29030400
101         unit="year"
102     x = int(x)
103     return "%s %s%s" % (x, unit, plural(x))
104
105 ################################################################################
106
107 def sg_compare (a, b):
108     a = a[1]
109     b = b[1]
110     """Sort by have note, time of oldest upload."""
111     # Sort by have note
112     a_note_state = a["note_state"]
113     b_note_state = b["note_state"]
114     if a_note_state < b_note_state:
115         return -1
116     elif a_note_state > b_note_state:
117         return 1
118
119     # Sort by time of oldest upload
120     return cmp(a["oldest"], b["oldest"])
121
122 ############################################################
123
124 def sortfunc(a,b):
125     for sorting in direction:
126         (sortkey, way, time) = sorting
127         ret = 0
128         if time == "m":
129             x=int(a[sortkey]/60)
130             y=int(b[sortkey]/60)
131         elif time == "h":
132             x=int(a[sortkey]/3600)
133             y=int(b[sortkey]/3600)
134         elif time == "d":
135             x=int(a[sortkey]/86400)
136             y=int(b[sortkey]/86400)
137         elif time == "w":
138             x=int(a[sortkey]/604800)
139             y=int(b[sortkey]/604800)
140         elif time == "o":
141             x=int(a[sortkey]/2419200)
142             y=int(b[sortkey]/2419200)
143         elif time == "y":
144             x=int(a[sortkey]/29030400)
145             y=int(b[sortkey]/29030400)
146         else:
147             x=a[sortkey]
148             y=b[sortkey]
149         if x < y:
150             ret = -1
151         elif x > y:
152             ret = 1
153         if ret != 0:
154             if way < 0:
155                 ret = ret*-1
156             return ret
157     return 0
158
159 ############################################################
160
161 def header():
162     print """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
163 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
164 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="de" lang="de">
165   <head>
166     <meta http-equiv="content-type" content="text/xhtml+xml; charset=utf-8" />
167     <link type="text/css" rel="stylesheet" href="style.css" />
168     <link rel="shortcut icon" href="http://www.debian.org/favicon.ico" />
169     <title>
170       Debian NEW and BYHAND Packages
171     </title>
172   </head>
173   <body id="NEW">
174     <div id="logo">
175       <a href="http://www.debian.org/">
176         <img src="http://www.debian.org/logos/openlogo-nd-50.png"
177         alt="debian logo" /></a>
178       <a href="http://www.debian.org/">
179         <img src="http://www.debian.org/Pics/debian.png"
180         alt="Debian Project" /></a>
181     </div>
182     <div id="titleblock">
183
184       <img src="http://www.debian.org/Pics/red-upperleft.png"
185       id="red-upperleft" alt="corner image"/>
186       <img src="http://www.debian.org/Pics/red-lowerleft.png"
187       id="red-lowerleft" alt="corner image"/>
188       <img src="http://www.debian.org/Pics/red-upperright.png"
189       id="red-upperright" alt="corner image"/>
190       <img src="http://www.debian.org/Pics/red-lowerright.png"
191       id="red-lowerright" alt="corner image"/>
192       <span class="title">
193         Debian NEW and BYHAND Packages
194       </span>
195     </div>
196     """
197
198 def footer():
199     print "<p class=\"timestamp\">Timestamp: %s (UTC)</p>" % (time.strftime("%d.%m.%Y / %H:%M:%S", time.gmtime()))
200
201     print """
202     <div class="footer">
203     <p>Hint: Age is the youngest upload of the package, if there is more than
204     one version.<br />
205     You may want to look at <a href="http://ftp-master.debian.org/REJECT-FAQ.html">the REJECT-FAQ</a>
206       for possible reasons why one of the above packages may get rejected.</p>
207       <p>
208       <a href="http://validator.w3.org/check?uri=referer"><img src="http://www.w3.org/Icons/valid-xhtml10"
209         alt="Valid XHTML 1.0 Strict" height="31" width="88" /></a>
210       <a href="http://jigsaw.w3.org/css-validator/">
211         <img style="border:0;width:88px;height:31px" src="http://jigsaw.w3.org/css-validator/images/vcss"
212         alt="Valid CSS!" />
213       </a>
214       </p>
215     </div> </body> </html>
216     """
217
218 def table_header(type, source_count, total_count):
219     print "<h1>Summary for: %s</h1>" % (type)
220     print """
221     <table class="NEW">
222       <caption>
223     """
224     print "Package count in <strong>%s</strong>: <em>%s</em>&nbsp;|&nbsp; Total Package count: <em>%s</em>" % (type, source_count, total_count)
225     print """
226       </caption>
227       <thead>
228         <tr>
229           <th>Package</th>
230           <th>Version</th>
231           <th>Arch</th>
232           <th>Distribution</th>
233           <th>Age</th>
234           <th>Upload info</th>
235           <th>Closes</th>
236         </tr>
237       </thead>
238       <tbody>
239     """
240
241 def table_footer(type):
242     print "</tbody></table>"
243
244
245 def table_row(source, version, arch, last_mod, maint, distribution, closes, fingerprint, sponsor, changedby):
246
247     global row_number
248
249     trclass = "sid"
250     for dist in distribution:
251         if dist == "experimental":
252             trclass = "exp"
253
254     if row_number % 2 != 0:
255         print "<tr class=\"%s even\">" % (trclass)
256     else:
257         print "<tr class=\"%s odd\">" % (trclass)
258
259     print "<td class=\"package\">%s</td>" % (source)
260     print "<td class=\"version\">"
261     for vers in version.split():
262         print "<a href=\"/new/%s_%s.html\">%s</a><br/>" % (source, utils.html_escape(vers), utils.html_escape(vers))
263     print "</td>"
264     print "<td class=\"arch\">%s</td>" % (arch)
265     print "<td class=\"distribution\">"
266     for dist in distribution:
267         print "%s<br/>" % (dist)
268     print "</td>"
269     print "<td class=\"age\">%s</td>" % (last_mod)
270     (name, mail) = maint.split(":")
271
272     print "<td class=\"upload-data\">"
273     print "<span class=\"maintainer\">Maintainer: <a href=\"http://qa.debian.org/developer.php?login=%s\">%s</a></span><br/>" % (utils.html_escape(mail), utils.html_escape(name))
274     (name, mail) = changedby.split(":")
275     print "<span class=\"changed-by\">Changed-By: <a href=\"http://qa.debian.org/developer.php?login=%s\">%s</a></span><br/>" % (utils.html_escape(mail), utils.html_escape(name))
276
277     try:
278         (login, domain) = sponsor.split("@")
279         print "<span class=\"sponsor\">Sponsor: <a href=\"http://qa.debian.org/developer.php?login=%s\">%s</a></span>@debian.org<br/>" % (utils.html_escape(login), utils.html_escape(login))
280     except:
281         pass
282
283     print "<span class=\"signature\">Fingerprint: %s</span>" % (fingerprint)
284     print "</td>"
285
286     print "<td class=\"closes\">"
287     for close in closes:
288         print "<a href=\"http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=%s\">#%s</a><br/>" % (utils.html_escape(close), utils.html_escape(close))
289     print "</td></tr>"
290     row_number+=1
291
292 ############################################################
293
294 def process_changes_files(changes_files, type, log):
295     msg = ""
296     cache = {}
297     # Read in all the .changes files
298     for filename in changes_files:
299         try:
300             Upload.pkg.changes_file = filename
301             Upload.init_vars()
302             Upload.update_vars()
303             cache[filename] = copy.copy(Upload.pkg.changes)
304             cache[filename]["filename"] = filename
305         except:
306             break
307     # Divide the .changes into per-source groups
308     per_source = {}
309     for filename in cache.keys():
310         source = cache[filename]["source"]
311         if not per_source.has_key(source):
312             per_source[source] = {}
313             per_source[source]["list"] = []
314         per_source[source]["list"].append(cache[filename])
315     # Determine oldest time and have note status for each source group
316     for source in per_source.keys():
317         source_list = per_source[source]["list"]
318         first = source_list[0]
319         oldest = os.stat(first["filename"])[stat.ST_MTIME]
320         have_note = 0
321         for d in per_source[source]["list"]:
322             mtime = os.stat(d["filename"])[stat.ST_MTIME]
323             if Cnf.has_key("Queue-Report::Options::New"):
324                 if mtime > oldest:
325                     oldest = mtime
326             else:
327                 if mtime < oldest:
328                     oldest = mtime
329             have_note += (d.has_key("process-new note"))
330         per_source[source]["oldest"] = oldest
331         if not have_note:
332             per_source[source]["note_state"] = 0; # none
333         elif have_note < len(source_list):
334             per_source[source]["note_state"] = 1; # some
335         else:
336             per_source[source]["note_state"] = 2; # all
337     per_source_items = per_source.items()
338     per_source_items.sort(sg_compare)
339
340     entries = []
341     max_source_len = 0
342     max_version_len = 0
343     max_arch_len = 0
344     for i in per_source_items:
345         maintainer = {}
346         maint=""
347         distribution=""
348         closes=""
349         fingerprint=""
350         changeby = {}
351         changedby=""
352         sponsor=""
353         last_modified = time.time()-i[1]["oldest"]
354         source = i[1]["list"][0]["source"]
355         if len(source) > max_source_len:
356             max_source_len = len(source)
357         arches = {}
358         versions = {}
359         for j in i[1]["list"]:
360             if Cnf.has_key("Queue-Report::Options::New") or Cnf.has_key("Queue-Report::Options::822"):
361                 try:
362                     (maintainer["maintainer822"], maintainer["maintainer2047"],
363                     maintainer["maintainername"], maintainer["maintaineremail"]) = \
364                     utils.fix_maintainer (j["maintainer"])
365                 except ParseMaintError, msg:
366                     print "Problems while parsing maintainer address\n"
367                     maintainer["maintainername"] = "Unknown"
368                     maintainer["maintaineremail"] = "Unknown"
369                 maint="%s:%s" % (maintainer["maintainername"], maintainer["maintaineremail"])
370                 # ...likewise for the Changed-By: field if it exists.
371                 try:
372                     (changeby["changedby822"], changeby["changedby2047"],
373                      changeby["changedbyname"], changeby["changedbyemail"]) = \
374                      utils.fix_maintainer (j["changed-by"])
375                 except ParseMaintError, msg:
376                     (changeby["changedby822"], changeby["changedby2047"],
377                      changeby["changedbyname"], changeby["changedbyemail"]) = \
378                      ("", "", "", "")
379                 changedby="%s:%s" % (changeby["changedbyname"], changeby["changedbyemail"])
380
381                 distribution=j["distribution"].keys()
382                 closes=j["closes"].keys()
383                 fingerprint=j["fingerprint"]
384                 if j.has_key("sponsoremail"):
385                     sponsor=j["sponsoremail"]
386             for arch in j["architecture"].keys():
387                 arches[arch] = ""
388             version = j["version"]
389             versions[version] = ""
390         arches_list = arches.keys()
391         arches_list.sort(utils.arch_compare_sw)
392         arch_list = " ".join(arches_list)
393         version_list = " ".join(versions.keys())
394         if len(version_list) > max_version_len:
395             max_version_len = len(version_list)
396         if len(arch_list) > max_arch_len:
397             max_arch_len = len(arch_list)
398         if i[1]["note_state"]:
399             note = " | [N]"
400         else:
401             note = ""
402         entries.append([source, version_list, arch_list, note, last_modified, maint, distribution, closes, fingerprint, sponsor, changedby])
403
404     # direction entry consists of "Which field, which direction, time-consider" where
405     # time-consider says how we should treat last_modified. Thats all.
406
407     # Look for the options for sort and then do the sort.
408     age = "h"
409     if Cnf.has_key("Queue-Report::Options::Age"):
410         age =  Cnf["Queue-Report::Options::Age"]
411     if Cnf.has_key("Queue-Report::Options::New"):
412     # If we produce html we always have oldest first.
413         direction.append([4,-1,"ao"])
414     else:
415         if Cnf.has_key("Queue-Report::Options::Sort"):
416             for i in Cnf["Queue-Report::Options::Sort"].split(","):
417                 if i == "ao":
418                     # Age, oldest first.
419                     direction.append([4,-1,age])
420                 elif i == "an":
421                     # Age, newest first.
422                     direction.append([4,1,age])
423                 elif i == "na":
424                     # Name, Ascending.
425                     direction.append([0,1,0])
426                 elif i == "nd":
427                     # Name, Descending.
428                     direction.append([0,-1,0])
429                 elif i == "nl":
430                     # Notes last.
431                     direction.append([3,1,0])
432                 elif i == "nf":
433                     # Notes first.
434                     direction.append([3,-1,0])
435     entries.sort(lambda x, y: sortfunc(x, y))
436     # Yes, in theory you can add several sort options at the commandline with. But my mind is to small
437     # at the moment to come up with a real good sorting function that considers all the sidesteps you
438     # have with it. (If you combine options it will simply take the last one at the moment).
439     # Will be enhanced in the future.
440
441     if Cnf.has_key("Queue-Report::Options::822"):
442         # print stuff out in 822 format
443         for entry in entries:
444             (source, version_list, arch_list, note, last_modified, maint, distribution, closes, fingerprint, sponsor, changedby) = entry
445
446             # We'll always have Source, Version, Arch, Mantainer, and Dist
447             # For the rest, check to see if we have them, then print them out
448             log.write("Source: " + source + "\n")
449             log.write("Version: " + version_list + "\n")
450             log.write("Architectures: ")
451             log.write( (", ".join(arch_list.split(" "))) + "\n")
452             log.write("Age: " + time_pp(last_modified) + "\n")
453             log.write("Last-Modified: " + str(int(time.time()) - int(last_modified)) + "\n")
454             log.write("Queue: " + type + "\n")
455
456             (name, mail) = maint.split(":")
457             log.write("Maintainer: " + name + " <"+mail+">" + "\n")
458             if changedby:
459                (name, mail) = changedby.split(":")
460                log.write("Changed-By: " + name + " <"+mail+">" + "\n")
461             if sponsor:
462                log.write("Sponsored-By: " + sponsor + "\n")
463             log.write("Distribution:")
464             for dist in distribution:
465                log.write(" " + dist)
466             log.write("\n")
467             log.write("Fingerprint: " + fingerprint + "\n")
468             if closes:
469                 bug_string = ""
470                 for bugs in closes:
471                     bug_string += "#"+bugs+", "
472                 log.write("Closes: " + bug_string[:-2] + "\n")
473             log.write("\n")
474
475     if Cnf.has_key("Queue-Report::Options::New"):
476         direction.append([4,1,"ao"])
477         entries.sort(lambda x, y: sortfunc(x, y))
478     # Output for a html file. First table header. then table_footer.
479     # Any line between them is then a <tr> printed from subroutine table_row.
480         if len(entries) > 0:
481             total_count = len(changes_files)
482             source_count = len(per_source_items)
483             table_header(type.upper(), source_count, total_count)
484             for entry in entries:
485                 (source, version_list, arch_list, note, last_modified, maint, distribution, closes, fingerprint, sponsor, changedby) = entry
486                 table_row(source, version_list, arch_list, time_pp(last_modified), maint, distribution, closes, fingerprint, sponsor, changedby)
487             table_footer(type.upper())
488     elif not Cnf.has_key("Queue-Report::Options::822"):
489     # The "normal" output without any formatting.
490         format="%%-%ds | %%-%ds | %%-%ds%%s | %%s old\n" % (max_source_len, max_version_len, max_arch_len)
491
492         msg = ""
493         for entry in entries:
494             (source, version_list, arch_list, note, last_modified, undef, undef, undef, undef, undef, undef) = entry
495             msg += format % (source, version_list, arch_list, note, time_pp(last_modified))
496
497         if msg:
498             total_count = len(changes_files)
499             source_count = len(per_source_items)
500             print type.upper()
501             print "-"*len(type)
502             print
503             print msg
504             print "%s %s source package%s / %s %s package%s in total." % (source_count, type, plural(source_count), total_count, type, plural(total_count))
505             print
506
507
508 ################################################################################
509
510 def main():
511     global Cnf, Upload
512
513     Cnf = utils.get_conf()
514     Arguments = [('h',"help","Queue-Report::Options::Help"),
515                  ('n',"new","Queue-Report::Options::New"),
516                  ('8','822',"Queue-Report::Options::822"),
517                  ('s',"sort","Queue-Report::Options::Sort", "HasArg"),
518                  ('a',"age","Queue-Report::Options::Age", "HasArg")]
519     for i in [ "help" ]:
520         if not Cnf.has_key("Queue-Report::Options::%s" % (i)):
521             Cnf["Queue-Report::Options::%s" % (i)] = ""
522
523     apt_pkg.ParseCommandLine(Cnf, Arguments, sys.argv)
524
525     Options = Cnf.SubTree("Queue-Report::Options")
526     if Options["Help"]:
527         usage()
528
529     Upload = queue.Upload(Cnf)
530
531     if Cnf.has_key("Queue-Report::Options::New"):
532         header()
533
534     directories = Cnf.ValueList("Queue-Report::Directories")
535     if not directories:
536         directories = [ "byhand", "new" ]
537
538     f = None
539     if Cnf.has_key("Queue-Report::Options::822"):
540         # Open the report file
541         f = open(Cnf["Queue-Report::ReportLocations::822Location"], "w")
542
543     for directory in directories:
544         changes_files = glob.glob("%s/*.changes" % (Cnf["Dir::Queue::%s" % (directory)]))
545         process_changes_files(changes_files, directory, f)
546
547     if Cnf.has_key("Queue-Report::Options::822"):
548         f.close()
549
550     if Cnf.has_key("Queue-Report::Options::New"):
551         footer()
552
553 ################################################################################
554
555 if __name__ == '__main__':
556     main()