2 # Copyright (C) 2000 James Troup <james@nocrew.org>
3 # $Id: utils.py,v 1.13 2001-01-28 09:06:44 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*\((.*)\)")
27 changes_parse_error_exc = "Can't parse line in .changes file";
28 invalid_dsc_format_exc = "Invalid .dsc file";
29 nk_format_exc = "Unknown Format: in .changes file";
30 no_files_exc = "No Files: field in .dsc file.";
31 cant_open_exc = "Can't read file.";
32 unknown_hostname_exc = "Unknown hostname";
33 cant_overwrite_exc = "Permission denied; can't overwrite existent file."
35 ######################################################################################
37 def open_file(filename, mode):
39 f = open(filename, mode);
41 raise cant_open_exc, filename
44 ######################################################################################
53 sys.stderr.write('\nUser interrupt (^D).\n')
56 ######################################################################################
59 def extract_component_from_section(section):
62 if string.find(section, '/') != -1:
63 component = string.split(section, '/')[0];
64 if string.lower(component) == "non-us" and string.count(section, '/') > 0:
65 s = string.split(section, '/')[1];
66 if s == "main" or s == "non-free" or s == "contrib": # Avoid e.g. non-US/libs
67 component = string.split(section, '/')[0]+ '/' + string.split(section, '/')[1];
69 if string.lower(section) == "non-us":
70 component = "non-US/main";
74 elif string.lower(component) == "non-us":
75 component = "non-US/main";
77 return (section, component);
79 ######################################################################################
81 # dsc_whitespace_rules turns on strict format checking to avoid
82 # allowing in source packages which are unextracable by the
83 # inappropriately fragile dpkg-source.
88 # o The PGP header consists of "-----BEGIN PGP SIGNED MESSAGE-----"
89 # followed by any PGP header data and must end with a blank line.
91 # o The data section must end with a blank line and must be followed by
92 # "-----BEGIN PGP SIGNATURE-----".
94 def parse_changes(filename, dsc_whitespace_rules):
95 changes_in = open_file(filename,'r');
98 lines = changes_in.readlines();
100 # Reindex by line number so we can easily verify the format of
106 indexed_lines[index] = line[:-1];
108 inside_signature = 0;
110 indices = indexed_lines.keys()
112 while index < max(indices):
114 line = indexed_lines[index];
116 if dsc_whitespace_rules:
118 if index > max(indices):
119 raise invalid_dsc_format_exc, index;
120 line = indexed_lines[index];
121 if not re.match('^-----BEGIN PGP SIGNATURE', line):
122 raise invalid_dsc_format_exc, index;
123 inside_signature = 0;
125 if re.match('^-----BEGIN PGP SIGNATURE', line):
127 if re.match(r'^-----BEGIN PGP SIGNED MESSAGE', line):
128 if dsc_whitespace_rules:
129 inside_signature = 1;
130 while index < max(indices) and line != "":
132 line = indexed_lines[index];
134 slf = re.match(r'^(\S*)\s*:\s*(.*)', line);
136 field = string.lower(slf.groups()[0]);
137 changes[field] = slf.groups()[1];
139 mld = re.match(r'^ \.$', line);
141 changes[field] = changes[field] + '\n';
143 mlf = re.match(r'^\s(.*)', line);
145 changes[field] = changes[field] + mlf.groups()[0] + '\n';
147 error = error + line;
149 if dsc_whitespace_rules and inside_signature:
150 raise invalid_dsc_format_exc, index;
153 changes["filecontents"] = string.join (lines, "");
156 raise changes_parse_error_exc, error;
160 ######################################################################################
162 # Dropped support for 1.4 and ``buggy dchanges 3.4'' (?!) compared to di.pl
164 def build_file_list(changes, dsc):
166 format = changes.get("format", "")
168 format = float(format)
169 if dsc == "" and (format < 1.5 or format > 2.0):
170 raise nk_format_exc, changes["format"];
172 # No really, this has happened. Think 0 length .dsc file.
173 if not changes.has_key("files"):
176 for i in string.split(changes["files"], "\n"):
180 section = priority = "";
183 (md5, size, name) = s
185 (md5, size, section, priority, name) = s
187 raise changes_parse_error_exc, i
189 if section == "": section = "-"
190 if priority == "": priority = "-"
192 (section, component) = extract_component_from_section(section);
194 files[name] = { "md5sum" : md5,
197 "priority": priority,
198 "component": component }
202 ######################################################################################
204 # Fix the `Maintainer:' field to be an RFC822 compatible address.
205 # cf. Packaging Manual (4.2.4)
207 # 06:28|<Culus> 'The standard sucks, but my tool is supposed to
208 # interoperate with it. I know - I'll fix the suckage
209 # and make things incompatible!'
211 def fix_maintainer (maintainer):
212 m = re.match(r"^\s*(\S.*\S)\s*\<([^\> \t]+)\>", maintainer)
216 if m != None and len(m.groups()) == 2:
219 if re.search(r'[,.]', name) != None:
220 rfc822 = re.sub(r"^\s*(\S.*\S)\s*\<([^\> \t]+)\>", r"\2 (\1)", maintainer)
221 return (rfc822, name, email)
223 ######################################################################################
225 # sendmail wrapper, takes _either_ a message string or a file as arguments
226 def send_mail (message, filename):
227 #### FIXME, how do I get this out of Cnf in katie?
228 sendmail_command = "/usr/sbin/sendmail -odq -oi -t";
230 # Sanity check arguments
231 if message != "" and filename != "":
232 sys.stderr.write ("send_mail() can't be called with both arguments as non-null! (`%s' and `%s')\n%s" % (message, filename))
234 # If we've been passed a string dump it into a temporary file
236 filename = tempfile.mktemp()
237 fd = os.open(filename, os.O_RDWR|os.O_CREAT|os.O_EXCL, 0700)
238 os.write (fd, message)
241 (result, output) = commands.getstatusoutput("%s < %s" % (sendmail_command, filename))
243 sys.stderr.write ("Sendmail invocation (`%s') failed for `%s'!\n%s" % (sendmail_command, filename, output))
245 # Clean up any temporary files
249 ######################################################################################
251 def poolify (source, component):
253 component = component + '/';
254 # FIXME: this is nasty
255 component = string.lower(component);
256 component = string.replace(component, 'non-us/', 'non-US/');
257 if source[:3] == "lib":
258 return component + source[:4] + '/' + source + '/'
260 return component + source[:1] + '/' + source + '/'
262 ######################################################################################
264 def move (src, dest):
265 if os.path.exists(dest) and os.path.isdir(dest):
268 dest_dir = os.path.dirname(dest);
269 if not os.path.exists(dest_dir):
270 umask = os.umask(00000);
271 os.makedirs(dest_dir, 02775);
273 #print "Moving %s to %s..." % (src, dest);
274 if os.path.exists(dest) and os.path.isdir(dest):
275 dest = dest + '/' + os.path.basename(src);
276 # Check for overwrite permission on existent files
277 if os.path.exists(dest) and not os.access(dest, os.W_OK):
278 raise cant_overwrite_exc
279 shutil.copy2(src, dest);
280 os.chmod(dest, 0664);
283 def copy (src, dest):
284 if os.path.exists(dest) and os.path.isdir(dest):
287 dest_dir = os.path.dirname(dest);
288 if not os.path.exists(dest_dir):
289 umask = os.umask(00000);
290 os.makedirs(dest_dir, 02775);
292 #print "Copying %s to %s..." % (src, dest);
293 if os.path.exists(dest) and os.path.isdir(dest):
294 dest = dest + '/' + os.path.basename(src);
295 if os.path.exists(dest) and not os.access(dest, os.W_OK):
296 raise cant_overwrite_exc
297 shutil.copy2(src, dest);
298 os.chmod(dest, 0664);
300 ######################################################################################
302 # FIXME: this is inherently nasty. Can't put this mapping in a conf
303 # file because the conf file depends on the archive.. doh. Maybe an
304 # archive independent conf file is needed.
307 res = socket.gethostbyaddr(socket.gethostname());
308 if res[0] == 'pandora.debian.org':
310 elif res[0] == 'auric.debian.org':
313 raise unknown_hostname_exc, res;
315 ######################################################################################
317 # FIXME: this isn't great either.
319 def which_conf_file ():
320 archive = where_am_i ();
321 if archive == 'non-US':
322 return '/org/non-us.debian.org/katie/katie.conf-non-US';
323 elif archive == 'ftp-master':
324 return '/org/ftp.debian.org/katie/katie.conf';
326 raise unknown_hostname_exc, archive
328 ######################################################################################
330 # Escape characters which have meaning to SQL's regex comparison operator ('~')
331 # (woefully incomplete)
334 s = string.replace(s, '+', '\\\\+');
337 ######################################################################################
347 return ("%d%s" % (c, t))