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