2 # Copyright (C) 2000 James Troup <james@nocrew.org>
3 # $Id: utils.py,v 1.26 2001-06-10 16:35:03 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";
49 # Valid components; used by extract_component_from_section() because
50 # it doesn't know about Conf from it's caller. FIXME
58 ######################################################################################
60 def open_file(filename, mode):
62 f = open(filename, mode);
64 raise cant_open_exc, filename
67 ######################################################################################
76 sys.stderr.write('\nUser interrupt (^D).\n')
79 ######################################################################################
83 if c not in string.digits:
87 ######################################################################################
89 # Prefix and components hardcoded into this like a good'un; need to unhardcod at some
92 def extract_component_from_section(section):
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];
102 if string.lower(section) == "non-us":
103 component = "non-US/main";
105 # non-US prefix is case insensitive
106 if string.lower(component)[:6] == "non-us":
107 component = "non-US"+component[6:];
109 # Expand default component
111 if valid_components.has_key(section):
115 elif component == "non-US":
116 component = "non-US/main";
118 return (section, component);
120 ######################################################################################
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.
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.
132 # o The data section must end with a blank line and must be followed by
133 # "-----BEGIN PGP SIGNATURE-----".
135 def parse_changes(filename, dsc_whitespace_rules):
136 changes_in = open_file(filename,'r');
139 lines = changes_in.readlines();
142 raise changes_parse_error_exc, "[Empty changes file]";
144 # Reindex by line number so we can easily verify the format of
150 indexed_lines[index] = line[:-1];
152 inside_signature = 0;
154 indices = indexed_lines.keys()
156 while index < max(indices):
158 line = indexed_lines[index];
160 if dsc_whitespace_rules:
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;
169 if re_begin_pgp_signature.match(line):
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 != "":
176 line = indexed_lines[index];
178 slf = re_single_line_field.match(line);
180 field = string.lower(slf.groups()[0]);
181 changes[field] = slf.groups()[1];
184 mld = re_multi_line_description.match(line);
186 changes[field] = changes[field] + '\n';
188 mlf = re_multi_line_field.match(line);
190 if first == 1 and changes[field] != "":
191 changes[field] = changes[field] + '\n';
193 changes[field] = changes[field] + mlf.groups()[0] + '\n';
195 error = error + line;
197 if dsc_whitespace_rules and inside_signature:
198 raise invalid_dsc_format_exc, index;
201 changes["filecontents"] = string.join (lines, "");
204 raise changes_parse_error_exc, error;
208 ######################################################################################
210 # Dropped support for 1.4 and ``buggy dchanges 3.4'' (?!) compared to di.pl
212 def build_file_list(changes, dsc):
214 format = changes.get("format", "")
216 format = float(format)
217 if dsc == "" and (format < 1.5 or format > 2.0):
218 raise nk_format_exc, changes["format"];
220 # No really, this has happened. Think 0 length .dsc file.
221 if not changes.has_key("files"):
224 for i in string.split(changes["files"], "\n"):
228 section = priority = "";
231 (md5, size, name) = s
233 (md5, size, section, priority, name) = s
235 raise changes_parse_error_exc, i
237 if section == "": section = "-"
238 if priority == "": priority = "-"
240 (section, component) = extract_component_from_section(section);
242 files[name] = { "md5sum" : md5,
245 "priority": priority,
246 "component": component }
250 ######################################################################################
252 # Fix the `Maintainer:' field to be an RFC822 compatible address.
253 # cf. Packaging Manual (4.2.4)
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!'
259 def fix_maintainer (maintainer):
260 m = re_parse_maintainer.match(maintainer);
264 if m != None and len(m.groups()) == 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)
271 ######################################################################################
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";
278 # Sanity check arguments
279 if message != "" and filename != "":
280 raise send_mail_invalid_args_exc;
282 # If we've been passed a string dump it into a temporary file
284 filename = tempfile.mktemp();
285 fd = os.open(filename, os.O_RDWR|os.O_CREAT|os.O_EXCL, 0700);
286 os.write (fd, message);
290 (result, output) = commands.getstatusoutput("%s < %s" % (sendmail_command, filename));
292 raise sendmail_failed_exc, output;
294 # Clean up any temporary files
296 os.unlink (filename);
298 ######################################################################################
300 def poolify (source, 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 + '/'
309 return component + source[:1] + '/' + source + '/'
311 ######################################################################################
313 def move (src, dest, overwrite = 0):
314 if os.path.exists(dest) and os.path.isdir(dest):
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);
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):
328 raise file_exists_exc;
330 if not os.access(dest, os.W_OK):
331 raise cant_overwrite_exc
332 shutil.copy2(src, dest);
333 os.chmod(dest, 0664);
336 def copy (src, dest, overwrite = 0):
337 if os.path.exists(dest) and os.path.isdir(dest):
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);
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):
351 raise file_exists_exc
353 if not os.access(dest, os.W_OK):
354 raise cant_overwrite_exc
355 shutil.copy2(src, dest);
356 os.chmod(dest, 0664);
358 ######################################################################################
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.
365 res = socket.gethostbyaddr(socket.gethostname());
366 if res[0] == 'pandora.debian.org':
368 elif res[0] == 'auric.debian.org':
371 raise unknown_hostname_exc, res;
373 ######################################################################################
375 # FIXME: this isn't great either.
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';
384 raise unknown_hostname_exc, archive
386 # FIXME: if the above isn't great, this can't be either :)
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';
395 raise unknown_hostname_exc, archive
397 ######################################################################################
399 # Escape characters which have meaning to SQL's regex comparison operator ('~')
400 # (woefully incomplete)
403 s = string.replace(s, '+', '\\\\+');
404 s = string.replace(s, '.', '\\\\.');
407 ######################################################################################
409 # Perform a substition of template
410 def TemplateSubst(Map,Template):
412 Template = string.replace(Template,x,Map[x]);
415 ######################################################################################
417 def fubar(msg, exit_code=1):
418 sys.stderr.write("E: %s\n" % (msg));
422 sys.stderr.write("W: %s\n" % (msg));
424 ######################################################################################
426 # Returns the user name with a laughable attempt at rfc822 conformancy
427 # (read: removing stray periods).
429 return string.replace(string.split(pwd.getpwuid(os.getuid())[4],',')[0], '.', '');
431 ######################################################################################
441 return ("%d%s" % (c, t))
443 ################################################################################
445 def cc_fix_changes (changes):
446 o = changes.get("architecture", "")
448 del changes["architecture"]
449 changes["architecture"] = {}
450 for j in string.split(o):
451 changes["architecture"][j] = 1
453 # Sort by 'have source', by source name, by source version number, by filename
455 def changes_compare (a, b):
457 a_changes = parse_changes(a, 0)
458 except changes_parse_error_exc, line:
462 b_changes = parse_changes(b, 0)
463 except changes_parse_error_exc, line:
466 cc_fix_changes (a_changes);
467 cc_fix_changes (b_changes);
469 # Sort by 'have source'
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:
475 elif b_has_source and not a_has_source:
478 # Sort by source name
480 a_source = a_changes.get("source");
481 b_source = b_changes.get("source");
482 q = cmp (a_source, b_source);
486 # Sort by source version
488 a_version = a_changes.get("version");
489 b_version = b_changes.get("version");
490 q = apt_pkg.VersionCompare(a_version, b_version);
494 # Fall back to sort by filename
498 ################################################################################