]> git.decadent.org.uk Git - dak.git/blob - utils.py
Fix extract_component_from_section and add a test suite.
[dak.git] / utils.py
1 # Utility functions
2 # Copyright (C) 2000  James Troup <james@nocrew.org>
3 # $Id: utils.py,v 1.26 2001-06-10 16:35:03 troup Exp $
4
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 of the License, or
8 # (at your option) any later version.
9
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18
19 import commands, os, pwd, re, socket, shutil, stat, string, sys, tempfile
20 import apt_pkg
21
22 re_comments = re.compile(r"\#.*")
23 re_no_epoch = re.compile(r"^\d*\:")
24 re_no_revision = re.compile(r"\-[^-]*$")
25 re_arch_from_filename = re.compile(r"/binary-[^/]+/")
26 re_extract_src_version = re.compile (r"(\S+)\s*\((.*)\)")
27 re_isadeb = re.compile (r".*\.u?deb$");
28 re_issource = re.compile (r"(.+)_(.+?)\.(orig\.tar\.gz|diff\.gz|tar\.gz|dsc)");
29
30 re_begin_pgp_signature = re.compile("^-----BEGIN PGP SIGNATURE");
31 re_begin_pgp_signed_msg = re.compile("^-----BEGIN PGP SIGNED MESSAGE");
32 re_single_line_field = re.compile(r"^(\S*)\s*:\s*(.*)");
33 re_multi_line_description = re.compile(r"^ \.$");
34 re_multi_line_field = re.compile(r"^\s(.*)");
35
36 re_parse_maintainer = re.compile(r"^\s*(\S.*\S)\s*\<([^\> \t]+)\>");
37
38 changes_parse_error_exc = "Can't parse line in .changes file";
39 invalid_dsc_format_exc = "Invalid .dsc file";
40 nk_format_exc = "Unknown Format: in .changes file";
41 no_files_exc = "No Files: field in .dsc file.";
42 cant_open_exc = "Can't read file.";
43 unknown_hostname_exc = "Unknown hostname";
44 cant_overwrite_exc = "Permission denied; can't overwrite existent file."
45 file_exists_exc = "Destination file exists";
46 send_mail_invalid_args_exc = "Both arguments are non-null.";
47 sendmail_failed_exc = "Sendmail invocation failed";
48
49 # Valid components; used by extract_component_from_section() because
50 # it doesn't know about Conf from it's caller.  FIXME
51
52 valid_components = {
53     "main": "",
54     "contrib": "",
55     "non-free": ""
56     };
57
58 ######################################################################################
59
60 def open_file(filename, mode):
61     try:
62         f = open(filename, mode);
63     except IOError:
64         raise cant_open_exc, filename
65     return f
66
67 ######################################################################################
68
69 # From reportbug
70 def our_raw_input():
71     sys.stdout.flush()
72     try:
73         ret = raw_input()
74         return ret
75     except EOFError:
76         sys.stderr.write('\nUser interrupt (^D).\n')
77         raise SystemExit
78
79 ######################################################################################
80
81 def str_isnum (s):
82     for c in s:
83         if c not in string.digits:
84             return 0;
85     return 1;
86
87 ######################################################################################
88
89 # Prefix and components hardcoded into this like a good'un; need to unhardcod at some
90 # stage. [FIXME]
91
92 def extract_component_from_section(section):
93     component = "";
94     
95     if string.find(section, '/') != -1: 
96         component = string.split(section, '/')[0];
97     if string.lower(component) == "non-us" and string.count(section, '/') > 0:
98         s = string.split(section, '/')[1];
99         if valid_components.has_key(s): # Avoid e.g. non-US/libs
100             component = string.split(section, '/')[0]+ '/' + string.split(section, '/')[1];
101
102     if string.lower(section) == "non-us":
103         component = "non-US/main";
104
105     # non-US prefix is case insensitive
106     if string.lower(component)[:6] == "non-us":
107         component = "non-US"+component[6:];
108
109     # Expand default component
110     if component == "":
111         if valid_components.has_key(section):
112             component = section;
113         else:
114             component = "main";
115     elif component == "non-US":
116         component = "non-US/main";
117
118     return (section, component);
119
120 ######################################################################################
121
122 # dsc_whitespace_rules turns on strict format checking to avoid
123 # allowing in source packages which are unextracable by the
124 # inappropriately fragile dpkg-source.
125 #
126 # The rules are:
127 #
128 #
129 # o The PGP header consists of "-----BEGIN PGP SIGNED MESSAGE-----"
130 #   followed by any PGP header data and must end with a blank line.
131 #
132 # o The data section must end with a blank line and must be followed by
133 #   "-----BEGIN PGP SIGNATURE-----".
134
135 def parse_changes(filename, dsc_whitespace_rules):
136     changes_in = open_file(filename,'r');
137     error = "";
138     changes = {};
139     lines = changes_in.readlines();
140
141     if lines == []:
142         raise changes_parse_error_exc, "[Empty changes file]";
143
144     # Reindex by line number so we can easily verify the format of
145     # .dsc files...
146     index = 0;
147     indexed_lines = {};
148     for line in lines:
149         index = index + 1;
150         indexed_lines[index] = line[:-1];
151
152     inside_signature = 0;
153
154     indices = indexed_lines.keys()
155     index = 0;
156     while index < max(indices):
157         index = index + 1;
158         line = indexed_lines[index];
159         if line == "":
160             if dsc_whitespace_rules:
161                 index = index + 1;
162                 if index > max(indices):
163                     raise invalid_dsc_format_exc, index;
164                 line = indexed_lines[index];
165                 if not re_begin_pgp_signature.match(line):
166                     raise invalid_dsc_format_exc, index;
167                 inside_signature = 0;
168                 break;
169         if re_begin_pgp_signature.match(line):
170             break;
171         if re_begin_pgp_signed_msg.match(line):
172             if dsc_whitespace_rules:
173                 inside_signature = 1;
174                 while index < max(indices) and line != "":
175                     index = index + 1;
176                     line = indexed_lines[index];
177             continue;
178         slf = re_single_line_field.match(line);
179         if slf:
180             field = string.lower(slf.groups()[0]);
181             changes[field] = slf.groups()[1];
182             first = 1;
183             continue;
184         mld = re_multi_line_description.match(line);
185         if mld:
186             changes[field] = changes[field] + '\n';
187             continue;
188         mlf = re_multi_line_field.match(line);
189         if mlf:
190             if first == 1 and changes[field] != "":
191                 changes[field] = changes[field] + '\n';
192             first = 0;
193             changes[field] = changes[field] + mlf.groups()[0] + '\n';
194             continue;
195         error = error + line;
196
197     if dsc_whitespace_rules and inside_signature:
198         raise invalid_dsc_format_exc, index;
199         
200     changes_in.close();
201     changes["filecontents"] = string.join (lines, "");
202
203     if error != "":
204         raise changes_parse_error_exc, error;
205
206     return changes;
207
208 ######################################################################################
209
210 # Dropped support for 1.4 and ``buggy dchanges 3.4'' (?!) compared to di.pl
211
212 def build_file_list(changes, dsc):
213     files = {}
214     format = changes.get("format", "")
215     if format != "":
216         format = float(format)
217     if dsc == "" and (format < 1.5 or format > 2.0):
218         raise nk_format_exc, changes["format"];
219
220     # No really, this has happened.  Think 0 length .dsc file.
221     if not changes.has_key("files"):
222         raise no_files_exc
223     
224     for i in string.split(changes["files"], "\n"):
225         if i == "":
226             break
227         s = string.split(i)
228         section = priority = "";
229         try:
230             if dsc != "":
231                 (md5, size, name) = s
232             else:
233                 (md5, size, section, priority, name) = s
234         except ValueError:
235             raise changes_parse_error_exc, i
236
237         if section == "": section = "-"
238         if priority == "": priority = "-"
239
240         (section, component) = extract_component_from_section(section);
241         
242         files[name] = { "md5sum" : md5,
243                         "size" : size,
244                         "section": section,
245                         "priority": priority,
246                         "component": component }
247
248     return files
249
250 ######################################################################################
251
252 # Fix the `Maintainer:' field to be an RFC822 compatible address.
253 # cf. Packaging Manual (4.2.4)
254 #
255 # 06:28|<Culus> 'The standard sucks, but my tool is supposed to
256 #                interoperate with it. I know - I'll fix the suckage
257 #                and make things incompatible!'
258         
259 def fix_maintainer (maintainer):
260     m = re_parse_maintainer.match(maintainer);
261     rfc822 = maintainer
262     name = ""
263     email = ""
264     if m != None and len(m.groups()) == 2:
265         name = m.group(1)
266         email = m.group(2)
267         if string.find(name, ',') != -1 or string.find(name, '.') != -1:
268             rfc822 = re_parse_maintainer.sub(r"\2 (\1)", maintainer)
269     return (rfc822, name, email)
270
271 ######################################################################################
272
273 # sendmail wrapper, takes _either_ a message string or a file as arguments
274 def send_mail (message, filename):
275         #### FIXME, how do I get this out of Cnf in katie?
276         sendmail_command = "/usr/sbin/sendmail -odq -oi -t";
277
278         # Sanity check arguments
279         if message != "" and filename != "":
280             raise send_mail_invalid_args_exc;
281
282         # If we've been passed a string dump it into a temporary file
283         if message != "":
284             filename = tempfile.mktemp();
285             fd = os.open(filename, os.O_RDWR|os.O_CREAT|os.O_EXCL, 0700);
286             os.write (fd, message);
287             os.close (fd);
288
289         # Invoke sendmail
290         (result, output) = commands.getstatusoutput("%s < %s" % (sendmail_command, filename));
291         if (result != 0):
292             raise sendmail_failed_exc, output;
293
294         # Clean up any temporary files
295         if message !="":
296             os.unlink (filename);
297
298 ######################################################################################
299
300 def poolify (source, component):
301     if component != "":
302         component = component + '/';
303     # FIXME: this is nasty
304     component = string.lower(component);
305     component = string.replace(component, 'non-us/', 'non-US/');
306     if source[:3] == "lib":
307         return component + source[:4] + '/' + source + '/'
308     else:
309         return component + source[:1] + '/' + source + '/'
310
311 ######################################################################################
312
313 def move (src, dest, overwrite = 0):
314     if os.path.exists(dest) and os.path.isdir(dest):
315         dest_dir = dest;
316     else:
317         dest_dir = os.path.dirname(dest);
318     if not os.path.exists(dest_dir):
319         umask = os.umask(00000);
320         os.makedirs(dest_dir, 02775);
321         os.umask(umask);
322     #print "Moving %s to %s..." % (src, dest);
323     if os.path.exists(dest) and os.path.isdir(dest):
324         dest = dest + '/' + os.path.basename(src);
325     # Don't overwrite unless forced to
326     if os.path.exists(dest):
327         if not overwrite:
328             raise file_exists_exc;
329         else:
330             if not os.access(dest, os.W_OK):
331                 raise cant_overwrite_exc
332     shutil.copy2(src, dest);
333     os.chmod(dest, 0664);
334     os.unlink(src);
335
336 def copy (src, dest, overwrite = 0):
337     if os.path.exists(dest) and os.path.isdir(dest):
338         dest_dir = dest;
339     else:
340         dest_dir = os.path.dirname(dest);
341     if not os.path.exists(dest_dir):
342         umask = os.umask(00000);
343         os.makedirs(dest_dir, 02775);
344         os.umask(umask);
345     #print "Copying %s to %s..." % (src, dest);
346     if os.path.exists(dest) and os.path.isdir(dest):
347         dest = dest + '/' + os.path.basename(src);
348     # Don't overwrite unless forced to
349     if os.path.exists(dest):
350         if not overwrite:
351             raise file_exists_exc
352         else:
353             if not os.access(dest, os.W_OK):
354                 raise cant_overwrite_exc
355     shutil.copy2(src, dest);
356     os.chmod(dest, 0664);
357
358 ######################################################################################
359
360 # FIXME: this is inherently nasty.  Can't put this mapping in a conf
361 # file because the conf file depends on the archive.. doh.  Maybe an
362 # archive independent conf file is needed.
363
364 def where_am_i ():
365     res = socket.gethostbyaddr(socket.gethostname());
366     if res[0] == 'pandora.debian.org':
367         return 'non-US';
368     elif res[0] == 'auric.debian.org':
369         return 'ftp-master';
370     else:
371         raise unknown_hostname_exc, res;
372
373 ######################################################################################
374
375 # FIXME: this isn't great either.
376
377 def which_conf_file ():
378     archive = where_am_i ();
379     if archive == 'non-US':
380         return '/org/non-us.debian.org/katie/katie.conf-non-US';
381     elif archive == 'ftp-master':
382         return '/org/ftp.debian.org/katie/katie.conf';
383     else:
384         raise unknown_hostname_exc, archive
385
386 # FIXME: if the above isn't great, this can't be either :)
387
388 def which_apt_conf_file ():
389     archive = where_am_i ();
390     if archive == 'non-US':
391         return '/org/non-us.debian.org/katie/apt.conf-non-US';
392     elif archive == 'ftp-master':
393         return '/org/ftp.debian.org/katie/apt.conf';
394     else:
395         raise unknown_hostname_exc, archive
396
397 ######################################################################################
398
399 # Escape characters which have meaning to SQL's regex comparison operator ('~')
400 # (woefully incomplete)
401
402 def regex_safe (s):
403     s = string.replace(s, '+', '\\\\+');
404     s = string.replace(s, '.', '\\\\.');
405     return s
406
407 ######################################################################################
408
409 # Perform a substition of template 
410 def TemplateSubst(Map,Template):
411     for x in Map.keys():
412         Template = string.replace(Template,x,Map[x]);
413     return Template;
414
415 ######################################################################################
416
417 def fubar(msg, exit_code=1):
418     sys.stderr.write("E: %s\n" % (msg));
419     sys.exit(exit_code);
420
421 def warn(msg):
422     sys.stderr.write("W: %s\n" % (msg));
423
424 ######################################################################################
425
426 # Returns the user name with a laughable attempt at rfc822 conformancy
427 # (read: removing stray periods).
428 def whoami ():
429     return string.replace(string.split(pwd.getpwuid(os.getuid())[4],',')[0], '.', '');
430
431 ######################################################################################
432
433 def size_type (c):
434     t  = " b";
435     if c > 10000:
436         c = c / 1000;
437         t = " Kb";
438     if c > 10000:
439         c = c / 1000;
440         t = " Mb";
441     return ("%d%s" % (c, t))
442
443 ################################################################################
444
445 def cc_fix_changes (changes):
446     o = changes.get("architecture", "")
447     if o != "":
448         del changes["architecture"]
449     changes["architecture"] = {}
450     for j in string.split(o):
451         changes["architecture"][j] = 1
452
453 # Sort by 'have source', by source name, by source version number, by filename
454
455 def changes_compare (a, b):
456     try:
457         a_changes = parse_changes(a, 0)
458     except changes_parse_error_exc, line:
459         return -1;
460
461     try:
462         b_changes = parse_changes(b, 0)
463     except changes_parse_error_exc, line:
464         return 1;
465     
466     cc_fix_changes (a_changes);
467     cc_fix_changes (b_changes);
468
469     # Sort by 'have source'
470
471     a_has_source = a_changes["architecture"].get("source")
472     b_has_source = b_changes["architecture"].get("source")
473     if a_has_source and not b_has_source:
474         return -1;
475     elif b_has_source and not a_has_source:
476         return 1;
477
478     # Sort by source name
479     
480     a_source = a_changes.get("source");
481     b_source = b_changes.get("source");
482     q = cmp (a_source, b_source);
483     if q:
484         return q;
485
486     # Sort by source version
487
488     a_version = a_changes.get("version");
489     b_version = b_changes.get("version");
490     q = apt_pkg.VersionCompare(a_version, b_version);
491     if q:
492         return q
493
494     # Fall back to sort by filename
495
496     return cmp(a, b);
497
498 ################################################################################