4 Script to automate some parts of checking NEW packages
6 Most functions are written in a functional programming style. They
7 return a string avoiding the side effect of directly printing the string
8 to stdout. Those functions can be used in multithreaded parts of dak.
10 @contact: Debian FTP Master <ftpmaster@debian.org>
11 @copyright: 2000, 2001, 2002, 2003, 2006 James Troup <james@nocrew.org>
12 @copyright: 2009 Joerg Jaspert <joerg@debian.org>
13 @license: GNU General Public License version 2 or later
16 # This program is free software; you can redistribute it and/or modify
17 # it under the terms of the GNU General Public License as published by
18 # the Free Software Foundation; either version 2 of the License, or
19 # (at your option) any later version.
21 # This program is distributed in the hope that it will be useful,
22 # but WITHOUT ANY WARRANTY; without even the implied warranty of
23 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 # GNU General Public License for more details.
26 # You should have received a copy of the GNU General Public License
27 # along with this program; if not, write to the Free Software
28 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
30 ################################################################################
32 # <Omnic> elmo wrote docs?!!?!?!?!?!?!
33 # <aj> as if he wasn't scary enough before!!
34 # * aj imagines a little red furry toy sitting hunched over a computer
35 # tapping furiously and giggling to himself
36 # <aj> eventually he stops, and his heads slowly spins around and you
37 # see this really evil grin and then he sees you, and picks up a
38 # knife from beside the keyboard and throws it at you, and as you
39 # breathe your last breath, he starts giggling again
40 # <aj> but i should be telling this to my psychiatrist, not you guys,
43 ################################################################################
56 from daklib import utils
57 from daklib.dbconn import DBConn, get_binary_from_name_suite
58 from daklib.regexes import html_escaping, re_html_escaping, re_version, re_spacestrip, \
59 re_contrib, re_nonfree, re_localhost, re_newlinespace, \
60 re_package, re_doc_directory
62 ################################################################################
65 Cnf = utils.get_conf()
67 changes_lock = threading.Lock()
68 printed_copyrights = {}
69 package_relations = {} #: Store relations of packages for later output
71 # default is to not output html.
74 ################################################################################
76 def usage (exit_code=0):
77 print """Usage: dak examine-package [PACKAGE]...
80 -h, --help show this help and exit
81 -H, --html-output output html page with inspection result
82 -f, --file-name filename for the html page
84 PACKAGE can be a .changes, .dsc, .deb or .udeb filename."""
88 ################################################################################
89 # probably xml.sax.saxutils would work as well
91 def escape_if_needed(s):
93 return re_html_escaping.sub(lambda x: html_escaping.get(x.group(0)), s)
97 def headline(s, level=2, bodyelement=None):
101 <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>
102 </thead>\n"""%{"bodyelement":bodyelement,"title":utils.html_escape(s)}
104 return "<h%d>%s</h%d>\n" % (level, utils.html_escape(s), level)
106 return "---- %s ----\n" % (s)
108 # Colour definitions, 'end' isn't really for use
112 'contrib': "\033[33m",
113 'nonfree': "\033[31m",
117 'maintainer': "\033[32m"}
120 'main': ('<span style="color: aqua">',"</span>"),
121 'contrib': ('<span style="color: yellow">',"</span>"),
122 'nonfree': ('<span style="color: red">',"</span>"),
123 'arch': ('<span style="color: green">',"</span>"),
124 'bold': ('<span style="font-weight: bold">',"</span>"),
125 'maintainer': ('<span style="color: green">',"</span>")}
127 def colour_output(s, colour):
129 return ("%s%s%s" % (html_colours[colour][0], utils.html_escape(s), html_colours[colour][1]))
131 return ("%s%s%s" % (ansi_colours[colour], s, ansi_colours['end']))
133 def escaped_text(s, strip=False):
137 return "<pre>%s</pre>" % (s)
141 def formatted_text(s, strip=False):
145 return "<pre>%s</pre>" % (utils.html_escape(s))
151 return """<tr><td>"""+s+"""</td></tr>"""
155 def format_field(k,v):
157 return """<tr><td class="key">%s:</td><td class="val">%s</td></tr>"""%(k,v)
159 return "%s: %s"%(k,v)
161 def foldable_output(title, elementnameprefix, content, norow=False):
162 d = {'elementnameprefix':elementnameprefix}
165 result += """<div id="%(elementnameprefix)s-wrap"><a name="%(elementnameprefix)s" />
166 <table class="infobox rfc822">\n"""%d
167 result += headline(title, bodyelement="%(elementnameprefix)s-body"%d)
169 result += """ <tbody id="%(elementnameprefix)s-body" class="infobody">\n"""%d
171 result += content + "\n"
173 result += output_row(content) + "\n"
175 result += """</tbody></table></div>"""
178 ################################################################################
180 def get_depends_parts(depend) :
181 v_match = re_version.match(depend)
183 d_parts = { 'name' : v_match.group(1), 'version' : v_match.group(2) }
185 d_parts = { 'name' : depend , 'version' : '' }
188 def get_or_list(depend) :
189 or_list = depend.split("|")
192 def get_comma_list(depend) :
193 dep_list = depend.split(",")
196 def split_depends (d_str) :
197 # creates a list of lists of dictionaries of depends (package,version relation)
199 d_str = re_spacestrip.sub('',d_str)
201 # first split depends string up amongs comma delimiter
202 dep_list = get_comma_list(d_str)
204 while d < len(dep_list):
205 # put depends into their own list
206 depends_tree.append([dep_list[d]])
209 while d < len(depends_tree):
211 # split up Or'd depends into a multi-item list
212 depends_tree[d] = get_or_list(depends_tree[d][0])
213 while k < len(depends_tree[d]):
214 # split depends into {package, version relation}
215 depends_tree[d][k] = get_depends_parts(depends_tree[d][k])
220 def read_control (filename):
227 deb_file = utils.open_file(filename)
229 extracts = apt_inst.debExtractControl(deb_file)
230 control = apt_pkg.ParseSection(extracts)
232 print formatted_text("can't parse control info")
238 control_keys = control.keys()
240 if control.has_key("Depends"):
241 depends_str = control.Find("Depends")
242 # create list of dependancy lists
243 depends = split_depends(depends_str)
245 if control.has_key("Recommends"):
246 recommends_str = control.Find("Recommends")
247 recommends = split_depends(recommends_str)
249 if control.has_key("Section"):
250 section_str = control.Find("Section")
252 c_match = re_contrib.search(section_str)
253 nf_match = re_nonfree.search(section_str)
256 section = colour_output(section_str, 'contrib')
259 section = colour_output(section_str, 'nonfree')
262 section = colour_output(section_str, 'main')
263 if control.has_key("Architecture"):
264 arch_str = control.Find("Architecture")
265 arch = colour_output(arch_str, 'arch')
267 if control.has_key("Maintainer"):
268 maintainer = control.Find("Maintainer")
269 localhost = re_localhost.search(maintainer)
272 maintainer = colour_output(maintainer, 'maintainer')
274 maintainer = escape_if_needed(maintainer)
276 return (control, control_keys, section, depends, recommends, arch, maintainer)
278 def read_changes_or_dsc (suite, filename):
281 dsc_file = utils.open_file(filename)
283 dsc = utils.parse_changes(filename, dsc_file=1)
285 return formatted_text("can't parse .dsc control info")
288 filecontents = strip_pgp_signature(filename)
290 for l in filecontents.split('\n'):
291 m = re.match(r'([-a-zA-Z0-9]*):', l)
293 keysinorder.append(m.group(1))
296 if k in ("build-depends","build-depends-indep"):
297 dsc[k] = create_depends_string(suite, split_depends(dsc[k]))
298 elif k == "architecture":
299 if (dsc["architecture"] != "any"):
300 dsc['architecture'] = colour_output(dsc["architecture"], 'arch')
301 elif k in ("files","changes","description"):
303 dsc[k] = formatted_text(dsc[k], strip=True)
305 dsc[k] = ('\n'+'\n'.join(map(lambda x: ' '+x, dsc[k].split('\n')))).rstrip()
307 dsc[k] = escape_if_needed(dsc[k])
309 keysinorder = filter(lambda x: not x.lower().startswith('checksums-'), keysinorder)
311 filecontents = '\n'.join(map(lambda x: format_field(x,dsc[x.lower()]), keysinorder))+'\n'
314 def create_depends_string (suite, depends_tree):
316 if suite == 'experimental':
317 suite_where = "in ('experimental','unstable')"
319 suite_where = "= '%s'" % suite
322 session = DBConn().session()
323 for l in depends_tree:
324 if (comma_count >= 2):
330 # doesn't do version lookup yet.
332 res = get_binary_from_name_suite(d['name'], suite_where)
337 if d['version'] != '' :
338 adepends += " (%s)" % (d['version'])
340 if i[2] == "contrib":
341 result += colour_output(adepends, "contrib")
342 elif i[2] == "non-free":
343 result += colour_output(adepends, "nonfree")
345 result += colour_output(adepends, "main")
348 if d['version'] != '' :
349 adepends += " (%s)" % (d['version'])
350 result += colour_output(adepends, "bold")
355 def output_package_relations ():
357 Output the package relations, if there is more than one package checked in this run.
360 if len(package_relations) < 2:
361 # Only list something if we have more than one binary to compare
362 package_relations.clear()
366 for package in package_relations:
367 for relation in package_relations[package]:
368 to_print += "%-15s: (%s) %s\n" % (package, relation, package_relations[package][relation])
370 package_relations.clear()
371 return foldable_output("Package relations", "relations", to_print)
373 def output_deb_info(suite, filename, packagename):
374 (control, control_keys, section, depends, recommends, arch, maintainer) = read_control(filename)
377 return formatted_text("no control info")
379 if not package_relations.has_key(packagename):
380 package_relations[packagename] = {}
381 for key in control_keys :
383 field_value = create_depends_string(suite, depends)
384 package_relations[packagename][key] = field_value
385 elif key == 'Recommends':
386 field_value = create_depends_string(suite, recommends)
387 package_relations[packagename][key] = field_value
388 elif key == 'Section':
389 field_value = section
390 elif key == 'Architecture':
392 elif key == 'Maintainer':
393 field_value = maintainer
394 elif key == 'Description':
396 field_value = formatted_text(control.Find(key), strip=True)
398 desc = control.Find(key)
399 desc = re_newlinespace.sub('\n ', desc)
400 field_value = escape_if_needed(desc)
402 field_value = escape_if_needed(control.Find(key))
403 to_print += " "+format_field(key,field_value)+'\n'
406 def do_command (command, filename, escaped=0):
407 o = os.popen("%s %s" % (command, filename))
409 return escaped_text(o.read())
411 return formatted_text(o.read())
413 def do_lintian (filename):
415 return do_command("lintian --show-overrides --color html", filename, 1)
417 return do_command("lintian --show-overrides --color always", filename, 1)
419 def get_copyright (deb_filename):
420 global changes_lock, printed_copyrights
422 package = re_package.sub(r'\1', deb_filename)
423 o = os.popen("dpkg-deb -c %s | egrep 'usr(/share)?/doc/[^/]*/copyright' | awk '{print $6}' | head -n 1" % (deb_filename))
424 cright = o.read()[:-1]
427 return formatted_text("WARNING: No copyright found, please check package manually.")
429 doc_directory = re_doc_directory.sub(r'\1', cright)
430 if package != doc_directory:
431 return formatted_text("WARNING: wrong doc directory (expected %s, got %s)." % (package, doc_directory))
433 o = os.popen("dpkg-deb --fsys-tarfile %s | tar xvOf - %s 2>/dev/null" % (deb_filename, cright))
435 copyrightmd5 = md5.md5(cright).hexdigest()
438 changes_lock.acquire()
439 if printed_copyrights.has_key(copyrightmd5) and printed_copyrights[copyrightmd5] != "%s (%s)" % (package, deb_filename):
440 res += formatted_text( "NOTE: Copyright is the same as %s.\n\n" % \
441 (printed_copyrights[copyrightmd5]))
443 printed_copyrights[copyrightmd5] = "%s (%s)" % (package, deb_filename)
444 changes_lock.release()
445 return res+formatted_text(cright)
447 def get_readme_source (dsc_filename):
448 tempdir = utils.temp_dirname()
451 cmd = "dpkg-source --no-check --no-copy -x %s %s" % (dsc_filename, tempdir)
452 (result, output) = commands.getstatusoutput(cmd)
454 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"
455 res += "Error, couldn't extract source, WTF?\n"
456 res += "'dpkg-source -x' failed. return code: %s.\n\n" % (result)
460 path = os.path.join(tempdir, 'debian/README.source')
462 if os.path.exists(path):
463 res += do_command("cat", path)
465 res += "No README.source in this package\n\n"
468 shutil.rmtree(tempdir)
470 if errno.errorcode[e.errno] != 'EACCES':
471 res += "%s: couldn't remove tmp dir %s for source tree." % (dsc_filename, tempdir)
475 def check_dsc (suite, dsc_filename):
476 (dsc) = read_changes_or_dsc(suite, dsc_filename)
477 return foldable_output(dsc_filename, "dsc", dsc, norow=True) + \
479 foldable_output("lintian check for %s" % dsc_filename,
480 "source-lintian", do_lintian(dsc_filename)) + \
482 foldable_output("README.source for %s" % dsc_filename,
483 "source-readmesource", get_readme_source(dsc_filename))
485 def check_deb (suite, deb_filename):
486 filename = os.path.basename(deb_filename)
487 packagename = filename.split('_')[0]
489 if filename.endswith(".udeb"):
494 result = foldable_output("control file for %s" % (filename), "binary-%s-control"%packagename,
495 output_deb_info(suite, deb_filename, packagename), norow=True) + "\n"
498 result += foldable_output("skipping lintian check for udeb",
499 "binary-%s-lintian"%packagename, "") + "\n"
501 result += foldable_output("lintian check for %s" % (filename),
502 "binary-%s-lintian"%packagename, do_lintian(deb_filename)) + "\n"
504 result += foldable_output("contents of %s" % (filename), "binary-%s-contents"%packagename,
505 do_command("dpkg -c", deb_filename)) + "\n"
508 result += foldable_output("skipping copyright for udeb",
509 "binary-%s-copyright"%packagename, "") + "\n"
511 result += foldable_output("copyright of %s" % (filename),
512 "binary-%s-copyright"%packagename, get_copyright(deb_filename)) + "\n"
514 result += foldable_output("file listing of %s" % (filename),
515 "binary-%s-file-listing"%packagename, do_command("ls -l", deb_filename))
519 # Read a file, strip the signature and return the modified contents as
521 def strip_pgp_signature (filename):
522 inputfile = utils.open_file (filename)
526 for line in inputfile.readlines():
534 if line.startswith("-----BEGIN PGP SIGNED MESSAGE"):
537 if line.startswith("-----BEGIN PGP SIGNATURE"):
540 if line.startswith("-----END PGP SIGNATURE"):
547 def display_changes(suite, changes_filename):
548 global changes_lock, printed_copyrights
549 changes = read_changes_or_dsc(suite, changes_filename)
550 changes_lock.acquire()
551 printed_copyrights = {}
552 changes_lock.release()
553 return foldable_output(changes_filename, "changes", changes, norow=True)
555 def check_changes (changes_filename):
557 changes = utils.parse_changes (changes_filename)
558 except ChangesUnicodeError:
559 utils.warn("Encoding problem with changes file %s" % (changes_filename))
560 print display_changes(changes['distribution'], changes_filename)
562 files = utils.build_file_list(changes)
563 for f in files.keys():
564 if f.endswith(".deb") or f.endswith(".udeb"):
565 print check_deb(changes['distribution'], f)
566 if f.endswith(".dsc"):
567 print check_dsc(changes['distribution'], f)
571 global Cnf, db_files, waste, excluded
573 # Cnf = utils.get_conf()
575 Arguments = [('h',"help","Examine-Package::Options::Help"),
576 ('H',"html-output","Examine-Package::Options::Html-Output"),
578 for i in [ "Help", "Html-Output", "partial-html" ]:
579 if not Cnf.has_key("Examine-Package::Options::%s" % (i)):
580 Cnf["Examine-Package::Options::%s" % (i)] = ""
582 args = apt_pkg.ParseCommandLine(Cnf,Arguments,sys.argv)
583 Options = Cnf.SubTree("Examine-Package::Options")
588 if Options["Html-Output"]:
592 stdout_fd = sys.stdout
596 if not Options["Html-Output"]:
597 # Pipe output for each argument through less
598 less_fd = os.popen("less -R -", 'w', 0)
599 # -R added to display raw control chars for colour
602 if f.endswith(".changes"):
604 elif f.endswith(".deb") or f.endswith(".udeb"):
605 # default to unstable when we don't have a .changes file
606 # perhaps this should be a command line option?
607 print check_deb('unstable', f)
608 elif f.endswith(".dsc"):
609 print check_dsc('unstable', f)
611 utils.fubar("Unrecognised file type: '%s'." % (f))
613 print output_package_relations()
614 if not Options["Html-Output"]:
615 # Reset stdout here so future less invocations aren't FUBAR
617 sys.stdout = stdout_fd
619 if errno.errorcode[e.errno] == 'EPIPE':
620 utils.warn("[examine-package] Caught EPIPE; skipping.")
624 except KeyboardInterrupt:
625 utils.warn("[examine-package] Caught C-c; skipping.")
628 #######################################################################################
630 if __name__ == '__main__':