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