2 # Copyright (C) 2000, 2001 James Troup <james@nocrew.org>
3 # $Id: utils.py,v 1.30 2001-07-25 15:51:15 troup Exp $
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.
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.
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
19 import commands, os, pwd, re, socket, shutil, stat, string, sys, tempfile
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)");
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(.*)");
36 re_parse_maintainer = re.compile(r"^\s*(\S.*\S)\s*\<([^\> \t]+)\>");
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.";
50 # Valid components; used by extract_component_from_section() because
51 # it doesn't know about Conf from it's caller. FIXME
59 ######################################################################################
61 def open_file(filename, mode='r'):
63 f = open(filename, mode);
65 raise cant_open_exc, filename
68 ######################################################################################
77 sys.stderr.write('\nUser interrupt (^D).\n')
80 ######################################################################################
84 if c not in string.digits:
88 ######################################################################################
90 # Prefix and components hardcoded into this like a good'un; need to unhardcod at some
93 def extract_component_from_section(section):
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];
103 if string.lower(section) == "non-us":
104 component = "non-US/main";
106 # non-US prefix is case insensitive
107 if string.lower(component)[:6] == "non-us":
108 component = "non-US"+component[6:];
110 # Expand default component
112 if valid_components.has_key(section):
116 elif component == "non-US":
117 component = "non-US/main";
119 return (section, component);
121 ######################################################################################
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.
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.
133 # o The data section must end with a blank line and must be followed by
134 # "-----BEGIN PGP SIGNATURE-----".
136 def parse_changes(filename, dsc_whitespace_rules):
137 changes_in = open_file(filename,'r');
140 lines = changes_in.readlines();
143 raise changes_parse_error_exc, "[Empty changes file]";
145 # Reindex by line number so we can easily verify the format of
151 indexed_lines[index] = line[:-1];
153 inside_signature = 0;
155 indices = indexed_lines.keys()
157 while index < max(indices):
159 line = indexed_lines[index];
161 if dsc_whitespace_rules:
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;
170 if re_begin_pgp_signature.match(line):
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 != "":
177 line = indexed_lines[index];
179 slf = re_single_line_field.match(line);
181 field = string.lower(slf.groups()[0]);
182 changes[field] = slf.groups()[1];
185 mld = re_multi_line_description.match(line);
187 changes[field] = changes[field] + '\n';
189 mlf = re_multi_line_field.match(line);
191 if first == 1 and changes[field] != "":
192 changes[field] = changes[field] + '\n';
194 changes[field] = changes[field] + mlf.groups()[0] + '\n';
196 error = error + line;
198 if dsc_whitespace_rules and inside_signature:
199 raise invalid_dsc_format_exc, index;
202 changes["filecontents"] = string.join (lines, "");
205 raise changes_parse_error_exc, error;
209 ######################################################################################
211 # Dropped support for 1.4 and ``buggy dchanges 3.4'' (?!) compared to di.pl
213 def build_file_list(changes, dsc):
215 format = changes.get("format", "")
217 format = float(format)
218 if dsc == "" and (format < 1.5 or format > 2.0):
219 raise nk_format_exc, format;
221 # No really, this has happened. Think 0 length .dsc file.
222 if not changes.has_key("files"):
225 for i in string.split(changes["files"], "\n"):
229 section = priority = "";
232 (md5, size, name) = s
234 (md5, size, section, priority, name) = s
236 raise changes_parse_error_exc, i
238 if section == "": section = "-"
239 if priority == "": priority = "-"
241 (section, component) = extract_component_from_section(section);
243 files[name] = { "md5sum" : md5,
246 "priority": priority,
247 "component": component }
251 ######################################################################################
253 # Fix the `Maintainer:' field to be an RFC822 compatible address.
254 # cf. Packaging Manual (4.2.4)
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!'
260 def fix_maintainer (maintainer):
261 m = re_parse_maintainer.match(maintainer);
265 if m != None and len(m.groups()) == 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)
272 ######################################################################################
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";
279 # Sanity check arguments
280 if message != "" and filename != "":
281 raise send_mail_invalid_args_exc;
283 # If we've been passed a string dump it into a temporary file
285 filename = tempfile.mktemp();
286 fd = os.open(filename, os.O_RDWR|os.O_CREAT|os.O_EXCL, 0700);
287 os.write (fd, message);
291 (result, output) = commands.getstatusoutput("%s < %s" % (sendmail_command, filename));
293 raise sendmail_failed_exc, output;
295 # Clean up any temporary files
297 os.unlink (filename);
299 ######################################################################################
301 def poolify (source, 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 + '/'
310 return component + source[:1] + '/' + source + '/'
312 ######################################################################################
314 def move (src, dest, overwrite = 0):
315 if os.path.exists(dest) and os.path.isdir(dest):
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);
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):
329 raise file_exists_exc;
331 if not os.access(dest, os.W_OK):
332 raise cant_overwrite_exc
333 shutil.copy2(src, dest);
334 os.chmod(dest, 0664);
337 def copy (src, dest, overwrite = 0):
338 if os.path.exists(dest) and os.path.isdir(dest):
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);
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):
352 raise file_exists_exc
354 if not os.access(dest, os.W_OK):
355 raise cant_overwrite_exc
356 shutil.copy2(src, dest);
357 os.chmod(dest, 0664);
359 ######################################################################################
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.
366 res = socket.gethostbyaddr(socket.gethostname());
367 if res[0] == 'pandora.debian.org':
369 elif res[0] == 'auric.debian.org':
372 raise unknown_hostname_exc, res;
374 ######################################################################################
376 # FIXME: this isn't great either.
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';
385 raise unknown_hostname_exc, archive
387 # FIXME: if the above isn't great, this can't be either :)
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';
396 raise unknown_hostname_exc, archive
398 ######################################################################################
400 # Escape characters which have meaning to SQL's regex comparison operator ('~')
401 # (woefully incomplete)
404 s = string.replace(s, '+', '\\\\+');
405 s = string.replace(s, '.', '\\\\.');
408 ######################################################################################
410 # Perform a substition of template
411 def TemplateSubst(Map,Template):
413 Template = string.replace(Template,x,Map[x]);
416 ######################################################################################
418 def fubar(msg, exit_code=1):
419 sys.stderr.write("E: %s\n" % (msg));
423 sys.stderr.write("W: %s\n" % (msg));
425 ######################################################################################
427 # Returns the user name with a laughable attempt at rfc822 conformancy
428 # (read: removing stray periods).
430 return string.replace(string.split(pwd.getpwuid(os.getuid())[4],',')[0], '.', '');
432 ######################################################################################
442 return ("%d%s" % (c, t))
444 ################################################################################
446 def cc_fix_changes (changes):
447 o = changes.get("architecture", "")
449 del changes["architecture"]
450 changes["architecture"] = {}
451 for j in string.split(o):
452 changes["architecture"][j] = 1
454 # Sort by 'have source', by source name, by source version number, by filename
456 def changes_compare (a, b):
458 a_changes = parse_changes(a, 0)
463 b_changes = parse_changes(b, 0)
467 cc_fix_changes (a_changes);
468 cc_fix_changes (b_changes);
470 # Sort by 'have source'
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:
476 elif b_has_source and not a_has_source:
479 # Sort by source name
481 a_source = a_changes.get("source");
482 b_source = b_changes.get("source");
483 q = cmp (a_source, b_source);
487 # Sort by source version
489 a_version = a_changes.get("version");
490 b_version = b_changes.get("version");
491 q = apt_pkg.VersionCompare(a_version, b_version);
495 # Fall back to sort by filename
499 ################################################################################
501 def find_next_free (dest, too_many=100):
504 while os.path.exists(dest) and extra < too_many:
505 dest = orig_dest + '.' + repr(extra);
507 if extra >= too_many:
508 raise tried_too_hard_exc;
511 ################################################################################