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