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
40 ################################################################################
42 re_package = re.compile(r"^(.+?)_.*")
43 re_doc_directory = re.compile(r".*/doc/([^/]*).*")
45 re_contrib = re.compile('^contrib/')
46 re_nonfree = re.compile('^non\-free/')
48 re_arch = re.compile("Architecture: .*")
49 re_builddep = re.compile("Build-Depends: .*")
50 re_builddepind = re.compile("Build-Depends-Indep: .*")
52 re_localhost = re.compile("localhost\.localdomain")
53 re_version = re.compile('^(.*)\((.*)\)')
55 re_newlinespace = re.compile('\n')
56 re_spacestrip = re.compile('(\s)')
58 html_escaping = {'"':'"', '&':'&', '<':'<', '>':'>'}
59 re_html_escaping = re.compile('|'.join(map(re.escape, html_escaping.keys())))
61 ################################################################################
66 Cnf = utils.get_conf()
67 projectB = pg.connect(Cnf["DB::Name"], Cnf["DB::Host"], int(Cnf["DB::Port"]))
68 database.init(Cnf, projectB)
70 printed_copyrights = {}
72 # default is to not output html.
75 ################################################################################
77 def usage (exit_code=0):
78 print """Usage: dak examine-package [PACKAGE]...
81 -h, --help show this help and exit
82 -H, --html-output output html page with inspection result
83 -f, --file-name filename for the html page
85 PACKAGE can be a .changes, .dsc, .deb or .udeb filename."""
89 ################################################################################
90 # probably xml.sax.saxutils would work as well
93 return re_html_escaping.sub(lambda x: html_escaping.get(x.group(0)), s)
95 def escape_if_needed(s):
97 return re_html_escaping.sub(lambda x: html_escaping.get(x.group(0)), s)
101 def headline(s, level=2, bodyelement=None):
105 <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>
106 </thead>"""%{"bodyelement":bodyelement,"title":html_escape(s)}
108 print "<h%d>%s</h%d>" % (level, html_escape(s), level)
110 print "---- %s ----" % (s)
112 # Colour definitions, 'end' isn't really for use
116 'contrib': "\033[33m",
117 'nonfree': "\033[31m",
121 'maintainer': "\033[32m"}
124 'main': ('<span style="color: aqua">',"</span>"),
125 'contrib': ('<span style="color: yellow">',"</span>"),
126 'nonfree': ('<span style="color: red">',"</span>"),
127 'arch': ('<span style="color: green">',"</span>"),
128 'bold': ('<span style="font-weight: bold">',"</span>"),
129 'maintainer': ('<span style="color: green">',"</span>")}
131 def colour_output(s, colour):
133 return ("%s%s%s" % (html_colours[colour][0], html_escape(s), html_colours[colour][1]))
135 return ("%s%s%s" % (ansi_colours[colour], s, ansi_colours['end']))
137 def escaped_text(s, strip=False):
141 return "<pre>%s</pre>" % (s)
145 def formatted_text(s, strip=False):
149 return "<pre>%s</pre>" % (html_escape(s))
155 return """<tr><td>"""+s+"""</td></tr>"""
159 def format_field(k,v):
161 return """<tr><td class="key">%s:</td><td class="val">%s</td></tr>"""%(k,v)
163 return "%s: %s"%(k,v)
165 def foldable_output(title, elementnameprefix, content, norow=False):
166 d = {'elementnameprefix':elementnameprefix}
168 print """<div id="%(elementnameprefix)s-wrap"><a name="%(elementnameprefix)s" />
169 <table class="infobox rfc822">"""%d
170 headline(title, bodyelement="%(elementnameprefix)s-body"%d)
172 print """ <tbody id="%(elementnameprefix)s-body" class="infobody">"""%d
176 print output_row(content)
178 print """</tbody></table></div>"""
180 ################################################################################
182 def get_depends_parts(depend) :
183 v_match = re_version.match(depend)
185 d_parts = { 'name' : v_match.group(1), 'version' : v_match.group(2) }
187 d_parts = { 'name' : depend , 'version' : '' }
190 def get_or_list(depend) :
191 or_list = depend.split("|")
194 def get_comma_list(depend) :
195 dep_list = depend.split(",")
198 def split_depends (d_str) :
199 # creates a list of lists of dictionaries of depends (package,version relation)
201 d_str = re_spacestrip.sub('',d_str)
203 # first split depends string up amongs comma delimiter
204 dep_list = get_comma_list(d_str)
206 while d < len(dep_list):
207 # put depends into their own list
208 depends_tree.append([dep_list[d]])
211 while d < len(depends_tree):
213 # split up Or'd depends into a multi-item list
214 depends_tree[d] = get_or_list(depends_tree[d][0])
215 while k < len(depends_tree[d]):
216 # split depends into {package, version relation}
217 depends_tree[d][k] = get_depends_parts(depends_tree[d][k])
222 def read_control (filename):
229 deb_file = utils.open_file(filename)
231 extracts = apt_inst.debExtractControl(deb_file)
232 control = apt_pkg.ParseSection(extracts)
234 print formatted_text("can't parse control info")
240 control_keys = control.keys()
242 if control.has_key("Depends"):
243 depends_str = control.Find("Depends")
244 # create list of dependancy lists
245 depends = split_depends(depends_str)
247 if control.has_key("Recommends"):
248 recommends_str = control.Find("Recommends")
249 recommends = split_depends(recommends_str)
251 if control.has_key("Section"):
252 section_str = control.Find("Section")
254 c_match = re_contrib.search(section_str)
255 nf_match = re_nonfree.search(section_str)
258 section = colour_output(section_str, 'contrib')
261 section = colour_output(section_str, 'nonfree')
264 section = colour_output(section_str, 'main')
265 if control.has_key("Architecture"):
266 arch_str = control.Find("Architecture")
267 arch = colour_output(arch_str, 'arch')
269 if control.has_key("Maintainer"):
270 maintainer = control.Find("Maintainer")
271 localhost = re_localhost.search(maintainer)
274 maintainer = colour_output(maintainer, 'maintainer')
276 maintainer = escape_if_needed(maintainer)
278 return (control, control_keys, section, depends, recommends, arch, maintainer)
280 def read_changes_or_dsc (filename):
283 dsc_file = utils.open_file(filename)
285 dsc = utils.parse_changes(filename)
287 return formatted_text("can't parse .dsc control info")
290 filecontents = strip_pgp_signature(filename)
292 for l in filecontents.split('\n'):
293 m = re.match(r'([-a-zA-Z0-9]*):', l)
295 keysinorder.append(m.group(1))
298 if k in ("build-depends","build-depends-indep"):
299 dsc[k] = create_depends_string(split_depends(dsc[k]))
300 elif k == "architecture":
301 if (dsc["architecture"] != "any"):
302 dsc['architecture'] = colour_output(dsc["architecture"], 'arch')
303 elif k in ("files","changes","description"):
305 dsc[k] = formatted_text(dsc[k], strip=True)
307 dsc[k] = ('\n'+'\n'.join(map(lambda x: ' '+x, dsc[k].split('\n')))).rstrip()
309 dsc[k] = escape_if_needed(dsc[k])
311 keysinorder = filter(lambda x: not x.lower().startswith('checksums-'), keysinorder)
313 filecontents = '\n'.join(map(lambda x: format_field(x,dsc[x.lower()]), keysinorder))+'\n'
316 def create_depends_string (depends_tree):
317 # just look up unstable for now. possibly pull from .changes later
321 for l in depends_tree:
322 if (comma_count >= 2):
328 # doesn't do version lookup yet.
330 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))
336 if d['version'] != '' :
337 adepends += " (%s)" % (d['version'])
339 if i[2] == "contrib":
340 result += colour_output(adepends, "contrib")
341 elif i[2] == "non-free":
342 result += colour_output(adepends, "nonfree")
344 result += colour_output(adepends, "main")
347 if d['version'] != '' :
348 adepends += " (%s)" % (d['version'])
349 result += colour_output(adepends, "bold")
354 def output_deb_info(filename):
355 (control, control_keys, section, depends, recommends, arch, maintainer) = read_control(filename)
358 return formatted_text("no control info")
360 for key in control_keys :
362 field_value = create_depends_string(depends)
363 elif key == 'Recommends':
364 field_value = create_depends_string(recommends)
365 elif key == 'Section':
366 field_value = section
367 elif key == 'Architecture':
369 elif key == 'Maintainer':
370 field_value = maintainer
371 elif key == 'Description':
373 field_value = formatted_text(control.Find(key), strip=True)
375 desc = control.Find(key)
376 desc = re_newlinespace.sub('\n ', desc)
377 field_value = escape_if_needed(desc)
379 field_value = escape_if_needed(control.Find(key))
380 to_print += " "+format_field(key,field_value)+'\n'
383 def do_command (command, filename, escaped=0):
384 o = os.popen("%s %s" % (command, filename))
386 return escaped_text(o.read())
388 return formatted_text(o.read())
390 def do_lintian (filename):
392 return do_command("lintian --show-overrides --color html", filename, 1)
394 return do_command("lintian --show-overrides --color always", filename, 1)
396 def get_copyright (deb_filename):
397 package = re_package.sub(r'\1', deb_filename)
398 o = os.popen("dpkg-deb -c %s | egrep 'usr(/share)?/doc/[^/]*/copyright' | awk '{print $6}' | head -n 1" % (deb_filename))
399 cright = o.read()[:-1]
402 return formatted_text("WARNING: No copyright found, please check package manually.")
404 doc_directory = re_doc_directory.sub(r'\1', cright)
405 if package != doc_directory:
406 return formatted_text("WARNING: wrong doc directory (expected %s, got %s)." % (package, doc_directory))
408 o = os.popen("dpkg-deb --fsys-tarfile %s | tar xvOf - %s 2>/dev/null" % (deb_filename, cright))
410 copyrightmd5 = md5.md5(cright).hexdigest()
413 if printed_copyrights.has_key(copyrightmd5) and printed_copyrights[copyrightmd5] != "%s (%s)" % (package, deb_filename):
414 res += formatted_text( "NOTE: Copyright is the same as %s.\n\n" % \
415 (printed_copyrights[copyrightmd5]))
417 printed_copyrights[copyrightmd5] = "%s (%s)" % (package, deb_filename)
418 return res+formatted_text(cright)
420 def check_dsc (dsc_filename):
421 (dsc) = read_changes_or_dsc(dsc_filename)
422 foldable_output(dsc_filename, "dsc", dsc, norow=True)
423 foldable_output("lintian check for %s" % dsc_filename, "source-lintian", do_lintian(dsc_filename))
425 def check_deb (deb_filename):
426 filename = os.path.basename(deb_filename)
427 packagename = filename.split('_')[0]
429 if filename.endswith(".udeb"):
435 foldable_output("control file for %s" % (filename), "binary-%s-control"%packagename,
436 output_deb_info(deb_filename), norow=True)
439 foldable_output("skipping lintian check for udeb", "binary-%s-lintian"%packagename,
442 foldable_output("lintian check for %s" % (filename), "binary-%s-lintian"%packagename,
443 do_lintian(deb_filename))
445 foldable_output("contents of %s" % (filename), "binary-%s-contents"%packagename,
446 do_command("dpkg -c", deb_filename))
449 foldable_output("skipping copyright for udeb", "binary-%s-copyright"%packagename,
452 foldable_output("copyright of %s" % (filename), "binary-%s-copyright"%packagename,
453 get_copyright(deb_filename))
455 foldable_output("file listing of %s" % (filename), "binary-%s-file-listing"%packagename,
456 do_command("ls -l", deb_filename))
458 # Read a file, strip the signature and return the modified contents as
460 def strip_pgp_signature (filename):
461 file = utils.open_file (filename)
465 for line in file.readlines():
473 if line.startswith("-----BEGIN PGP SIGNED MESSAGE"):
476 if line.startswith("-----BEGIN PGP SIGNATURE"):
479 if line.startswith("-----END PGP SIGNATURE"):
486 def display_changes(changes_filename):
487 changes = read_changes_or_dsc(changes_filename)
488 foldable_output(changes_filename, "changes", changes, norow=True)
490 def check_changes (changes_filename):
491 display_changes(changes_filename)
493 changes = utils.parse_changes (changes_filename)
494 files = utils.build_file_list(changes)
495 for f in files.keys():
496 if f.endswith(".deb") or f.endswith(".udeb"):
498 if f.endswith(".dsc"):
503 global Cnf, projectB, db_files, waste, excluded
505 # Cnf = utils.get_conf()
507 Arguments = [('h',"help","Examine-Package::Options::Help"),
508 ('H',"html-output","Examine-Package::Options::Html-Output"),
510 for i in [ "Help", "Html-Output", "partial-html" ]:
511 if not Cnf.has_key("Examine-Package::Options::%s" % (i)):
512 Cnf["Examine-Package::Options::%s" % (i)] = ""
514 args = apt_pkg.ParseCommandLine(Cnf,Arguments,sys.argv)
515 Options = Cnf.SubTree("Examine-Package::Options")
520 stdout_fd = sys.stdout
524 if not Options["Html-Output"]:
525 # Pipe output for each argument through less
526 less_fd = os.popen("less -R -", 'w', 0)
527 # -R added to display raw control chars for colour
530 if f.endswith(".changes"):
532 elif f.endswith(".deb") or f.endswith(".udeb"):
534 elif f.endswith(".dsc"):
537 utils.fubar("Unrecognised file type: '%s'." % (f))
539 if not Options["Html-Output"]:
540 # Reset stdout here so future less invocations aren't FUBAR
542 sys.stdout = stdout_fd
544 if errno.errorcode[e.errno] == 'EPIPE':
545 utils.warn("[examine-package] Caught EPIPE; skipping.")
549 except KeyboardInterrupt:
550 utils.warn("[examine-package] Caught C-c; skipping.")
553 #######################################################################################
555 if __name__ == '__main__':