]> git.decadent.org.uk Git - dak.git/blob - dak/queue_report.py
18fa867a0f4e5885d62016b5d4eaa179dbc8247d
[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 daklib.queue 
40 import daklib.utils
41
42 Cnf = None
43 Upload = None
44 direction = []
45 row_number = 0
46
47 ################################################################################
48
49 def usage(exit_code=0):
50     print """Usage: dak queue-report
51 Prints a report of packages in queue directories (usually new and byhand).
52
53   -h, --help                show this help and exit.
54   -n, --new                 produce html-output
55   -s, --sort=key            sort output according to key, see below.
56   -a, --age=key             if using sort by age, how should time be treated?
57                             If not given a default of hours will be used.
58
59      Sorting Keys: ao=age,   oldest first.   an=age,   newest first.
60                    na=name,  ascending       nd=name,  descending
61                    nf=notes, first           nl=notes, last
62
63      Age Keys: m=minutes, h=hours, d=days, w=weeks, o=months, y=years
64      
65 """
66     sys.exit(exit_code)
67
68 ################################################################################
69
70 def plural(x):
71     if x > 1:
72         return "s"
73     else:
74         return ""
75
76 ################################################################################
77
78 def time_pp(x):
79     if x < 60:
80         unit="second"
81     elif x < 3600:
82         x /= 60
83         unit="minute"
84     elif x < 86400:
85         x /= 3600
86         unit="hour"
87     elif x < 604800:
88         x /= 86400
89         unit="day"
90     elif x < 2419200:
91         x /= 604800
92         unit="week"
93     elif x < 29030400:
94         x /= 2419200
95         unit="month"
96     else:
97         x /= 29030400
98         unit="year"
99     x = int(x)
100     return "%s %s%s" % (x, unit, plural(x))
101
102 ################################################################################
103
104 def sg_compare (a, b):
105     a = a[1]
106     b = b[1]
107     """Sort by have note, time of oldest upload."""
108     # Sort by have note
109     a_note_state = a["note_state"]
110     b_note_state = b["note_state"]
111     if a_note_state < b_note_state:
112         return -1
113     elif a_note_state > b_note_state:
114         return 1
115
116     # Sort by time of oldest upload
117     return cmp(a["oldest"], b["oldest"])
118
119 ############################################################
120
121 def sortfunc(a,b):
122      for sorting in direction:
123          (sortkey, way, time) = sorting
124          ret = 0
125          if time == "m":
126              x=int(a[sortkey]/60)
127              y=int(b[sortkey]/60)
128          elif time == "h":
129              x=int(a[sortkey]/3600)
130              y=int(b[sortkey]/3600)
131          elif time == "d":
132              x=int(a[sortkey]/86400)
133              y=int(b[sortkey]/86400)
134          elif time == "w":
135              x=int(a[sortkey]/604800)
136              y=int(b[sortkey]/604800)
137          elif time == "o":
138              x=int(a[sortkey]/2419200)
139              y=int(b[sortkey]/2419200)
140          elif time == "y":
141              x=int(a[sortkey]/29030400)
142              y=int(b[sortkey]/29030400)
143          else:
144              x=a[sortkey]
145              y=b[sortkey]
146          if x < y:
147              ret = -1
148          elif x > y:
149              ret = 1
150          if ret != 0:
151              if way < 0:
152                  ret = ret*-1
153              return ret
154      return 0
155
156 ############################################################
157
158 def header():
159     print """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
160         <html><head><meta http-equiv="Content-Type" content="text/html; charset=iso8859-1">
161         <title>Debian NEW and BYHAND Packages</title>
162         <link type="text/css" rel="stylesheet" href="style.css">
163         <link rel="shortcut icon" href="http://www.debian.org/favicon.ico">
164         </head>
165         <body>
166         <div align="center">
167         <a href="http://www.debian.org/">
168      <img src="http://www.debian.org/logos/openlogo-nd-50.png" border="0" hspace="0" vspace="0" alt=""></a>
169         <a href="http://www.debian.org/">
170      <img src="http://www.debian.org/Pics/debian.png" border="0" hspace="0" vspace="0" alt="Debian Project"></a>
171         </div>
172         <br />
173         <table class="reddy" width="100%">
174         <tr>
175         <td class="reddy">
176     <img src="http://www.debian.org/Pics/red-upperleft.png" align="left" border="0" hspace="0" vspace="0"
177      alt="" width="15" height="16"></td>
178         <td rowspan="2" class="reddy">Debian NEW and BYHAND Packages</td>
179         <td class="reddy">
180     <img src="http://www.debian.org/Pics/red-upperright.png" align="right" border="0" hspace="0" vspace="0"
181      alt="" width="16" height="16"></td>
182         </tr>
183         <tr>
184         <td class="reddy">
185     <img src="http://www.debian.org/Pics/red-lowerleft.png" align="left" border="0" hspace="0" vspace="0"
186      alt="" width="16" height="16"></td>
187         <td class="reddy">
188     <img src="http://www.debian.org/Pics/red-lowerright.png" align="right" border="0" hspace="0" vspace="0"
189      alt="" width="15" height="16"></td>
190         </tr>
191         </table>
192         """
193
194 def footer():
195     print "<p class=\"validate\">Timestamp: %s (UTC)</p>" % (time.strftime("%d.%m.%Y / %H:%M:%S", time.gmtime()))
196     print "<hr><p>Hint: Age is the youngest upload of the package, if there is more than one version.</p>"
197     print "<p>You may want to look at <a href=\"http://ftp-master.debian.org/REJECT-FAQ.html\">the REJECT-FAQ</a> for possible reasons why one of the above packages may get rejected.</p>"
198     print """<a href="http://validator.w3.org/check?uri=referer">
199     <img border="0" src="http://www.w3.org/Icons/valid-html401" alt="Valid HTML 4.01!" height="31" width="88"></a>
200         <a href="http://jigsaw.w3.org/css-validator/check/referer">
201     <img border="0" src="http://jigsaw.w3.org/css-validator/images/vcss" alt="Valid CSS!"
202      height="31" width="88"></a>
203     """
204     print "</body></html>"
205
206 def table_header(type):
207     print "<h1>Summary for: %s</h1>" % (type)
208     print """<center><table border="0">
209         <tr>
210           <th align="center">Package</th>
211           <th align="center">Version</th>
212           <th align="center">Arch</th>
213           <th align="center">Distribution</th>
214           <th align="center">Age</th>
215           <th align="center">Maintainer</th>
216           <th align="center">Closes</th>
217         </tr>
218         """
219
220 def table_footer(type, source_count, total_count):
221     print "</table></center><br>\n"
222     print "<p class=\"validate\">Package count in <b>%s</b>: <i>%s</i>\n" % (type, source_count)
223     print "<br>Total Package count: <i>%s</i></p>\n" % (total_count)
224
225 def force_to_latin(s):
226     """Forces a string to Latin-1."""
227     latin1_s = unicode(s,'utf-8')
228     return latin1_s.encode('iso8859-1', 'replace')
229
230
231 def table_row(source, version, arch, last_mod, maint, distribution, closes):
232
233     global row_number
234
235     if row_number % 2 != 0:
236         print "<tr class=\"even\">"
237     else:
238         print "<tr class=\"odd\">"
239
240     tdclass = "sid"
241     for dist in distribution:
242         if dist == "experimental":
243             tdclass = "exp"
244     print "<td valign=\"top\" class=\"%s\">%s</td>" % (tdclass, source)
245     print "<td valign=\"top\" class=\"%s\">" % (tdclass)
246     for vers in version.split():
247         print "%s<br>" % (vers)
248     print "</td><td valign=\"top\" class=\"%s\">%s</td><td valign=\"top\" class=\"%s\">" % (tdclass, arch, tdclass)
249     for dist in distribution:
250         print "%s<br>" % (dist)
251     print "</td><td valign=\"top\" class=\"%s\">%s</td>" % (tdclass, last_mod)
252     (name, mail) = maint.split(":")
253     name = force_to_latin(name)
254
255     print "<td valign=\"top\" class=\"%s\"><a href=\"http://qa.debian.org/developer.php?login=%s\">%s</a></td>" % (tdclass, mail, name)
256     print "<td valign=\"top\" class=\"%s\">" % (tdclass)
257     for close in closes:
258         print "<a href=\"http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=%s\">#%s</a><br>" % (close, close)
259     print "</td></tr>"
260     row_number+=1
261     
262 ############################################################
263
264 def process_changes_files(changes_files, type):
265     msg = ""
266     cache = {}
267     # Read in all the .changes files
268     for filename in changes_files:
269         try:
270             Upload.pkg.changes_file = filename
271             Upload.init_vars()
272             Upload.update_vars()
273             cache[filename] = copy.copy(Upload.pkg.changes)
274             cache[filename]["filename"] = filename
275         except:
276             break
277     # Divide the .changes into per-source groups
278     per_source = {}
279     for filename in cache.keys():
280         source = cache[filename]["source"]
281         if not per_source.has_key(source):
282             per_source[source] = {}
283             per_source[source]["list"] = []
284         per_source[source]["list"].append(cache[filename])
285     # Determine oldest time and have note status for each source group
286     for source in per_source.keys():
287         source_list = per_source[source]["list"]
288         first = source_list[0]
289         oldest = os.stat(first["filename"])[stat.ST_MTIME]
290         have_note = 0
291         for d in per_source[source]["list"]:
292             mtime = os.stat(d["filename"])[stat.ST_MTIME]
293             if Cnf.has_key("Queue-Report::Options::New"):
294                 if mtime > oldest:
295                     oldest = mtime
296             else:
297                 if mtime < oldest:
298                     oldest = mtime
299             have_note += (d.has_key("process-new note"))
300         per_source[source]["oldest"] = oldest
301         if not have_note:
302             per_source[source]["note_state"] = 0; # none
303         elif have_note < len(source_list):
304             per_source[source]["note_state"] = 1; # some
305         else:
306             per_source[source]["note_state"] = 2; # all
307     per_source_items = per_source.items()
308     per_source_items.sort(sg_compare)
309
310     entries = []
311     max_source_len = 0
312     max_version_len = 0
313     max_arch_len = 0
314     maintainer = {}
315     maint=""
316     distribution=""
317     closes=""
318     source_exists=""
319     for i in per_source_items:
320         last_modified = time.time()-i[1]["oldest"]
321         source = i[1]["list"][0]["source"]
322         if len(source) > max_source_len:
323             max_source_len = len(source)
324         arches = {}
325         versions = {}
326         for j in i[1]["list"]:
327             if Cnf.has_key("Queue-Report::Options::New"):
328                 try:
329                     (maintainer["maintainer822"], maintainer["maintainer2047"],
330                     maintainer["maintainername"], maintainer["maintaineremail"]) = \
331                     daklib.utils.fix_maintainer (j["maintainer"])
332                 except daklib.utils.ParseMaintError, msg:
333                     print "Problems while parsing maintainer address\n"
334                     maintainer["maintainername"] = "Unknown"
335                     maintainer["maintaineremail"] = "Unknown"
336                 maint="%s:%s" % (maintainer["maintainername"], maintainer["maintaineremail"])
337                 distribution=j["distribution"].keys()
338                 closes=j["closes"].keys()
339             for arch in j["architecture"].keys():
340                 arches[arch] = ""
341             version = j["version"]
342             versions[version] = ""
343         arches_list = arches.keys()
344         arches_list.sort(daklib.utils.arch_compare_sw)
345         arch_list = " ".join(arches_list)
346         version_list = " ".join(versions.keys())
347         if len(version_list) > max_version_len:
348             max_version_len = len(version_list)
349         if len(arch_list) > max_arch_len:
350             max_arch_len = len(arch_list)
351         if i[1]["note_state"]:
352             note = " | [N]"
353         else:
354             note = ""
355         entries.append([source, version_list, arch_list, note, last_modified, maint, distribution, closes])
356
357     # direction entry consists of "Which field, which direction, time-consider" where
358     # time-consider says how we should treat last_modified. Thats all.
359
360     # Look for the options for sort and then do the sort.
361     age = "h"
362     if Cnf.has_key("Queue-Report::Options::Age"):
363         age =  Cnf["Queue-Report::Options::Age"]
364     if Cnf.has_key("Queue-Report::Options::New"):
365     # If we produce html we always have oldest first.
366         direction.append([4,-1,"ao"])
367     else:
368                 if Cnf.has_key("Queue-Report::Options::Sort"):
369                         for i in Cnf["Queue-Report::Options::Sort"].split(","):
370                           if i == "ao":
371                                   # Age, oldest first.
372                                   direction.append([4,-1,age])
373                           elif i == "an":
374                                   # Age, newest first.
375                                   direction.append([4,1,age])
376                           elif i == "na":
377                                   # Name, Ascending.
378                                   direction.append([0,1,0])
379                           elif i == "nd":
380                                   # Name, Descending.
381                                   direction.append([0,-1,0])
382                           elif i == "nl":
383                                   # Notes last.
384                                   direction.append([3,1,0])
385                           elif i == "nf":
386                                   # Notes first.
387                                   direction.append([3,-1,0])
388     entries.sort(lambda x, y: sortfunc(x, y))
389     # Yes, in theory you can add several sort options at the commandline with. But my mind is to small
390     # at the moment to come up with a real good sorting function that considers all the sidesteps you
391     # have with it. (If you combine options it will simply take the last one at the moment).
392     # Will be enhanced in the future.
393
394     if Cnf.has_key("Queue-Report::Options::New"):
395         direction.append([4,1,"ao"])
396         entries.sort(lambda x, y: sortfunc(x, y))
397     # Output for a html file. First table header. then table_footer.
398     # Any line between them is then a <tr> printed from subroutine table_row.
399         if len(entries) > 0:
400             table_header(type.upper())
401             for entry in entries:
402                 (source, version_list, arch_list, note, last_modified, maint, distribution, closes) = entry
403                 table_row(source, version_list, arch_list, time_pp(last_modified), maint, distribution, closes)
404             total_count = len(changes_files)
405             source_count = len(per_source_items)
406             table_footer(type.upper(), source_count, total_count)
407     else:
408     # The "normal" output without any formatting.
409         format="%%-%ds | %%-%ds | %%-%ds%%s | %%s old\n" % (max_source_len, max_version_len, max_arch_len)
410
411         msg = ""
412         for entry in entries:
413             (source, version_list, arch_list, note, last_modified, undef, undef, undef) = entry
414             msg += format % (source, version_list, arch_list, note, time_pp(last_modified))
415
416         if msg:
417             total_count = len(changes_files)
418             source_count = len(per_source_items)
419             print type.upper()
420             print "-"*len(type)
421             print
422             print msg
423             print "%s %s source package%s / %s %s package%s in total." % (source_count, type, plural(source_count), total_count, type, plural(total_count))
424             print
425
426
427 ################################################################################
428
429 def main():
430     global Cnf, Upload
431
432     Cnf = daklib.utils.get_conf()
433     Arguments = [('h',"help","Queue-Report::Options::Help"),
434                  ('n',"new","Queue-Report::Options::New"),
435                  ('s',"sort","Queue-Report::Options::Sort", "HasArg"),
436                  ('a',"age","Queue-Report::Options::Age", "HasArg")]
437     for i in [ "help" ]:
438         if not Cnf.has_key("Queue-Report::Options::%s" % (i)):
439             Cnf["Queue-Report::Options::%s" % (i)] = ""
440
441     apt_pkg.ParseCommandLine(Cnf, Arguments, sys.argv)
442
443     Options = Cnf.SubTree("Queue-Report::Options")
444     if Options["Help"]:
445         usage()
446
447     Upload = daklib.queue.Upload(Cnf)
448
449     if Cnf.has_key("Queue-Report::Options::New"):
450         header()
451
452     directories = Cnf.ValueList("Queue-Report::Directories")
453     if not directories:
454         directories = [ "byhand", "new" ]
455
456     for directory in directories:
457         changes_files = glob.glob("%s/*.changes" % (Cnf["Dir::Queue::%s" % (directory)]))
458         process_changes_files(changes_files, directory)
459
460     if Cnf.has_key("Queue-Report::Options::New"):
461         footer()
462
463 ################################################################################
464
465 if __name__ == '__main__':
466     main()