2 # Copyright (C) 2000 James Troup <james@nocrew.org>
3 # $Id: utils.py,v 1.25 2001-06-01 00:17:45 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 ######################################################################################
51 def open_file(filename, mode):
53 f = open(filename, mode);
55 raise cant_open_exc, filename
58 ######################################################################################
67 sys.stderr.write('\nUser interrupt (^D).\n')
70 ######################################################################################
74 if c not in string.digits:
78 ######################################################################################
81 def extract_component_from_section(section):
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];
91 if string.lower(section) == "non-us":
92 component = "non-US/main";
96 elif string.lower(component) == "non-us":
97 component = "non-US/main";
99 return (section, component);
101 ######################################################################################
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.
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.
113 # o The data section must end with a blank line and must be followed by
114 # "-----BEGIN PGP SIGNATURE-----".
116 def parse_changes(filename, dsc_whitespace_rules):
117 changes_in = open_file(filename,'r');
120 lines = changes_in.readlines();
123 raise changes_parse_error_exc, "[Empty changes file]";
125 # Reindex by line number so we can easily verify the format of
131 indexed_lines[index] = line[:-1];
133 inside_signature = 0;
135 indices = indexed_lines.keys()
137 while index < max(indices):
139 line = indexed_lines[index];
141 if dsc_whitespace_rules:
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;
150 if re_begin_pgp_signature.match(line):
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 != "":
157 line = indexed_lines[index];
159 slf = re_single_line_field.match(line);
161 field = string.lower(slf.groups()[0]);
162 changes[field] = slf.groups()[1];
165 mld = re_multi_line_description.match(line);
167 changes[field] = changes[field] + '\n';
169 mlf = re_multi_line_field.match(line);
171 if first == 1 and changes[field] != "":
172 changes[field] = changes[field] + '\n';
174 changes[field] = changes[field] + mlf.groups()[0] + '\n';
176 error = error + line;
178 if dsc_whitespace_rules and inside_signature:
179 raise invalid_dsc_format_exc, index;
182 changes["filecontents"] = string.join (lines, "");
185 raise changes_parse_error_exc, error;
189 ######################################################################################
191 # Dropped support for 1.4 and ``buggy dchanges 3.4'' (?!) compared to di.pl
193 def build_file_list(changes, dsc):
195 format = changes.get("format", "")
197 format = float(format)
198 if dsc == "" and (format < 1.5 or format > 2.0):
199 raise nk_format_exc, changes["format"];
201 # No really, this has happened. Think 0 length .dsc file.
202 if not changes.has_key("files"):
205 for i in string.split(changes["files"], "\n"):
209 section = priority = "";
212 (md5, size, name) = s
214 (md5, size, section, priority, name) = s
216 raise changes_parse_error_exc, i
218 if section == "": section = "-"
219 if priority == "": priority = "-"
221 (section, component) = extract_component_from_section(section);
223 files[name] = { "md5sum" : md5,
226 "priority": priority,
227 "component": component }
231 ######################################################################################
233 # Fix the `Maintainer:' field to be an RFC822 compatible address.
234 # cf. Packaging Manual (4.2.4)
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!'
240 def fix_maintainer (maintainer):
241 m = re_parse_maintainer.match(maintainer);
245 if m != None and len(m.groups()) == 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)
252 ######################################################################################
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";
259 # Sanity check arguments
260 if message != "" and filename != "":
261 raise send_mail_invalid_args_exc;
263 # If we've been passed a string dump it into a temporary file
265 filename = tempfile.mktemp();
266 fd = os.open(filename, os.O_RDWR|os.O_CREAT|os.O_EXCL, 0700);
267 os.write (fd, message);
271 (result, output) = commands.getstatusoutput("%s < %s" % (sendmail_command, filename));
273 raise sendmail_failed_exc, output;
275 # Clean up any temporary files
277 os.unlink (filename);
279 ######################################################################################
281 def poolify (source, 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 + '/'
290 return component + source[:1] + '/' + source + '/'
292 ######################################################################################
294 def move (src, dest, overwrite = 0):
295 if os.path.exists(dest) and os.path.isdir(dest):
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);
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):
309 raise file_exists_exc;
311 if not os.access(dest, os.W_OK):
312 raise cant_overwrite_exc
313 shutil.copy2(src, dest);
314 os.chmod(dest, 0664);
317 def copy (src, dest, overwrite = 0):
318 if os.path.exists(dest) and os.path.isdir(dest):
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);
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):
332 raise file_exists_exc
334 if not os.access(dest, os.W_OK):
335 raise cant_overwrite_exc
336 shutil.copy2(src, dest);
337 os.chmod(dest, 0664);
339 ######################################################################################
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.
346 res = socket.gethostbyaddr(socket.gethostname());
347 if res[0] == 'pandora.debian.org':
349 elif res[0] == 'auric.debian.org':
352 raise unknown_hostname_exc, res;
354 ######################################################################################
356 # FIXME: this isn't great either.
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';
365 raise unknown_hostname_exc, archive
367 # FIXME: if the above isn't great, this can't be either :)
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';
376 raise unknown_hostname_exc, archive
378 ######################################################################################
380 # Escape characters which have meaning to SQL's regex comparison operator ('~')
381 # (woefully incomplete)
384 s = string.replace(s, '+', '\\\\+');
385 s = string.replace(s, '.', '\\\\.');
388 ######################################################################################
390 # Perform a substition of template
391 def TemplateSubst(Map,Template):
393 Template = string.replace(Template,x,Map[x]);
396 ######################################################################################
398 def fubar(msg, exit_code=1):
399 sys.stderr.write("E: %s\n" % (msg));
403 sys.stderr.write("W: %s\n" % (msg));
405 ######################################################################################
407 # Returns the user name with a laughable attempt at rfc822 conformancy
408 # (read: removing stray periods).
410 return string.replace(string.split(pwd.getpwuid(os.getuid())[4],',')[0], '.', '');
412 ######################################################################################
422 return ("%d%s" % (c, t))
424 ################################################################################
426 def cc_fix_changes (changes):
427 o = changes.get("architecture", "")
429 del changes["architecture"]
430 changes["architecture"] = {}
431 for j in string.split(o):
432 changes["architecture"][j] = 1
434 # Sort by 'have source', by source name, by source version number, by filename
436 def changes_compare (a, b):
438 a_changes = parse_changes(a, 0)
439 except changes_parse_error_exc, line:
443 b_changes = parse_changes(b, 0)
444 except changes_parse_error_exc, line:
447 cc_fix_changes (a_changes);
448 cc_fix_changes (b_changes);
450 # Sort by 'have source'
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:
456 elif b_has_source and not a_has_source:
459 # Sort by source name
461 a_source = a_changes.get("source");
462 b_source = b_changes.get("source");
463 q = cmp (a_source, b_source);
467 # Sort by source version
469 a_version = a_changes.get("version");
470 b_version = b_changes.get("version");
471 q = apt_pkg.VersionCompare(a_version, b_version);
475 # Fall back to sort by filename
479 ################################################################################