]> git.decadent.org.uk Git - dak.git/blob - dak/examine_package.py
Fix examine_packages
[dak.git] / dak / examine_package.py
1 #!/usr/bin/env python
2
3 # Script to automate some parts of checking NEW packages
4 # Copyright (C) 2000, 2001, 2002, 2003, 2006  James Troup <james@nocrew.org>
5
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.
10
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.
15
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
19
20 ################################################################################
21
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,
31 #      right? :)
32
33 ################################################################################
34
35 import errno, os, pg, re, sys, md5
36 import apt_pkg, apt_inst
37 import daklib.database, daklib.utils
38
39 ################################################################################
40
41 re_package = re.compile(r"^(.+?)_.*")
42 re_doc_directory = re.compile(r".*/doc/([^/]*).*")
43
44 re_contrib = re.compile('^contrib/')
45 re_nonfree = re.compile('^non\-free/')
46
47 re_arch = re.compile("Architecture: .*")
48 re_builddep = re.compile("Build-Depends: .*")
49 re_builddepind = re.compile("Build-Depends-Indep: .*")
50
51 re_localhost = re.compile("localhost\.localdomain")
52 re_version = re.compile('^(.*)\((.*)\)')
53
54 re_newlinespace = re.compile('\n')
55 re_spacestrip = re.compile('(\s)')
56
57 ################################################################################
58
59 # Colour definitions
60
61 # Main
62 main_colour = "\033[36m"
63 # Contrib
64 contrib_colour = "\033[33m"
65 # Non-Free
66 nonfree_colour = "\033[31m"
67 # Arch
68 arch_colour = "\033[32m"
69 # End
70 end_colour = "\033[0m"
71 # Bold
72 bold_colour = "\033[1m"
73 # Bad maintainer
74 maintainer_colour = arch_colour
75
76 ################################################################################
77
78 Cnf = None
79 projectB = None
80
81 Cnf = daklib.utils.get_conf()
82 projectB = pg.connect(Cnf["DB::Name"], Cnf["DB::Host"], int(Cnf["DB::Port"]))
83 daklib.database.init(Cnf, projectB)
84
85 printed_copyrights = {}
86
87 ################################################################################
88
89 def usage (exit_code=0):
90     print """Usage: dak examine-package [PACKAGE]...
91 Check NEW package(s).
92
93   -h, --help                 show this help and exit
94
95 PACKAGE can be a .changes, .dsc, .deb or .udeb filename."""
96
97     sys.exit(exit_code)
98
99 ################################################################################
100
101 def get_depends_parts(depend) :
102     v_match = re_version.match(depend)
103     if v_match:
104         d_parts = { 'name' : v_match.group(1), 'version' : v_match.group(2) }
105     else :
106         d_parts = { 'name' : depend , 'version' : '' }
107     return d_parts
108
109 def get_or_list(depend) :
110     or_list = depend.split("|")
111     return or_list
112
113 def get_comma_list(depend) :
114     dep_list = depend.split(",")
115     return dep_list
116
117 def split_depends (d_str) :
118     # creates a list of lists of dictionaries of depends (package,version relation)
119
120     d_str = re_spacestrip.sub('',d_str)
121     depends_tree = []
122     # first split depends string up amongs comma delimiter
123     dep_list = get_comma_list(d_str)
124     d = 0
125     while d < len(dep_list):
126         # put depends into their own list
127         depends_tree.append([dep_list[d]])
128         d += 1
129     d = 0
130     while d < len(depends_tree):
131         k = 0
132         # split up Or'd depends into a multi-item list
133         depends_tree[d] = get_or_list(depends_tree[d][0])
134         while k < len(depends_tree[d]):
135             # split depends into {package, version relation}
136             depends_tree[d][k] = get_depends_parts(depends_tree[d][k])
137             k += 1
138         d += 1
139     return depends_tree
140
141 def read_control (filename):
142     recommends = []
143     depends = []
144     section = ''
145     maintainer = ''
146     arch = ''
147
148     deb_file = daklib.utils.open_file(filename)
149     try:
150         extracts = apt_inst.debExtractControl(deb_file)
151         control = apt_pkg.ParseSection(extracts)
152     except:
153         print "can't parse control info"
154         control = ''
155
156     deb_file.close()
157
158     control_keys = control.keys()
159
160     if control.has_key("Depends"):
161         depends_str = control.Find("Depends")
162         # create list of dependancy lists
163         depends = split_depends(depends_str)
164
165     if control.has_key("Recommends"):
166         recommends_str = control.Find("Recommends")
167         recommends = split_depends(recommends_str)
168
169     if control.has_key("Section"):
170         section_str = control.Find("Section")
171
172         c_match = re_contrib.search(section_str)
173         nf_match = re_nonfree.search(section_str)
174         if c_match :
175             # contrib colour
176             section = contrib_colour + section_str + end_colour
177         elif nf_match :
178             # non-free colour
179             section = nonfree_colour + section_str + end_colour
180         else :
181             # main
182             section = main_colour +  section_str + end_colour
183     if control.has_key("Architecture"):
184         arch_str = control.Find("Architecture")
185         arch = arch_colour + arch_str + end_colour
186
187     if control.has_key("Maintainer"):
188         maintainer = control.Find("Maintainer")
189         localhost = re_localhost.search(maintainer)
190         if localhost:
191             #highlight bad email
192             maintainer = maintainer_colour + maintainer + end_colour
193
194     return (control, control_keys, section, depends, recommends, arch, maintainer)
195
196 def read_dsc (dsc_filename):
197     dsc = {}
198
199     dsc_file = daklib.utils.open_file(dsc_filename)
200     try:
201         dsc = daklib.utils.parse_changes(dsc_filename)
202     except:
203         print "can't parse control info"
204     dsc_file.close()
205
206     filecontents = strip_pgp_signature(dsc_filename)
207
208     if dsc.has_key("build-depends"):
209         builddep = split_depends(dsc["build-depends"])
210         builddepstr = create_depends_string(builddep)
211         filecontents = re_builddep.sub("Build-Depends: "+builddepstr, filecontents)
212
213     if dsc.has_key("build-depends-indep"):
214         builddepindstr = create_depends_string(split_depends(dsc["build-depends-indep"]))
215         filecontents = re_builddepind.sub("Build-Depends-Indep: "+builddepindstr, filecontents)
216
217     if dsc.has_key("architecture") :
218         if (dsc["architecture"] != "any"):
219             newarch = arch_colour + dsc["architecture"] + end_colour
220             filecontents = re_arch.sub("Architecture: " + newarch, filecontents)
221
222     return filecontents
223
224 def create_depends_string (depends_tree):
225     # just look up unstable for now. possibly pull from .changes later
226     suite = "unstable"
227     result = ""
228     comma_count = 1
229     for l in depends_tree:
230         if (comma_count >= 2):
231             result += ", "
232         or_count = 1
233         for d in l:
234             if (or_count >= 2 ):
235                 result += " | "
236             # doesn't do version lookup yet.
237
238             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))
239             ql = q.getresult()
240             if ql:
241                 i = ql[0]
242
243                 if i[2] == "contrib":
244                     result += contrib_colour + d['name']
245                 elif i[2] == "non-free":
246                     result += nonfree_colour + d['name']
247                 else :
248                     result += main_colour + d['name']
249
250                 if d['version'] != '' :
251                     result += " (%s)" % (d['version'])
252                 result += end_colour
253             else:
254                 result += bold_colour + d['name']
255                 if d['version'] != '' :
256                     result += " (%s)" % (d['version'])
257                 result += end_colour
258             or_count += 1
259         comma_count += 1
260     return result
261
262 def output_deb_info(filename):
263     (control, control_keys, section, depends, recommends, arch, maintainer) = read_control(filename)
264
265     if control == '':
266         print "no control info"
267     else:
268         for key in control_keys :
269             output = " " + key + ": "
270             if key == 'Depends':
271                 output += create_depends_string(depends)
272             elif key == 'Recommends':
273                 output += create_depends_string(recommends)
274             elif key == 'Section':
275                 output += section
276             elif key == 'Architecture':
277                 output += arch
278             elif key == 'Maintainer':
279                 output += maintainer
280             elif key == 'Description':
281                 desc = control.Find(key)
282                 desc = re_newlinespace.sub('\n ', desc)
283                 output += desc
284             else:
285                 output += control.Find(key)
286             print output
287
288 def do_command (command, filename):
289     o = os.popen("%s %s" % (command, filename))
290     print o.read()
291
292 def print_copyright (deb_filename):
293     package = re_package.sub(r'\1', deb_filename)
294     o = os.popen("dpkg-deb -c %s | egrep 'usr(/share)?/doc/[^/]*/copyright' | awk '{print $6}' | head -n 1" % (deb_filename))
295     copyright = o.read()[:-1]
296
297     if copyright == "":
298         print "WARNING: No copyright found, please check package manually."
299         return
300
301     doc_directory = re_doc_directory.sub(r'\1', copyright)
302     if package != doc_directory:
303         print "WARNING: wrong doc directory (expected %s, got %s)." % (package, doc_directory)
304         return
305
306     o = os.popen("dpkg-deb --fsys-tarfile %s | tar xvOf - %s" % (deb_filename, copyright))
307     copyright = o.read()
308     copyrightmd5 = md5.md5(copyright).hexdigest()
309
310     if printed_copyrights.has_key(copyrightmd5) and printed_copyrights[copyrightmd5] != "%s (%s)" % (package, deb_filename):
311         print "NOTE: Copyright is the same as %s.\n" % \
312                 (printed_copyrights[copyrightmd5])
313     else:
314         printed_copyrights[copyrightmd5] = "%s (%s)" % (package, deb_filename)
315
316     print copyright
317
318 def check_dsc (dsc_filename):
319     print "---- .dsc file for %s ----" % (dsc_filename)
320     (dsc) = read_dsc(dsc_filename)
321     print dsc
322     print "---- lintian check for %s ----" % (dsc_filename)
323         do_command ("lintian --show-overrides --color always", dsc_filename)
324
325 def check_deb (deb_filename):
326     filename = os.path.basename(deb_filename)
327
328     if filename.endswith(".udeb"):
329         is_a_udeb = 1
330     else:
331         is_a_udeb = 0
332
333     print "---- control file for %s ----" % (filename)
334     #do_command ("dpkg -I", deb_filename)
335     output_deb_info(deb_filename)
336
337     if is_a_udeb:
338         print "---- skipping lintian check for udeb ----"
339         print 
340     else:
341         print "---- lintian check for %s ----" % (filename)
342         do_command ("lintian --show-overrides --color always", deb_filename)
343         print "---- linda check for %s ----" % (filename)
344         do_command ("linda", deb_filename)
345
346     print "---- contents of %s ----" % (filename)
347     do_command ("dpkg -c", deb_filename)
348
349     if is_a_udeb:
350         print "---- skipping copyright for udeb ----"
351     else:
352         print "---- copyright of %s ----" % (filename)
353         print_copyright(deb_filename)
354
355     print "---- file listing of %s ----" % (filename)
356     do_command ("ls -l", deb_filename)
357
358 # Read a file, strip the signature and return the modified contents as
359 # a string.
360 def strip_pgp_signature (filename):
361     file = daklib.utils.open_file (filename)
362     contents = ""
363     inside_signature = 0
364     skip_next = 0
365     for line in file.readlines():
366         if line[:-1] == "":
367             continue
368         if inside_signature:
369             continue
370         if skip_next:
371             skip_next = 0
372             continue
373         if line.startswith("-----BEGIN PGP SIGNED MESSAGE"):
374             skip_next = 1
375             continue
376         if line.startswith("-----BEGIN PGP SIGNATURE"):
377             inside_signature = 1
378             continue
379         if line.startswith("-----END PGP SIGNATURE"):
380             inside_signature = 0
381             continue
382         contents += line
383     file.close()
384     return contents
385
386 # Display the .changes [without the signature]
387 def display_changes (changes_filename):
388     print "---- .changes file for %s ----" % (changes_filename)
389     print strip_pgp_signature(changes_filename)
390
391 def check_changes (changes_filename):
392     display_changes(changes_filename)
393
394     changes = daklib.utils.parse_changes (changes_filename)
395     files = daklib.utils.build_file_list(changes)
396     for file in files.keys():
397         if file.endswith(".deb") or file.endswith(".udeb"):
398             check_deb(file)
399         if file.endswith(".dsc"):
400             check_dsc(file)
401         # else: => byhand
402
403 def main ():
404     global Cnf, projectB, db_files, waste, excluded
405
406 #    Cnf = daklib.utils.get_conf()
407
408     Arguments = [('h',"help","Examine-Package::Options::Help")]
409     for i in [ "help" ]:
410         if not Cnf.has_key("Frenanda::Options::%s" % (i)):
411             Cnf["Examine-Package::Options::%s" % (i)] = ""
412
413     args = apt_pkg.ParseCommandLine(Cnf,Arguments,sys.argv)
414     Options = Cnf.SubTree("Examine-Package::Options")
415
416     if Options["Help"]:
417         usage()
418
419     stdout_fd = sys.stdout
420
421     for file in args:
422         try:
423             # Pipe output for each argument through less
424             less_fd = os.popen("less -R -", 'w', 0)
425             # -R added to display raw control chars for colour
426             sys.stdout = less_fd
427
428             try:
429                 if file.endswith(".changes"):
430                     check_changes(file)
431                 elif file.endswith(".deb") or file.endswith(".udeb"):
432                     check_deb(file)
433                 elif file.endswith(".dsc"):
434                     check_dsc(file)
435                 else:
436                     daklib.utils.fubar("Unrecognised file type: '%s'." % (file))
437             finally:
438                 # Reset stdout here so future less invocations aren't FUBAR
439                 less_fd.close()
440                 sys.stdout = stdout_fd
441         except IOError, e:
442             if errno.errorcode[e.errno] == 'EPIPE':
443                 daklib.utils.warn("[examine-package] Caught EPIPE; skipping.")
444                 pass
445             else:
446                 raise
447         except KeyboardInterrupt:
448             daklib.utils.warn("[examine-package] Caught C-c; skipping.")
449             pass
450
451 #######################################################################################
452
453 if __name__ == '__main__':
454     main()
455