3 # Script to automate some parts of checking NEW packages
4 # Copyright (C) 2000, 2001, 2002, 2003, 2006 James Troup <james@nocrew.org>
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.
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.
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
20 ################################################################################
22 # <Omnic> elmo wrote docs?!!?!?!?!?!?!
23 # <aj> as if he wasn't scary enough before!!
24 # * aj imagines a little red furry toy sitting hunched over a computer
25 # tapping furiously and giggling to himself
26 # <aj> eventually he stops, and his heads slowly spins around and you
27 # see this really evil grin and then he sees you, and picks up a
28 # knife from beside the keyboard and throws it at you, and as you
29 # breathe your last breath, he starts giggling again
30 # <aj> but i should be telling this to my psychiatrist, not you guys,
33 ################################################################################
35 import errno, os, pg, re, sys, md5
36 import apt_pkg, apt_inst
37 from daklib import database
38 from daklib import utils
39 from daklib.regexes import *
41 ################################################################################
46 Cnf = utils.get_conf()
47 projectB = pg.connect(Cnf["DB::Name"], Cnf["DB::Host"], int(Cnf["DB::Port"]))
48 database.init(Cnf, projectB)
50 printed_copyrights = {}
52 # default is to not output html.
55 ################################################################################
57 def usage (exit_code=0):
58 print """Usage: dak examine-package [PACKAGE]...
61 -h, --help show this help and exit
62 -H, --html-output output html page with inspection result
63 -f, --file-name filename for the html page
65 PACKAGE can be a .changes, .dsc, .deb or .udeb filename."""
69 ################################################################################
70 # probably xml.sax.saxutils would work as well
72 def escape_if_needed(s):
74 return utils.re_html_escaping.sub(lambda x: utils.html_escaping.get(x.group(0)), s)
78 def headline(s, level=2, bodyelement=None):
82 <tr><th colspan="2" class="title" onclick="toggle('%(bodyelement)s', 'table-row-group', 'table-row-group')">%(title)s <span class="toggle-msg">(click to toggle)</span></th></tr>
83 </thead>"""%{"bodyelement":bodyelement,"title":utils.html_escape(s)}
85 print "<h%d>%s</h%d>" % (level, utils.html_escape(s), level)
87 print "---- %s ----" % (s)
89 # Colour definitions, 'end' isn't really for use
93 'contrib': "\033[33m",
94 'nonfree': "\033[31m",
98 'maintainer': "\033[32m"}
101 'main': ('<span style="color: aqua">',"</span>"),
102 'contrib': ('<span style="color: yellow">',"</span>"),
103 'nonfree': ('<span style="color: red">',"</span>"),
104 'arch': ('<span style="color: green">',"</span>"),
105 'bold': ('<span style="font-weight: bold">',"</span>"),
106 'maintainer': ('<span style="color: green">',"</span>")}
108 def colour_output(s, colour):
110 return ("%s%s%s" % (html_colours[colour][0], utils.html_escape(s), html_colours[colour][1]))
112 return ("%s%s%s" % (ansi_colours[colour], s, ansi_colours['end']))
114 def escaped_text(s, strip=False):
118 return "<pre>%s</pre>" % (s)
122 def formatted_text(s, strip=False):
126 return "<pre>%s</pre>" % (utils.html_escape(s))
132 return """<tr><td>"""+s+"""</td></tr>"""
136 def format_field(k,v):
138 return """<tr><td class="key">%s:</td><td class="val">%s</td></tr>"""%(k,v)
140 return "%s: %s"%(k,v)
142 def foldable_output(title, elementnameprefix, content, norow=False):
143 d = {'elementnameprefix':elementnameprefix}
145 print """<div id="%(elementnameprefix)s-wrap"><a name="%(elementnameprefix)s" />
146 <table class="infobox rfc822">"""%d
147 headline(title, bodyelement="%(elementnameprefix)s-body"%d)
149 print """ <tbody id="%(elementnameprefix)s-body" class="infobody">"""%d
153 print output_row(content)
155 print """</tbody></table></div>"""
157 ################################################################################
159 def get_depends_parts(depend) :
160 v_match = re_version.match(depend)
162 d_parts = { 'name' : v_match.group(1), 'version' : v_match.group(2) }
164 d_parts = { 'name' : depend , 'version' : '' }
167 def get_or_list(depend) :
168 or_list = depend.split("|")
171 def get_comma_list(depend) :
172 dep_list = depend.split(",")
175 def split_depends (d_str) :
176 # creates a list of lists of dictionaries of depends (package,version relation)
178 d_str = re_spacestrip.sub('',d_str)
180 # first split depends string up amongs comma delimiter
181 dep_list = get_comma_list(d_str)
183 while d < len(dep_list):
184 # put depends into their own list
185 depends_tree.append([dep_list[d]])
188 while d < len(depends_tree):
190 # split up Or'd depends into a multi-item list
191 depends_tree[d] = get_or_list(depends_tree[d][0])
192 while k < len(depends_tree[d]):
193 # split depends into {package, version relation}
194 depends_tree[d][k] = get_depends_parts(depends_tree[d][k])
199 def read_control (filename):
206 deb_file = utils.open_file(filename)
208 extracts = apt_inst.debExtractControl(deb_file)
209 control = apt_pkg.ParseSection(extracts)
211 print formatted_text("can't parse control info")
217 control_keys = control.keys()
219 if control.has_key("Depends"):
220 depends_str = control.Find("Depends")
221 # create list of dependancy lists
222 depends = split_depends(depends_str)
224 if control.has_key("Recommends"):
225 recommends_str = control.Find("Recommends")
226 recommends = split_depends(recommends_str)
228 if control.has_key("Section"):
229 section_str = control.Find("Section")
231 c_match = re_contrib.search(section_str)
232 nf_match = re_nonfree.search(section_str)
235 section = colour_output(section_str, 'contrib')
238 section = colour_output(section_str, 'nonfree')
241 section = colour_output(section_str, 'main')
242 if control.has_key("Architecture"):
243 arch_str = control.Find("Architecture")
244 arch = colour_output(arch_str, 'arch')
246 if control.has_key("Maintainer"):
247 maintainer = control.Find("Maintainer")
248 localhost = re_localhost.search(maintainer)
251 maintainer = colour_output(maintainer, 'maintainer')
253 maintainer = escape_if_needed(maintainer)
255 return (control, control_keys, section, depends, recommends, arch, maintainer)
257 def read_changes_or_dsc (suite, filename):
260 dsc_file = utils.open_file(filename)
262 dsc = utils.parse_changes(filename)
264 return formatted_text("can't parse .dsc control info")
267 filecontents = strip_pgp_signature(filename)
269 for l in filecontents.split('\n'):
270 m = re.match(r'([-a-zA-Z0-9]*):', l)
272 keysinorder.append(m.group(1))
275 if k in ("build-depends","build-depends-indep"):
276 dsc[k] = create_depends_string(suite, split_depends(dsc[k]))
277 elif k == "architecture":
278 if (dsc["architecture"] != "any"):
279 dsc['architecture'] = colour_output(dsc["architecture"], 'arch')
280 elif k in ("files","changes","description"):
282 dsc[k] = formatted_text(dsc[k], strip=True)
284 dsc[k] = ('\n'+'\n'.join(map(lambda x: ' '+x, dsc[k].split('\n')))).rstrip()
286 dsc[k] = escape_if_needed(dsc[k])
288 keysinorder = filter(lambda x: not x.lower().startswith('checksums-'), keysinorder)
290 filecontents = '\n'.join(map(lambda x: format_field(x,dsc[x.lower()]), keysinorder))+'\n'
293 def create_depends_string (suite, depends_tree):
295 if suite == 'experimental':
296 suite_where = " in ('experimental','unstable')"
298 suite_where = " ='%s'" % suite
301 for l in depends_tree:
302 if (comma_count >= 2):
308 # doesn't do version lookup yet.
310 q = projectB.query("SELECT DISTINCT(b.package), b.version, c.name, su.suite_name FROM binaries b, files fi, location l, component c, bin_associations ba, suite su WHERE b.package='%s' AND b.file = fi.id AND fi.location = l.id AND l.component = c.id AND ba.bin=b.id AND ba.suite = su.id AND su.suite_name %s ORDER BY b.version desc" % (d['name'], suite_where))
316 if d['version'] != '' :
317 adepends += " (%s)" % (d['version'])
319 if i[2] == "contrib":
320 result += colour_output(adepends, "contrib")
321 elif i[2] == "non-free":
322 result += colour_output(adepends, "nonfree")
324 result += colour_output(adepends, "main")
327 if d['version'] != '' :
328 adepends += " (%s)" % (d['version'])
329 result += colour_output(adepends, "bold")
334 def output_deb_info(suite, filename):
335 (control, control_keys, section, depends, recommends, arch, maintainer) = read_control(filename)
338 return formatted_text("no control info")
340 for key in control_keys :
342 field_value = create_depends_string(suite, depends)
343 elif key == 'Recommends':
344 field_value = create_depends_string(suite, recommends)
345 elif key == 'Section':
346 field_value = section
347 elif key == 'Architecture':
349 elif key == 'Maintainer':
350 field_value = maintainer
351 elif key == 'Description':
353 field_value = formatted_text(control.Find(key), strip=True)
355 desc = control.Find(key)
356 desc = re_newlinespace.sub('\n ', desc)
357 field_value = escape_if_needed(desc)
359 field_value = escape_if_needed(control.Find(key))
360 to_print += " "+format_field(key,field_value)+'\n'
363 def do_command (command, filename, escaped=0):
364 o = os.popen("%s %s" % (command, filename))
366 return escaped_text(o.read())
368 return formatted_text(o.read())
370 def do_lintian (filename):
372 return do_command("lintian --show-overrides --color html", filename, 1)
374 return do_command("lintian --show-overrides --color always", filename, 1)
376 def get_copyright (deb_filename):
377 package = re_package.sub(r'\1', deb_filename)
378 o = os.popen("dpkg-deb -c %s | egrep 'usr(/share)?/doc/[^/]*/copyright' | awk '{print $6}' | head -n 1" % (deb_filename))
379 cright = o.read()[:-1]
382 return formatted_text("WARNING: No copyright found, please check package manually.")
384 doc_directory = re_doc_directory.sub(r'\1', cright)
385 if package != doc_directory:
386 return formatted_text("WARNING: wrong doc directory (expected %s, got %s)." % (package, doc_directory))
388 o = os.popen("dpkg-deb --fsys-tarfile %s | tar xvOf - %s 2>/dev/null" % (deb_filename, cright))
390 copyrightmd5 = md5.md5(cright).hexdigest()
393 if printed_copyrights.has_key(copyrightmd5) and printed_copyrights[copyrightmd5] != "%s (%s)" % (package, deb_filename):
394 res += formatted_text( "NOTE: Copyright is the same as %s.\n\n" % \
395 (printed_copyrights[copyrightmd5]))
397 printed_copyrights[copyrightmd5] = "%s (%s)" % (package, deb_filename)
398 return res+formatted_text(cright)
400 def check_dsc (suite, dsc_filename):
401 (dsc) = read_changes_or_dsc(suite, dsc_filename)
402 foldable_output(dsc_filename, "dsc", dsc, norow=True)
403 foldable_output("lintian check for %s" % dsc_filename, "source-lintian", do_lintian(dsc_filename))
405 def check_deb (suite, deb_filename):
406 filename = os.path.basename(deb_filename)
407 packagename = filename.split('_')[0]
409 if filename.endswith(".udeb"):
415 foldable_output("control file for %s" % (filename), "binary-%s-control"%packagename,
416 output_deb_info(suite, deb_filename), norow=True)
419 foldable_output("skipping lintian check for udeb", "binary-%s-lintian"%packagename,
422 foldable_output("lintian check for %s" % (filename), "binary-%s-lintian"%packagename,
423 do_lintian(deb_filename))
425 foldable_output("contents of %s" % (filename), "binary-%s-contents"%packagename,
426 do_command("dpkg -c", deb_filename))
429 foldable_output("skipping copyright for udeb", "binary-%s-copyright"%packagename,
432 foldable_output("copyright of %s" % (filename), "binary-%s-copyright"%packagename,
433 get_copyright(deb_filename))
435 foldable_output("file listing of %s" % (filename), "binary-%s-file-listing"%packagename,
436 do_command("ls -l", deb_filename))
438 # Read a file, strip the signature and return the modified contents as
440 def strip_pgp_signature (filename):
441 file = utils.open_file (filename)
445 for line in file.readlines():
453 if line.startswith("-----BEGIN PGP SIGNED MESSAGE"):
456 if line.startswith("-----BEGIN PGP SIGNATURE"):
459 if line.startswith("-----END PGP SIGNATURE"):
466 def display_changes(suite, changes_filename):
467 changes = read_changes_or_dsc(suite, changes_filename)
468 foldable_output(changes_filename, "changes", changes, norow=True)
470 def check_changes (changes_filename):
471 changes = utils.parse_changes (changes_filename)
472 display_changes(changes['distribution'], changes_filename)
474 files = utils.build_file_list(changes)
475 for f in files.keys():
476 if f.endswith(".deb") or f.endswith(".udeb"):
477 check_deb(changes['distribution'], f)
478 if f.endswith(".dsc"):
479 check_dsc(changes['distribution'], f)
483 global Cnf, projectB, db_files, waste, excluded
485 # Cnf = utils.get_conf()
487 Arguments = [('h',"help","Examine-Package::Options::Help"),
488 ('H',"html-output","Examine-Package::Options::Html-Output"),
490 for i in [ "Help", "Html-Output", "partial-html" ]:
491 if not Cnf.has_key("Examine-Package::Options::%s" % (i)):
492 Cnf["Examine-Package::Options::%s" % (i)] = ""
494 args = apt_pkg.ParseCommandLine(Cnf,Arguments,sys.argv)
495 Options = Cnf.SubTree("Examine-Package::Options")
500 stdout_fd = sys.stdout
504 if not Options["Html-Output"]:
505 # Pipe output for each argument through less
506 less_fd = os.popen("less -R -", 'w', 0)
507 # -R added to display raw control chars for colour
510 if f.endswith(".changes"):
512 elif f.endswith(".deb") or f.endswith(".udeb"):
513 # default to unstable when we don't have a .changes file
514 # perhaps this should be a command line option?
515 check_deb('unstable', file)
516 elif f.endswith(".dsc"):
517 check_dsc('unstable', f)
519 utils.fubar("Unrecognised file type: '%s'." % (f))
521 if not Options["Html-Output"]:
522 # Reset stdout here so future less invocations aren't FUBAR
524 sys.stdout = stdout_fd
526 if errno.errorcode[e.errno] == 'EPIPE':
527 utils.warn("[examine-package] Caught EPIPE; skipping.")
531 except KeyboardInterrupt:
532 utils.warn("[examine-package] Caught C-c; skipping.")
535 #######################################################################################
537 if __name__ == '__main__':