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