2 # Copyright (C) 2000 James Troup <james@nocrew.org>
3 # $Id: utils.py,v 1.18 2001-03-21 01:02:04 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, re, socket, shutil, stat, string, sys, tempfile
21 re_comments = re.compile(r"\#.*")
22 re_no_epoch = re.compile(r"^\d*\:")
23 re_no_revision = re.compile(r"\-[^-]*$")
24 re_arch_from_filename = re.compile(r"/binary-[^/]+/")
25 re_extract_src_version = re.compile (r"(\S+)\s*\((.*)\)")
26 re_isadeb = re.compile (r'.*\.u?deb$');
27 re_issource = re.compile (r'(.+)_(.+?)\.(orig\.tar\.gz|diff\.gz|tar\.gz|dsc)');
29 changes_parse_error_exc = "Can't parse line in .changes file";
30 invalid_dsc_format_exc = "Invalid .dsc file";
31 nk_format_exc = "Unknown Format: in .changes file";
32 no_files_exc = "No Files: field in .dsc file.";
33 cant_open_exc = "Can't read file.";
34 unknown_hostname_exc = "Unknown hostname";
35 cant_overwrite_exc = "Permission denied; can't overwrite existent file."
37 ######################################################################################
39 def open_file(filename, mode):
41 f = open(filename, mode);
43 raise cant_open_exc, filename
46 ######################################################################################
55 sys.stderr.write('\nUser interrupt (^D).\n')
58 ######################################################################################
62 if c not in string.digits:
66 ######################################################################################
69 def extract_component_from_section(section):
72 if string.find(section, '/') != -1:
73 component = string.split(section, '/')[0];
74 if string.lower(component) == "non-us" and string.count(section, '/') > 0:
75 s = string.split(section, '/')[1];
76 if s == "main" or s == "non-free" or s == "contrib": # Avoid e.g. non-US/libs
77 component = string.split(section, '/')[0]+ '/' + string.split(section, '/')[1];
79 if string.lower(section) == "non-us":
80 component = "non-US/main";
84 elif string.lower(component) == "non-us":
85 component = "non-US/main";
87 return (section, component);
89 ######################################################################################
91 # dsc_whitespace_rules turns on strict format checking to avoid
92 # allowing in source packages which are unextracable by the
93 # inappropriately fragile dpkg-source.
98 # o The PGP header consists of "-----BEGIN PGP SIGNED MESSAGE-----"
99 # followed by any PGP header data and must end with a blank line.
101 # o The data section must end with a blank line and must be followed by
102 # "-----BEGIN PGP SIGNATURE-----".
104 def parse_changes(filename, dsc_whitespace_rules):
105 changes_in = open_file(filename,'r');
108 lines = changes_in.readlines();
111 raise changes_parse_error_exc, "[Empty changes file]";
113 # Reindex by line number so we can easily verify the format of
119 indexed_lines[index] = line[:-1];
121 inside_signature = 0;
123 indices = indexed_lines.keys()
125 while index < max(indices):
127 line = indexed_lines[index];
129 if dsc_whitespace_rules:
131 if index > max(indices):
132 raise invalid_dsc_format_exc, index;
133 line = indexed_lines[index];
134 if not re.match('^-----BEGIN PGP SIGNATURE', line):
135 raise invalid_dsc_format_exc, index;
136 inside_signature = 0;
138 if re.match('^-----BEGIN PGP SIGNATURE', line):
140 if re.match(r'^-----BEGIN PGP SIGNED MESSAGE', line):
141 if dsc_whitespace_rules:
142 inside_signature = 1;
143 while index < max(indices) and line != "":
145 line = indexed_lines[index];
147 slf = re.match(r'^(\S*)\s*:\s*(.*)', line);
149 field = string.lower(slf.groups()[0]);
150 changes[field] = slf.groups()[1];
152 mld = re.match(r'^ \.$', line);
154 changes[field] = changes[field] + '\n';
156 mlf = re.match(r'^\s(.*)', line);
158 changes[field] = changes[field] + mlf.groups()[0] + '\n';
160 error = error + line;
162 if dsc_whitespace_rules and inside_signature:
163 raise invalid_dsc_format_exc, index;
166 changes["filecontents"] = string.join (lines, "");
169 raise changes_parse_error_exc, error;
173 ######################################################################################
175 # Dropped support for 1.4 and ``buggy dchanges 3.4'' (?!) compared to di.pl
177 def build_file_list(changes, dsc):
179 format = changes.get("format", "")
181 format = float(format)
182 if dsc == "" and (format < 1.5 or format > 2.0):
183 raise nk_format_exc, changes["format"];
185 # No really, this has happened. Think 0 length .dsc file.
186 if not changes.has_key("files"):
189 for i in string.split(changes["files"], "\n"):
193 section = priority = "";
196 (md5, size, name) = s
198 (md5, size, section, priority, name) = s
200 raise changes_parse_error_exc, i
202 if section == "": section = "-"
203 if priority == "": priority = "-"
205 (section, component) = extract_component_from_section(section);
207 files[name] = { "md5sum" : md5,
210 "priority": priority,
211 "component": component }
215 ######################################################################################
217 # Fix the `Maintainer:' field to be an RFC822 compatible address.
218 # cf. Packaging Manual (4.2.4)
220 # 06:28|<Culus> 'The standard sucks, but my tool is supposed to
221 # interoperate with it. I know - I'll fix the suckage
222 # and make things incompatible!'
224 def fix_maintainer (maintainer):
225 m = re.match(r"^\s*(\S.*\S)\s*\<([^\> \t]+)\>", maintainer)
229 if m != None and len(m.groups()) == 2:
232 if re.search(r'[,.]', name) != None:
233 rfc822 = re.sub(r"^\s*(\S.*\S)\s*\<([^\> \t]+)\>", r"\2 (\1)", maintainer)
234 return (rfc822, name, email)
236 ######################################################################################
238 # sendmail wrapper, takes _either_ a message string or a file as arguments
239 def send_mail (message, filename):
240 #### FIXME, how do I get this out of Cnf in katie?
241 sendmail_command = "/usr/sbin/sendmail -odq -oi -t";
243 # Sanity check arguments
244 if message != "" and filename != "":
245 sys.stderr.write ("send_mail() can't be called with both arguments as non-null! (`%s' and `%s')\n%s" % (message, filename))
247 # If we've been passed a string dump it into a temporary file
249 filename = tempfile.mktemp()
250 fd = os.open(filename, os.O_RDWR|os.O_CREAT|os.O_EXCL, 0700)
251 os.write (fd, message)
254 (result, output) = commands.getstatusoutput("%s < %s" % (sendmail_command, filename))
256 sys.stderr.write ("Sendmail invocation (`%s') failed for `%s'!\n%s" % (sendmail_command, filename, output))
258 # Clean up any temporary files
262 ######################################################################################
264 def poolify (source, component):
266 component = component + '/';
267 # FIXME: this is nasty
268 component = string.lower(component);
269 component = string.replace(component, 'non-us/', 'non-US/');
270 if source[:3] == "lib":
271 return component + source[:4] + '/' + source + '/'
273 return component + source[:1] + '/' + source + '/'
275 ######################################################################################
277 def move (src, dest):
278 if os.path.exists(dest) and os.path.isdir(dest):
281 dest_dir = os.path.dirname(dest);
282 if not os.path.exists(dest_dir):
283 umask = os.umask(00000);
284 os.makedirs(dest_dir, 02775);
286 #print "Moving %s to %s..." % (src, dest);
287 if os.path.exists(dest) and os.path.isdir(dest):
288 dest = dest + '/' + os.path.basename(src);
289 # Check for overwrite permission on existent files
290 if os.path.exists(dest) and not os.access(dest, os.W_OK):
291 raise cant_overwrite_exc
292 shutil.copy2(src, dest);
293 os.chmod(dest, 0664);
296 def copy (src, dest):
297 if os.path.exists(dest) and os.path.isdir(dest):
300 dest_dir = os.path.dirname(dest);
301 if not os.path.exists(dest_dir):
302 umask = os.umask(00000);
303 os.makedirs(dest_dir, 02775);
305 #print "Copying %s to %s..." % (src, dest);
306 if os.path.exists(dest) and os.path.isdir(dest):
307 dest = dest + '/' + os.path.basename(src);
308 if os.path.exists(dest) and not os.access(dest, os.W_OK):
309 raise cant_overwrite_exc
310 shutil.copy2(src, dest);
311 os.chmod(dest, 0664);
313 ######################################################################################
315 # FIXME: this is inherently nasty. Can't put this mapping in a conf
316 # file because the conf file depends on the archive.. doh. Maybe an
317 # archive independent conf file is needed.
320 res = socket.gethostbyaddr(socket.gethostname());
321 if res[0] == 'pandora.debian.org':
323 elif res[0] == 'auric.debian.org':
326 raise unknown_hostname_exc, res;
328 ######################################################################################
330 # FIXME: this isn't great either.
332 def which_conf_file ():
333 archive = where_am_i ();
334 if archive == 'non-US':
335 return '/org/non-us.debian.org/katie/katie.conf-non-US';
336 elif archive == 'ftp-master':
337 return '/org/ftp.debian.org/katie/katie.conf';
339 raise unknown_hostname_exc, archive
341 # FIXME: if the above isn't great, this can't be either :)
343 def which_apt_conf_file ():
344 archive = where_am_i ();
345 if archive == 'non-US':
346 return '/org/non-us.debian.org/katie/apt.conf-non-US';
347 elif archive == 'ftp-master':
348 return '/org/ftp.debian.org/katie/apt.conf';
350 raise unknown_hostname_exc, archive
352 ######################################################################################
354 # Escape characters which have meaning to SQL's regex comparison operator ('~')
355 # (woefully incomplete)
358 s = string.replace(s, '+', '\\\\+');
361 ######################################################################################
363 # Perform a substition of template
364 def TemplateSubst(Map,Template):
366 Template = string.replace(Template,x,Map[x]);
369 ######################################################################################
379 return ("%d%s" % (c, t))