4 Script to automate some parts of checking NEW packages
6 @contact: Debian FTP Master <ftpmaster@debian.org>
7 @copyright: 2000, 2001, 2002, 2003, 2006 James Troup <james@nocrew.org>
8 @copyright: 2009 Joerg Jaspert <joerg@debian.org>
9 @license: GNU General Public License version 2 or later
12 # This program is free software; you can redistribute it and/or modify
13 # it under the terms of the GNU General Public License as published by
14 # the Free Software Foundation; either version 2 of the License, or
15 # (at your option) any later version.
17 # This program is distributed in the hope that it will be useful,
18 # but WITHOUT ANY WARRANTY; without even the implied warranty of
19 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 # GNU General Public License for more details.
22 # You should have received a copy of the GNU General Public License
23 # along with this program; if not, write to the Free Software
24 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
26 ################################################################################
28 # <Omnic> elmo wrote docs?!!?!?!?!?!?!
29 # <aj> as if he wasn't scary enough before!!
30 # * aj imagines a little red furry toy sitting hunched over a computer
31 # tapping furiously and giggling to himself
32 # <aj> eventually he stops, and his heads slowly spins around and you
33 # see this really evil grin and then he sees you, and picks up a
34 # knife from beside the keyboard and throws it at you, and as you
35 # breathe your last breath, he starts giggling again
36 # <aj> but i should be telling this to my psychiatrist, not you guys,
39 ################################################################################
51 from daklib import utils
52 from daklib.dbconn import DBConn, get_binary_from_name_suite
53 from daklib.regexes import html_escaping, re_html_escaping, re_version, re_spacestrip, \
54 re_contrib, re_nonfree, re_localhost, re_newlinespace, \
55 re_package, re_doc_directory
57 ################################################################################
60 Cnf = utils.get_conf()
62 printed_copyrights = {}
63 package_relations = {} #: Store relations of packages for later output
65 # default is to not output html.
68 ################################################################################
70 def usage (exit_code=0):
71 print """Usage: dak examine-package [PACKAGE]...
74 -h, --help show this help and exit
75 -H, --html-output output html page with inspection result
76 -f, --file-name filename for the html page
78 PACKAGE can be a .changes, .dsc, .deb or .udeb filename."""
82 ################################################################################
83 # probably xml.sax.saxutils would work as well
85 def escape_if_needed(s):
87 return re_html_escaping.sub(lambda x: html_escaping.get(x.group(0)), s)
91 def headline(s, level=2, bodyelement=None):
95 <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>
96 </thead>"""%{"bodyelement":bodyelement,"title":utils.html_escape(s)}
98 print "<h%d>%s</h%d>" % (level, utils.html_escape(s), level)
100 print "---- %s ----" % (s)
102 # Colour definitions, 'end' isn't really for use
106 'contrib': "\033[33m",
107 'nonfree': "\033[31m",
111 'maintainer': "\033[32m"}
114 'main': ('<span style="color: aqua">',"</span>"),
115 'contrib': ('<span style="color: yellow">',"</span>"),
116 'nonfree': ('<span style="color: red">',"</span>"),
117 'arch': ('<span style="color: green">',"</span>"),
118 'bold': ('<span style="font-weight: bold">',"</span>"),
119 'maintainer': ('<span style="color: green">',"</span>")}
121 def colour_output(s, colour):
123 return ("%s%s%s" % (html_colours[colour][0], utils.html_escape(s), html_colours[colour][1]))
125 return ("%s%s%s" % (ansi_colours[colour], s, ansi_colours['end']))
127 def escaped_text(s, strip=False):
131 return "<pre>%s</pre>" % (s)
135 def formatted_text(s, strip=False):
139 return "<pre>%s</pre>" % (utils.html_escape(s))
145 return """<tr><td>"""+s+"""</td></tr>"""
149 def format_field(k,v):
151 return """<tr><td class="key">%s:</td><td class="val">%s</td></tr>"""%(k,v)
153 return "%s: %s"%(k,v)
155 def foldable_output(title, elementnameprefix, content, norow=False):
156 d = {'elementnameprefix':elementnameprefix}
158 print """<div id="%(elementnameprefix)s-wrap"><a name="%(elementnameprefix)s" />
159 <table class="infobox rfc822">"""%d
160 headline(title, bodyelement="%(elementnameprefix)s-body"%d)
162 print """ <tbody id="%(elementnameprefix)s-body" class="infobody">"""%d
166 print output_row(content)
168 print """</tbody></table></div>"""
170 ################################################################################
172 def get_depends_parts(depend) :
173 v_match = re_version.match(depend)
175 d_parts = { 'name' : v_match.group(1), 'version' : v_match.group(2) }
177 d_parts = { 'name' : depend , 'version' : '' }
180 def get_or_list(depend) :
181 or_list = depend.split("|")
184 def get_comma_list(depend) :
185 dep_list = depend.split(",")
188 def split_depends (d_str) :
189 # creates a list of lists of dictionaries of depends (package,version relation)
191 d_str = re_spacestrip.sub('',d_str)
193 # first split depends string up amongs comma delimiter
194 dep_list = get_comma_list(d_str)
196 while d < len(dep_list):
197 # put depends into their own list
198 depends_tree.append([dep_list[d]])
201 while d < len(depends_tree):
203 # split up Or'd depends into a multi-item list
204 depends_tree[d] = get_or_list(depends_tree[d][0])
205 while k < len(depends_tree[d]):
206 # split depends into {package, version relation}
207 depends_tree[d][k] = get_depends_parts(depends_tree[d][k])
212 def read_control (filename):
219 deb_file = utils.open_file(filename)
221 extracts = apt_inst.debExtractControl(deb_file)
222 control = apt_pkg.ParseSection(extracts)
224 print formatted_text("can't parse control info")
230 control_keys = control.keys()
232 if control.has_key("Depends"):
233 depends_str = control.Find("Depends")
234 # create list of dependancy lists
235 depends = split_depends(depends_str)
237 if control.has_key("Recommends"):
238 recommends_str = control.Find("Recommends")
239 recommends = split_depends(recommends_str)
241 if control.has_key("Section"):
242 section_str = control.Find("Section")
244 c_match = re_contrib.search(section_str)
245 nf_match = re_nonfree.search(section_str)
248 section = colour_output(section_str, 'contrib')
251 section = colour_output(section_str, 'nonfree')
254 section = colour_output(section_str, 'main')
255 if control.has_key("Architecture"):
256 arch_str = control.Find("Architecture")
257 arch = colour_output(arch_str, 'arch')
259 if control.has_key("Maintainer"):
260 maintainer = control.Find("Maintainer")
261 localhost = re_localhost.search(maintainer)
264 maintainer = colour_output(maintainer, 'maintainer')
266 maintainer = escape_if_needed(maintainer)
268 return (control, control_keys, section, depends, recommends, arch, maintainer)
270 def read_changes_or_dsc (suite, filename):
273 dsc_file = utils.open_file(filename)
275 dsc = utils.parse_changes(filename)
277 return formatted_text("can't parse .dsc control info")
280 filecontents = strip_pgp_signature(filename)
282 for l in filecontents.split('\n'):
283 m = re.match(r'([-a-zA-Z0-9]*):', l)
285 keysinorder.append(m.group(1))
288 if k in ("build-depends","build-depends-indep"):
289 dsc[k] = create_depends_string(suite, split_depends(dsc[k]))
290 elif k == "architecture":
291 if (dsc["architecture"] != "any"):
292 dsc['architecture'] = colour_output(dsc["architecture"], 'arch')
293 elif k in ("files","changes","description"):
295 dsc[k] = formatted_text(dsc[k], strip=True)
297 dsc[k] = ('\n'+'\n'.join(map(lambda x: ' '+x, dsc[k].split('\n')))).rstrip()
299 dsc[k] = escape_if_needed(dsc[k])
301 keysinorder = filter(lambda x: not x.lower().startswith('checksums-'), keysinorder)
303 filecontents = '\n'.join(map(lambda x: format_field(x,dsc[x.lower()]), keysinorder))+'\n'
306 def create_depends_string (suite, depends_tree):
308 if suite == 'experimental':
309 suite_where = "in ('experimental','unstable')"
311 suite_where = "= '%s'" % suite
314 session = DBConn().session()
315 for l in depends_tree:
316 if (comma_count >= 2):
322 # doesn't do version lookup yet.
324 res = get_binary_from_name_suite(d['name'], suite_where)
329 if d['version'] != '' :
330 adepends += " (%s)" % (d['version'])
332 if i[2] == "contrib":
333 result += colour_output(adepends, "contrib")
334 elif i[2] == "non-free":
335 result += colour_output(adepends, "nonfree")
337 result += colour_output(adepends, "main")
340 if d['version'] != '' :
341 adepends += " (%s)" % (d['version'])
342 result += colour_output(adepends, "bold")
347 def output_package_relations ():
349 Output the package relations, if there is more than one package checked in this run.
352 if len(package_relations) < 2:
353 # Only list something if we have more than one binary to compare
354 package_relations.clear()
358 for package in package_relations:
359 for relation in package_relations[package]:
360 to_print += "%-15s: (%s) %s\n" % (package, relation, package_relations[package][relation])
362 package_relations.clear()
363 foldable_output("Package relations", "relations", to_print)
365 def output_deb_info(suite, filename, packagename):
366 (control, control_keys, section, depends, recommends, arch, maintainer) = read_control(filename)
369 return formatted_text("no control info")
371 if not package_relations.has_key(packagename):
372 package_relations[packagename] = {}
373 for key in control_keys :
375 field_value = create_depends_string(suite, depends)
376 package_relations[packagename][key] = field_value
377 elif key == 'Recommends':
378 field_value = create_depends_string(suite, recommends)
379 package_relations[packagename][key] = field_value
380 elif key == 'Section':
381 field_value = section
382 elif key == 'Architecture':
384 elif key == 'Maintainer':
385 field_value = maintainer
386 elif key == 'Description':
388 field_value = formatted_text(control.Find(key), strip=True)
390 desc = control.Find(key)
391 desc = re_newlinespace.sub('\n ', desc)
392 field_value = escape_if_needed(desc)
394 field_value = escape_if_needed(control.Find(key))
395 to_print += " "+format_field(key,field_value)+'\n'
398 def do_command (command, filename, escaped=0):
399 o = os.popen("%s %s" % (command, filename))
401 return escaped_text(o.read())
403 return formatted_text(o.read())
405 def do_lintian (filename):
407 return do_command("lintian --show-overrides --color html", filename, 1)
409 return do_command("lintian --show-overrides --color always", filename, 1)
411 def get_copyright (deb_filename):
412 package = re_package.sub(r'\1', deb_filename)
413 o = os.popen("dpkg-deb -c %s | egrep 'usr(/share)?/doc/[^/]*/copyright' | awk '{print $6}' | head -n 1" % (deb_filename))
414 cright = o.read()[:-1]
417 return formatted_text("WARNING: No copyright found, please check package manually.")
419 doc_directory = re_doc_directory.sub(r'\1', cright)
420 if package != doc_directory:
421 return formatted_text("WARNING: wrong doc directory (expected %s, got %s)." % (package, doc_directory))
423 o = os.popen("dpkg-deb --fsys-tarfile %s | tar xvOf - %s 2>/dev/null" % (deb_filename, cright))
425 copyrightmd5 = md5.md5(cright).hexdigest()
428 if printed_copyrights.has_key(copyrightmd5) and printed_copyrights[copyrightmd5] != "%s (%s)" % (package, deb_filename):
429 res += formatted_text( "NOTE: Copyright is the same as %s.\n\n" % \
430 (printed_copyrights[copyrightmd5]))
432 printed_copyrights[copyrightmd5] = "%s (%s)" % (package, deb_filename)
433 return res+formatted_text(cright)
435 def get_readme_source (dsc_filename):
436 tempdir = utils.temp_dirname()
439 cmd = "dpkg-source --no-check --no-copy -x %s %s" % (dsc_filename, tempdir)
440 (result, output) = commands.getstatusoutput(cmd)
442 res = "How is education supposed to make me feel smarter? Besides, every time I learn something new, it pushes some\n old stuff out of my brain. Remember when I took that home winemaking course, and I forgot how to drive?\n"
443 res += "Error, couldn't extract source, WTF?\n"
444 res += "'dpkg-source -x' failed. return code: %s.\n\n" % (result)
448 path = os.path.join(tempdir, 'debian/README.source')
450 if os.path.exists(path):
451 res += do_command("cat", path)
453 res += "No README.source in this package\n\n"
456 shutil.rmtree(tempdir)
458 if errno.errorcode[e.errno] != 'EACCES':
459 res += "%s: couldn't remove tmp dir %s for source tree." % (dsc_filename, tempdir)
463 def check_dsc (suite, dsc_filename):
464 (dsc) = read_changes_or_dsc(suite, dsc_filename)
465 foldable_output(dsc_filename, "dsc", dsc, norow=True)
466 foldable_output("lintian check for %s" % dsc_filename, "source-lintian", do_lintian(dsc_filename))
467 foldable_output("README.source for %s" % dsc_filename, "source-readmesource", get_readme_source(dsc_filename))
469 def check_deb (suite, deb_filename):
470 filename = os.path.basename(deb_filename)
471 packagename = filename.split('_')[0]
473 if filename.endswith(".udeb"):
479 foldable_output("control file for %s" % (filename), "binary-%s-control"%packagename,
480 output_deb_info(suite, deb_filename, packagename), norow=True)
483 foldable_output("skipping lintian check for udeb", "binary-%s-lintian"%packagename,
486 foldable_output("lintian check for %s" % (filename), "binary-%s-lintian"%packagename,
487 do_lintian(deb_filename))
489 foldable_output("contents of %s" % (filename), "binary-%s-contents"%packagename,
490 do_command("dpkg -c", deb_filename))
493 foldable_output("skipping copyright for udeb", "binary-%s-copyright"%packagename,
496 foldable_output("copyright of %s" % (filename), "binary-%s-copyright"%packagename,
497 get_copyright(deb_filename))
499 foldable_output("file listing of %s" % (filename), "binary-%s-file-listing"%packagename,
500 do_command("ls -l", deb_filename))
502 # Read a file, strip the signature and return the modified contents as
504 def strip_pgp_signature (filename):
505 inputfile = utils.open_file (filename)
509 for line in inputfile.readlines():
517 if line.startswith("-----BEGIN PGP SIGNED MESSAGE"):
520 if line.startswith("-----BEGIN PGP SIGNATURE"):
523 if line.startswith("-----END PGP SIGNATURE"):
530 def display_changes(suite, changes_filename):
531 changes = read_changes_or_dsc(suite, changes_filename)
532 foldable_output(changes_filename, "changes", changes, norow=True)
534 def check_changes (changes_filename):
536 changes = utils.parse_changes (changes_filename)
537 except ChangesUnicodeError:
538 utils.warn("Encoding problem with changes file %s" % (changes_filename))
539 display_changes(changes['distribution'], changes_filename)
541 files = utils.build_file_list(changes)
542 for f in files.keys():
543 if f.endswith(".deb") or f.endswith(".udeb"):
544 check_deb(changes['distribution'], f)
545 if f.endswith(".dsc"):
546 check_dsc(changes['distribution'], f)
550 global Cnf, db_files, waste, excluded
552 # Cnf = utils.get_conf()
554 Arguments = [('h',"help","Examine-Package::Options::Help"),
555 ('H',"html-output","Examine-Package::Options::Html-Output"),
557 for i in [ "Help", "Html-Output", "partial-html" ]:
558 if not Cnf.has_key("Examine-Package::Options::%s" % (i)):
559 Cnf["Examine-Package::Options::%s" % (i)] = ""
561 args = apt_pkg.ParseCommandLine(Cnf,Arguments,sys.argv)
562 Options = Cnf.SubTree("Examine-Package::Options")
567 stdout_fd = sys.stdout
571 if not Options["Html-Output"]:
572 # Pipe output for each argument through less
573 less_fd = os.popen("less -R -", 'w', 0)
574 # -R added to display raw control chars for colour
577 if f.endswith(".changes"):
579 elif f.endswith(".deb") or f.endswith(".udeb"):
580 # default to unstable when we don't have a .changes file
581 # perhaps this should be a command line option?
582 check_deb('unstable', file)
583 elif f.endswith(".dsc"):
584 check_dsc('unstable', f)
586 utils.fubar("Unrecognised file type: '%s'." % (f))
588 output_package_relations()
589 if not Options["Html-Output"]:
590 # Reset stdout here so future less invocations aren't FUBAR
592 sys.stdout = stdout_fd
594 if errno.errorcode[e.errno] == 'EPIPE':
595 utils.warn("[examine-package] Caught EPIPE; skipping.")
599 except KeyboardInterrupt:
600 utils.warn("[examine-package] Caught C-c; skipping.")
603 #######################################################################################
605 if __name__ == '__main__':