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 ################################################################################
45 # suppress some deprecation warnings in squeeze related to md5 module
47 warnings.filterwarnings('ignore', \
48 "the md5 module is deprecated; use hashlib instead", \
62 from daklib import utils
63 from daklib.config import Config
64 from daklib.dbconn import DBConn, get_component_by_package_suite
65 from daklib.gpg import SignedFile
66 from daklib.regexes import html_escaping, re_html_escaping, re_version, re_spacestrip, \
67 re_contrib, re_nonfree, re_localhost, re_newlinespace, \
68 re_package, re_doc_directory
69 from daklib.dak_exceptions import ChangesUnicodeError
70 import daklib.daksubprocess
72 ################################################################################
75 Cnf = utils.get_conf()
77 printed = threading.local()
78 printed.copyrights = {}
79 package_relations = {} #: Store relations of packages for later output
81 # default is to not output html.
84 ################################################################################
86 def usage (exit_code=0):
87 print """Usage: dak examine-package [PACKAGE]...
90 -h, --help show this help and exit
91 -H, --html-output output html page with inspection result
92 -f, --file-name filename for the html page
94 PACKAGE can be a .changes, .dsc, .deb or .udeb filename."""
98 ################################################################################
99 # probably xml.sax.saxutils would work as well
101 def escape_if_needed(s):
103 return re_html_escaping.sub(lambda x: html_escaping.get(x.group(0)), s)
107 def headline(s, level=2, bodyelement=None):
111 <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>
112 </thead>\n"""%{"bodyelement":bodyelement,"title":utils.html_escape(os.path.basename(s))}
114 return "<h%d>%s</h%d>\n" % (level, utils.html_escape(s), level)
116 return "---- %s ----\n" % (s)
118 # Colour definitions, 'end' isn't really for use
122 'contrib': "\033[33m",
123 'nonfree': "\033[31m",
124 'provides': "\033[35m",
128 'maintainer': "\033[32m",
129 'distro': "\033[1m\033[41m"}
132 'main': ('<span style="color: aqua">',"</span>"),
133 'contrib': ('<span style="color: yellow">',"</span>"),
134 'nonfree': ('<span style="color: red">',"</span>"),
135 'provides': ('<span style="color: magenta">',"</span>"),
136 'arch': ('<span style="color: green">',"</span>"),
137 'bold': ('<span style="font-weight: bold">',"</span>"),
138 'maintainer': ('<span style="color: green">',"</span>"),
139 'distro': ('<span style="font-weight: bold; background-color: red">',"</span>")}
141 def colour_output(s, colour):
143 return ("%s%s%s" % (html_colours[colour][0], utils.html_escape(s), html_colours[colour][1]))
145 return ("%s%s%s" % (ansi_colours[colour], s, ansi_colours['end']))
147 def escaped_text(s, strip=False):
151 return "<pre>%s</pre>" % (s)
155 def formatted_text(s, strip=False):
159 return "<pre>%s</pre>" % (utils.html_escape(s))
165 return """<tr><td>"""+s+"""</td></tr>"""
169 def format_field(k,v):
171 return """<tr><td class="key">%s:</td><td class="val">%s</td></tr>"""%(k,v)
173 return "%s: %s"%(k,v)
175 def foldable_output(title, elementnameprefix, content, norow=False):
176 d = {'elementnameprefix':elementnameprefix}
179 result += """<div id="%(elementnameprefix)s-wrap"><a name="%(elementnameprefix)s" />
180 <table class="infobox rfc822">\n"""%d
181 result += headline(title, bodyelement="%(elementnameprefix)s-body"%d)
183 result += """ <tbody id="%(elementnameprefix)s-body" class="infobody">\n"""%d
185 result += content + "\n"
187 result += output_row(content) + "\n"
189 result += """</tbody></table></div>"""
192 ################################################################################
194 def get_depends_parts(depend) :
195 v_match = re_version.match(depend)
197 d_parts = { 'name' : v_match.group(1), 'version' : v_match.group(2) }
199 d_parts = { 'name' : depend , 'version' : '' }
202 def get_or_list(depend) :
203 or_list = depend.split("|")
206 def get_comma_list(depend) :
207 dep_list = depend.split(",")
210 def split_depends (d_str) :
211 # creates a list of lists of dictionaries of depends (package,version relation)
213 d_str = re_spacestrip.sub('',d_str)
215 # first split depends string up amongs comma delimiter
216 dep_list = get_comma_list(d_str)
218 while d < len(dep_list):
219 # put depends into their own list
220 depends_tree.append([dep_list[d]])
223 while d < len(depends_tree):
225 # split up Or'd depends into a multi-item list
226 depends_tree[d] = get_or_list(depends_tree[d][0])
227 while k < len(depends_tree[d]):
228 # split depends into {package, version relation}
229 depends_tree[d][k] = get_depends_parts(depends_tree[d][k])
234 def read_control (filename):
242 deb_file = utils.open_file(filename)
244 extracts = utils.deb_extract_control(deb_file)
245 control = apt_pkg.TagSection(extracts)
247 print formatted_text("can't parse control info")
253 control_keys = control.keys()
255 if "Pre-Depends" in control:
256 predepends_str = control["Pre-Depends"]
257 predepends = split_depends(predepends_str)
259 if "Depends" in control:
260 depends_str = control["Depends"]
261 # create list of dependancy lists
262 depends = split_depends(depends_str)
264 if "Recommends" in control:
265 recommends_str = control["Recommends"]
266 recommends = split_depends(recommends_str)
268 if "Section" in control:
269 section_str = control["Section"]
271 c_match = re_contrib.search(section_str)
272 nf_match = re_nonfree.search(section_str)
275 section = colour_output(section_str, 'contrib')
278 section = colour_output(section_str, 'nonfree')
281 section = colour_output(section_str, 'main')
282 if "Architecture" in control:
283 arch_str = control["Architecture"]
284 arch = colour_output(arch_str, 'arch')
286 if "Maintainer" in control:
287 maintainer = control["Maintainer"]
288 localhost = re_localhost.search(maintainer)
291 maintainer = colour_output(maintainer, 'maintainer')
293 maintainer = escape_if_needed(maintainer)
295 return (control, control_keys, section, predepends, depends, recommends, arch, maintainer)
297 def read_changes_or_dsc (suite, filename, session = None):
300 dsc_file = utils.open_file(filename)
302 dsc = utils.parse_changes(filename, dsc_file=1)
304 return formatted_text("can't parse .dsc control info")
307 filecontents = strip_pgp_signature(filename)
309 for l in filecontents.split('\n'):
310 m = re.match(r'([-a-zA-Z0-9]*):', l)
312 keysinorder.append(m.group(1))
315 if k in ("build-depends","build-depends-indep"):
316 dsc[k] = create_depends_string(suite, split_depends(dsc[k]), session)
317 elif k == "architecture":
318 if (dsc["architecture"] != "any"):
319 dsc['architecture'] = colour_output(dsc["architecture"], 'arch')
320 elif k == "distribution":
321 if dsc["distribution"] not in ('unstable', 'experimental'):
322 dsc['distribution'] = colour_output(dsc["distribution"], 'distro')
323 elif k in ("files","changes","description"):
325 dsc[k] = formatted_text(dsc[k], strip=True)
327 dsc[k] = ('\n'+'\n'.join(map(lambda x: ' '+x, dsc[k].split('\n')))).rstrip()
329 dsc[k] = escape_if_needed(dsc[k])
331 keysinorder = filter(lambda x: not x.lower().startswith('checksums-'), keysinorder)
333 filecontents = '\n'.join(map(lambda x: format_field(x,dsc[x.lower()]), keysinorder))+'\n'
336 def get_provides(suite):
338 session = DBConn().session()
339 query = '''SELECT DISTINCT value
340 FROM binaries_metadata m
341 JOIN bin_associations b
346 WHERE key = 'Provides' )
350 WHERE suite_name = '%(suite)s'
351 OR codename = '%(suite)s')''' % \
353 for p in session.execute(query):
355 for i in e.split(','):
356 provides.add(i.strip())
360 def create_depends_string (suite, depends_tree, session = None):
362 if suite == 'experimental':
363 suite_list = ['experimental','unstable']
369 for l in depends_tree:
370 if (comma_count >= 2):
376 # doesn't do version lookup yet.
378 component = get_component_by_package_suite(d['name'], suite_list, \
380 if component is not None:
382 if d['version'] != '' :
383 adepends += " (%s)" % (d['version'])
385 if component == "contrib":
386 result += colour_output(adepends, "contrib")
387 elif component == "non-free":
388 result += colour_output(adepends, "nonfree")
390 result += colour_output(adepends, "main")
393 if d['version'] != '' :
394 adepends += " (%s)" % (d['version'])
396 provides = get_provides(suite)
397 if d['name'] in provides:
398 result += colour_output(adepends, "provides")
400 result += colour_output(adepends, "bold")
405 def output_package_relations ():
407 Output the package relations, if there is more than one package checked in this run.
410 if len(package_relations) < 2:
411 # Only list something if we have more than one binary to compare
412 package_relations.clear()
416 for package in package_relations:
417 for relation in package_relations[package]:
418 to_print += "%-15s: (%s) %s\n" % (package, relation, package_relations[package][relation])
420 package_relations.clear()
421 return foldable_output("Package relations", "relations", to_print)
423 def output_deb_info(suite, filename, packagename, session = None):
424 (control, control_keys, section, predepends, depends, recommends, arch, maintainer) = read_control(filename)
427 return formatted_text("no control info")
429 if not package_relations.has_key(packagename):
430 package_relations[packagename] = {}
431 for key in control_keys :
432 if key == 'Pre-Depends':
433 field_value = create_depends_string(suite, predepends, session)
434 package_relations[packagename][key] = field_value
435 elif key == 'Depends':
436 field_value = create_depends_string(suite, depends, session)
437 package_relations[packagename][key] = field_value
438 elif key == 'Recommends':
439 field_value = create_depends_string(suite, recommends, session)
440 package_relations[packagename][key] = field_value
441 elif key == 'Section':
442 field_value = section
443 elif key == 'Architecture':
445 elif key == 'Maintainer':
446 field_value = maintainer
447 elif key == 'Homepage':
448 field_value = escape_if_needed(control.find(key))
450 field_value = '<a href="%s" rel="nofollow">%s</a>' % \
451 (field_value, field_value)
452 elif key == 'Description':
454 field_value = formatted_text(control.find(key), strip=True)
456 desc = control.find(key)
457 desc = re_newlinespace.sub('\n ', desc)
458 field_value = escape_if_needed(desc)
460 field_value = escape_if_needed(control.find(key))
461 to_print += " "+format_field(key,field_value)+'\n'
464 def do_command (command, escaped=False):
465 process = daklib.daksubprocess.Popen(command, stdout=subprocess.PIPE)
469 return escaped_text(o.read())
471 return formatted_text(o.read())
475 def do_lintian (filename):
479 user = cnf.get('Dinstall::UnprivUser') or None
481 cmd.extend(['sudo', '-H', '-u', user])
487 cmd.extend(['lintian', '--show-overrides', '--color', color, "--", filename])
489 return do_command(cmd, escaped=True)
491 def get_copyright (deb_filename):
494 package = re_package.sub(r'\1', os.path.basename(deb_filename))
495 o = os.popen("dpkg-deb -c %s | egrep 'usr(/share)?/doc/[^/]*/copyright' | awk '{print $6}' | head -n 1" % (deb_filename))
496 cright = o.read()[:-1]
499 return formatted_text("WARNING: No copyright found, please check package manually.")
501 doc_directory = re_doc_directory.sub(r'\1', cright)
502 if package != doc_directory:
503 return formatted_text("WARNING: wrong doc directory (expected %s, got %s)." % (package, doc_directory))
505 o = os.popen("dpkg-deb --fsys-tarfile %s | tar xvOf - %s 2>/dev/null" % (deb_filename, cright))
507 copyrightmd5 = md5.md5(cright).hexdigest()
510 if printed.copyrights.has_key(copyrightmd5) and printed.copyrights[copyrightmd5] != "%s (%s)" % (package, os.path.basename(deb_filename)):
511 res += formatted_text( "NOTE: Copyright is the same as %s.\n\n" % \
512 (printed.copyrights[copyrightmd5]))
514 printed.copyrights[copyrightmd5] = "%s (%s)" % (package, os.path.basename(deb_filename))
515 return res+formatted_text(cright)
517 def get_readme_source (dsc_filename):
518 tempdir = utils.temp_dirname()
521 cmd = ('dpkg-source', '--no-check', '--no-copy', '-x', dsc_filename, tempdir)
523 daklib.daksubprocess.check_output(cmd, stderr=1)
524 except subprocess.CalledProcessError as e:
525 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"
526 res += "Error, couldn't extract source, WTF?\n"
527 res += "'dpkg-source -x' failed. return code: %s.\n\n" % (e.returncode)
531 path = os.path.join(tempdir, 'debian/README.source')
533 if os.path.exists(path):
534 res += do_command(["cat", "--", path])
536 res += "No README.source in this package\n\n"
539 shutil.rmtree(tempdir)
541 if errno.errorcode[e.errno] != 'EACCES':
542 res += "%s: couldn't remove tmp dir %s for source tree." % (dsc_filename, tempdir)
546 def check_dsc (suite, dsc_filename, session = None):
547 dsc = read_changes_or_dsc(suite, dsc_filename, session)
548 dsc_basename = os.path.basename(dsc_filename)
549 return foldable_output(dsc_filename, "dsc", dsc, norow=True) + \
551 foldable_output("lintian check for %s" % dsc_basename,
552 "source-lintian", do_lintian(dsc_filename)) + \
554 foldable_output("README.source for %s" % dsc_basename,
555 "source-readmesource", get_readme_source(dsc_filename))
557 def check_deb (suite, deb_filename, session = None):
558 filename = os.path.basename(deb_filename)
559 packagename = filename.split('_')[0]
561 if filename.endswith(".udeb"):
566 result = foldable_output("control file for %s" % (filename), "binary-%s-control"%packagename,
567 output_deb_info(suite, deb_filename, packagename, session), norow=True) + "\n"
570 result += foldable_output("skipping lintian check for udeb",
571 "binary-%s-lintian"%packagename, "") + "\n"
573 result += foldable_output("lintian check for %s" % (filename),
574 "binary-%s-lintian"%packagename, do_lintian(deb_filename)) + "\n"
576 result += foldable_output("contents of %s" % (filename), "binary-%s-contents"%packagename,
577 do_command(["dpkg", "-c", deb_filename])) + "\n"
580 result += foldable_output("skipping copyright for udeb",
581 "binary-%s-copyright"%packagename, "") + "\n"
583 result += foldable_output("copyright of %s" % (filename),
584 "binary-%s-copyright"%packagename, get_copyright(deb_filename)) + "\n"
588 # Read a file, strip the signature and return the modified contents as
590 def strip_pgp_signature (filename):
591 with utils.open_file(filename) as f:
593 signedfile = SignedFile(data, keyrings=(), require_signature=False)
594 return signedfile.contents
596 def display_changes(suite, changes_filename):
598 changes = read_changes_or_dsc(suite, changes_filename)
599 printed.copyrights = {}
600 return foldable_output(changes_filename, "changes", changes, norow=True)
602 def check_changes (changes_filename):
604 changes = utils.parse_changes (changes_filename)
605 except ChangesUnicodeError:
606 utils.warn("Encoding problem with changes file %s" % (changes_filename))
607 print display_changes(changes['distribution'], changes_filename)
609 files = utils.build_file_list(changes)
610 for f in files.keys():
611 if f.endswith(".deb") or f.endswith(".udeb"):
612 print check_deb(changes['distribution'], f)
613 if f.endswith(".dsc"):
614 print check_dsc(changes['distribution'], f)
618 global Cnf, db_files, waste, excluded
620 # Cnf = utils.get_conf()
622 Arguments = [('h',"help","Examine-Package::Options::Help"),
623 ('H',"html-output","Examine-Package::Options::Html-Output"),
625 for i in [ "Help", "Html-Output", "partial-html" ]:
626 if not Cnf.has_key("Examine-Package::Options::%s" % (i)):
627 Cnf["Examine-Package::Options::%s" % (i)] = ""
629 args = apt_pkg.parse_commandline(Cnf,Arguments,sys.argv)
630 Options = Cnf.subtree("Examine-Package::Options")
635 if Options["Html-Output"]:
639 stdout_fd = sys.stdout
643 if not Options["Html-Output"]:
644 # Pipe output for each argument through less
645 less_cmd = ("less", "-R", "-")
646 less_process = daklib.daksubprocess.Popen(less_cmd, stdin=subprocess.PIPE, bufsize=0)
647 less_fd = less_process.stdin
648 # -R added to display raw control chars for colour
651 if f.endswith(".changes"):
653 elif f.endswith(".deb") or f.endswith(".udeb"):
654 # default to unstable when we don't have a .changes file
655 # perhaps this should be a command line option?
656 print check_deb('unstable', f)
657 elif f.endswith(".dsc"):
658 print check_dsc('unstable', f)
660 utils.fubar("Unrecognised file type: '%s'." % (f))
662 print output_package_relations()
663 if not Options["Html-Output"]:
664 # Reset stdout here so future less invocations aren't FUBAR
667 sys.stdout = stdout_fd
669 if errno.errorcode[e.errno] == 'EPIPE':
670 utils.warn("[examine-package] Caught EPIPE; skipping.")
674 except KeyboardInterrupt:
675 utils.warn("[examine-package] Caught C-c; skipping.")
678 #######################################################################################
680 if __name__ == '__main__':