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