2 # Copyright (C) 2000, 2001 James Troup <james@nocrew.org>
3 # $Id: utils.py,v 1.32 2001-09-17 11:18:37 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_single_line_field = re.compile(r"^(\S*)\s*:\s*(.*)");
31 re_multi_line_field = re.compile(r"^\s(.*)");
33 re_parse_maintainer = re.compile(r"^\s*(\S.*\S)\s*\<([^\> \t]+)\>");
35 changes_parse_error_exc = "Can't parse line in .changes file";
36 invalid_dsc_format_exc = "Invalid .dsc file";
37 nk_format_exc = "Unknown Format: in .changes file";
38 no_files_exc = "No Files: field in .dsc file.";
39 cant_open_exc = "Can't read file.";
40 unknown_hostname_exc = "Unknown hostname";
41 cant_overwrite_exc = "Permission denied; can't overwrite existent file."
42 file_exists_exc = "Destination file exists";
43 send_mail_invalid_args_exc = "Both arguments are non-null.";
44 sendmail_failed_exc = "Sendmail invocation failed";
45 tried_too_hard_exc = "Tried too hard to find a free filename.";
47 # Valid components; used by extract_component_from_section() because
48 # it doesn't know about Conf from it's caller. FIXME
56 ######################################################################################
58 def open_file(filename, mode='r'):
60 f = open(filename, mode);
62 raise cant_open_exc, filename
65 ######################################################################################
74 sys.stderr.write('\nUser interrupt (^D).\n')
77 ######################################################################################
81 if c not in string.digits:
85 ######################################################################################
87 # Prefix and components hardcoded into this like a good'un; need to unhardcod at some
90 def extract_component_from_section(section):
93 if string.find(section, '/') != -1:
94 component = string.split(section, '/')[0];
95 if string.lower(component) == "non-us" and string.count(section, '/') > 0:
96 s = string.split(section, '/')[1];
97 if valid_components.has_key(s): # Avoid e.g. non-US/libs
98 component = string.split(section, '/')[0]+ '/' + string.split(section, '/')[1];
100 if string.lower(section) == "non-us":
101 component = "non-US/main";
103 # non-US prefix is case insensitive
104 if string.lower(component)[:6] == "non-us":
105 component = "non-US"+component[6:];
107 # Expand default component
109 if valid_components.has_key(section):
113 elif component == "non-US":
114 component = "non-US/main";
116 return (section, component);
118 ######################################################################################
120 # dsc_whitespace_rules turns on strict format checking to avoid
121 # allowing in source packages which are unextracable by the
122 # inappropriately fragile dpkg-source.
127 # o The PGP header consists of "-----BEGIN PGP SIGNED MESSAGE-----"
128 # followed by any PGP header data and must end with a blank line.
130 # o The data section must end with a blank line and must be followed by
131 # "-----BEGIN PGP SIGNATURE-----".
133 def parse_changes(filename, dsc_whitespace_rules):
134 changes_in = open_file(filename,'r');
137 lines = changes_in.readlines();
140 raise changes_parse_error_exc, "[Empty changes file]";
142 # Reindex by line number so we can easily verify the format of
148 indexed_lines[index] = line[:-1];
150 inside_signature = 0;
152 indices = indexed_lines.keys()
154 while index < max(indices):
156 line = indexed_lines[index];
158 if dsc_whitespace_rules:
160 if index > max(indices):
161 raise invalid_dsc_format_exc, index;
162 line = indexed_lines[index];
163 if line[:24] != "-----BEGIN PGP SIGNATURE":
164 raise invalid_dsc_format_exc, index;
165 inside_signature = 0;
167 if line[:24] == "-----BEGIN PGP SIGNATURE":
169 if line[:29] == "-----BEGIN PGP SIGNED MESSAGE":
170 if dsc_whitespace_rules:
171 inside_signature = 1;
172 while index < max(indices) and line != "":
174 line = indexed_lines[index];
176 slf = re_single_line_field.match(line);
178 field = string.lower(slf.groups()[0]);
179 changes[field] = slf.groups()[1];
183 changes[field] = changes[field] + '\n';
185 mlf = re_multi_line_field.match(line);
187 if first == 1 and changes[field] != "":
188 changes[field] = changes[field] + '\n';
190 changes[field] = changes[field] + mlf.groups()[0] + '\n';
192 error = error + line;
194 if dsc_whitespace_rules and inside_signature:
195 raise invalid_dsc_format_exc, index;
198 changes["filecontents"] = string.join (lines, "");
201 raise changes_parse_error_exc, error;
205 ######################################################################################
207 # Dropped support for 1.4 and ``buggy dchanges 3.4'' (?!) compared to di.pl
209 def build_file_list(changes, dsc):
211 format = changes.get("format", "")
213 format = float(format)
214 if dsc == "" and (format < 1.5 or format > 2.0):
215 raise nk_format_exc, format;
217 # No really, this has happened. Think 0 length .dsc file.
218 if not changes.has_key("files"):
221 for i in string.split(changes["files"], "\n"):
225 section = priority = "";
228 (md5, size, name) = s
230 (md5, size, section, priority, name) = s
232 raise changes_parse_error_exc, i
234 if section == "": section = "-"
235 if priority == "": priority = "-"
237 (section, component) = extract_component_from_section(section);
239 files[name] = { "md5sum" : md5,
242 "priority": priority,
243 "component": component }
247 ######################################################################################
249 # Fix the `Maintainer:' field to be an RFC822 compatible address.
250 # cf. Packaging Manual (4.2.4)
252 # 06:28|<Culus> 'The standard sucks, but my tool is supposed to
253 # interoperate with it. I know - I'll fix the suckage
254 # and make things incompatible!'
256 def fix_maintainer (maintainer):
257 m = re_parse_maintainer.match(maintainer);
261 if m != None and len(m.groups()) == 2:
264 if string.find(name, ',') != -1 or string.find(name, '.') != -1:
265 rfc822 = re_parse_maintainer.sub(r"\2 (\1)", maintainer)
266 return (rfc822, name, email)
268 ######################################################################################
270 # sendmail wrapper, takes _either_ a message string or a file as arguments
271 def send_mail (message, filename):
272 #### FIXME, how do I get this out of Cnf in katie?
273 sendmail_command = "/usr/sbin/sendmail -odq -oi -t";
275 # Sanity check arguments
276 if message != "" and filename != "":
277 raise send_mail_invalid_args_exc;
279 # If we've been passed a string dump it into a temporary file
281 filename = tempfile.mktemp();
282 fd = os.open(filename, os.O_RDWR|os.O_CREAT|os.O_EXCL, 0700);
283 os.write (fd, message);
287 (result, output) = commands.getstatusoutput("%s < %s" % (sendmail_command, filename));
289 raise sendmail_failed_exc, output;
291 # Clean up any temporary files
293 os.unlink (filename);
295 ######################################################################################
297 def poolify (source, component):
299 component = component + '/';
300 # FIXME: this is nasty
301 component = string.lower(component);
302 component = string.replace(component, 'non-us/', 'non-US/');
303 if source[:3] == "lib":
304 return component + source[:4] + '/' + source + '/'
306 return component + source[:1] + '/' + source + '/'
308 ######################################################################################
310 def move (src, dest, overwrite = 0):
311 if os.path.exists(dest) and os.path.isdir(dest):
314 dest_dir = os.path.dirname(dest);
315 if not os.path.exists(dest_dir):
316 umask = os.umask(00000);
317 os.makedirs(dest_dir, 02775);
319 #print "Moving %s to %s..." % (src, dest);
320 if os.path.exists(dest) and os.path.isdir(dest):
321 dest = dest + '/' + os.path.basename(src);
322 # Don't overwrite unless forced to
323 if os.path.exists(dest):
325 raise file_exists_exc;
327 if not os.access(dest, os.W_OK):
328 raise cant_overwrite_exc
329 shutil.copy2(src, dest);
330 os.chmod(dest, 0664);
333 def copy (src, dest, overwrite = 0):
334 if os.path.exists(dest) and os.path.isdir(dest):
337 dest_dir = os.path.dirname(dest);
338 if not os.path.exists(dest_dir):
339 umask = os.umask(00000);
340 os.makedirs(dest_dir, 02775);
342 #print "Copying %s to %s..." % (src, dest);
343 if os.path.exists(dest) and os.path.isdir(dest):
344 dest = dest + '/' + os.path.basename(src);
345 # Don't overwrite unless forced to
346 if os.path.exists(dest):
348 raise file_exists_exc
350 if not os.access(dest, os.W_OK):
351 raise cant_overwrite_exc
352 shutil.copy2(src, dest);
353 os.chmod(dest, 0664);
355 ######################################################################################
357 # FIXME: this is inherently nasty. Can't put this mapping in a conf
358 # file because the conf file depends on the archive.. doh. Maybe an
359 # archive independent conf file is needed.
362 res = socket.gethostbyaddr(socket.gethostname());
363 if res[0] == 'pandora.debian.org':
365 elif res[0] == 'auric.debian.org':
368 raise unknown_hostname_exc, res;
370 ######################################################################################
372 # FIXME: this isn't great either.
374 def which_conf_file ():
375 archive = where_am_i ();
376 if archive == 'non-US':
377 return '/org/non-us.debian.org/katie/katie.conf-non-US';
378 elif archive == 'ftp-master':
379 return '/org/ftp.debian.org/katie/katie.conf';
381 raise unknown_hostname_exc, archive
383 # FIXME: if the above isn't great, this can't be either :)
385 def which_apt_conf_file ():
386 archive = where_am_i ();
387 if archive == 'non-US':
388 return '/org/non-us.debian.org/katie/apt.conf-non-US';
389 elif archive == 'ftp-master':
390 return '/org/ftp.debian.org/katie/apt.conf';
392 raise unknown_hostname_exc, archive
394 ######################################################################################
396 # Escape characters which have meaning to SQL's regex comparison operator ('~')
397 # (woefully incomplete)
400 s = string.replace(s, '+', '\\\\+');
401 s = string.replace(s, '.', '\\\\.');
404 ######################################################################################
406 # Perform a substition of template
407 def TemplateSubst(Map,Template):
409 Template = string.replace(Template,x,Map[x]);
412 ######################################################################################
414 def fubar(msg, exit_code=1):
415 sys.stderr.write("E: %s\n" % (msg));
419 sys.stderr.write("W: %s\n" % (msg));
421 ######################################################################################
423 # Returns the user name with a laughable attempt at rfc822 conformancy
424 # (read: removing stray periods).
426 return string.replace(string.split(pwd.getpwuid(os.getuid())[4],',')[0], '.', '');
428 ######################################################################################
438 return ("%d%s" % (c, t))
440 ################################################################################
442 def cc_fix_changes (changes):
443 o = changes.get("architecture", "")
445 del changes["architecture"]
446 changes["architecture"] = {}
447 for j in string.split(o):
448 changes["architecture"][j] = 1
450 # Sort by 'have source', by source name, by source version number, by filename
452 def changes_compare (a, b):
454 a_changes = parse_changes(a, 0)
459 b_changes = parse_changes(b, 0)
463 cc_fix_changes (a_changes);
464 cc_fix_changes (b_changes);
466 # Sort by 'have source'
468 a_has_source = a_changes["architecture"].get("source")
469 b_has_source = b_changes["architecture"].get("source")
470 if a_has_source and not b_has_source:
472 elif b_has_source and not a_has_source:
475 # Sort by source name
477 a_source = a_changes.get("source");
478 b_source = b_changes.get("source");
479 q = cmp (a_source, b_source);
483 # Sort by source version
485 a_version = a_changes.get("version");
486 b_version = b_changes.get("version");
487 q = apt_pkg.VersionCompare(a_version, b_version);
491 # Fall back to sort by filename
495 ################################################################################
497 def find_next_free (dest, too_many=100):
500 while os.path.exists(dest) and extra < too_many:
501 dest = orig_dest + '.' + repr(extra);
503 if extra >= too_many:
504 raise tried_too_hard_exc;
507 ################################################################################
509 def result_join (original, sep = '\t'):
511 for i in xrange(len(original)):
512 if original[i] == None:
515 list.append(original[i]);
516 return string.join(list, sep);
518 ################################################################################