2 # Copyright (C) 2000, 2001 James Troup <james@nocrew.org>
3 # $Id: utils.py,v 1.36 2001-11-18 19:57:58 rmurray 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(.*)");
32 re_taint_free = re.compile(r"^[-+\.\w]+$");
34 re_parse_maintainer = re.compile(r"^\s*(\S.*\S)\s*\<([^\> \t]+)\>");
36 changes_parse_error_exc = "Can't parse line in .changes file";
37 invalid_dsc_format_exc = "Invalid .dsc file";
38 nk_format_exc = "Unknown Format: in .changes file";
39 no_files_exc = "No Files: field in .dsc file.";
40 cant_open_exc = "Can't read file.";
41 unknown_hostname_exc = "Unknown hostname";
42 cant_overwrite_exc = "Permission denied; can't overwrite existent file."
43 file_exists_exc = "Destination file exists";
44 send_mail_invalid_args_exc = "Both arguments are non-null.";
45 sendmail_failed_exc = "Sendmail invocation failed";
46 tried_too_hard_exc = "Tried too hard to find a free filename.";
48 default_config = "/etc/katie/katie.conf";
49 default_apt_config = "/etc/katie/apt.conf";
51 ######################################################################################
53 def open_file(filename, mode='r'):
55 f = open(filename, mode);
57 raise cant_open_exc, filename
60 def touch_file(filename):
61 fd = os.open(filename, os.O_RDONLY | os.O_CREAT);
64 ######################################################################################
73 sys.stderr.write('\nUser interrupt (^D).\n')
76 ######################################################################################
80 if c not in string.digits:
84 ######################################################################################
86 def extract_component_from_section(section):
89 if string.find(section, '/') != -1:
90 component = string.split(section, '/')[0];
91 if string.lower(component) == "non-us" and string.count(section, '/') > 0:
92 s = string.split(section, '/')[1];
93 if Cnf.has_key("Component::%s" % s): # Avoid e.g. non-US/libs
94 component = string.split(section, '/')[0]+ '/' + string.split(section, '/')[1];
96 if string.lower(section) == "non-us":
97 component = "non-US/main";
99 # non-US prefix is case insensitive
100 if string.lower(component)[:6] == "non-us":
101 component = "non-US"+component[6:];
103 # Expand default component
105 if Cnf.has_key("Component::%s" % section):
109 elif component == "non-US":
110 component = "non-US/main";
112 return (section, component);
114 ######################################################################################
116 # dsc_whitespace_rules turns on strict format checking to avoid
117 # allowing in source packages which are unextracable by the
118 # inappropriately fragile dpkg-source.
123 # o The PGP header consists of "-----BEGIN PGP SIGNED MESSAGE-----"
124 # followed by any PGP header data and must end with a blank line.
126 # o The data section must end with a blank line and must be followed by
127 # "-----BEGIN PGP SIGNATURE-----".
129 def parse_changes(filename, dsc_whitespace_rules):
130 changes_in = open_file(filename);
133 lines = changes_in.readlines();
136 raise changes_parse_error_exc, "[Empty changes file]";
138 # Reindex by line number so we can easily verify the format of
144 indexed_lines[index] = line[:-1];
146 inside_signature = 0;
148 indices = indexed_lines.keys()
150 while index < max(indices):
152 line = indexed_lines[index];
154 if dsc_whitespace_rules:
156 if index > max(indices):
157 raise invalid_dsc_format_exc, index;
158 line = indexed_lines[index];
159 if string.find(line, "-----BEGIN PGP SIGNATURE") != 0:
160 raise invalid_dsc_format_exc, index;
161 inside_signature = 0;
163 if string.find(line, "-----BEGIN PGP SIGNATURE") == 0:
165 if string.find(line, "-----BEGIN PGP SIGNED MESSAGE") == 0:
166 if dsc_whitespace_rules:
167 inside_signature = 1;
168 while index < max(indices) and line != "":
170 line = indexed_lines[index];
172 slf = re_single_line_field.match(line);
174 field = string.lower(slf.groups()[0]);
175 changes[field] = slf.groups()[1];
179 changes[field] = changes[field] + '\n';
181 mlf = re_multi_line_field.match(line);
183 if first == 1 and changes[field] != "":
184 changes[field] = changes[field] + '\n';
186 changes[field] = changes[field] + mlf.groups()[0] + '\n';
188 error = error + line;
190 if dsc_whitespace_rules and inside_signature:
191 raise invalid_dsc_format_exc, index;
194 changes["filecontents"] = string.join (lines, "");
197 raise changes_parse_error_exc, error;
201 ######################################################################################
203 # Dropped support for 1.4 and ``buggy dchanges 3.4'' (?!) compared to di.pl
205 def build_file_list(changes, dsc):
207 format = changes.get("format", "")
209 format = float(format)
210 if dsc == "" and (format < 1.5 or format > 2.0):
211 raise nk_format_exc, format;
213 # No really, this has happened. Think 0 length .dsc file.
214 if not changes.has_key("files"):
217 for i in string.split(changes["files"], "\n"):
221 section = priority = "";
224 (md5, size, name) = s
226 (md5, size, section, priority, name) = s
228 raise changes_parse_error_exc, i
230 if section == "": section = "-"
231 if priority == "": priority = "-"
233 (section, component) = extract_component_from_section(section);
235 files[name] = { "md5sum" : md5,
238 "priority": priority,
239 "component": component }
243 ######################################################################################
245 # Fix the `Maintainer:' field to be an RFC822 compatible address.
246 # cf. Packaging Manual (4.2.4)
248 # 06:28|<Culus> 'The standard sucks, but my tool is supposed to
249 # interoperate with it. I know - I'll fix the suckage
250 # and make things incompatible!'
252 def fix_maintainer (maintainer):
253 m = re_parse_maintainer.match(maintainer);
257 if m != None and len(m.groups()) == 2:
260 if string.find(name, ',') != -1 or string.find(name, '.') != -1:
261 rfc822 = re_parse_maintainer.sub(r"\2 (\1)", maintainer)
262 return (rfc822, name, email)
264 ######################################################################################
266 # sendmail wrapper, takes _either_ a message string or a file as arguments
267 def send_mail (message, filename):
268 # Sanity check arguments
269 if message != "" and filename != "":
270 raise send_mail_invalid_args_exc;
272 # If we've been passed a string dump it into a temporary file
274 filename = tempfile.mktemp();
275 fd = os.open(filename, os.O_RDWR|os.O_CREAT|os.O_EXCL, 0700);
276 os.write (fd, message);
280 (result, output) = commands.getstatusoutput("%s < %s" % (Cnf["Dinstall::SendmailCommand"], filename));
282 raise sendmail_failed_exc, output;
284 # Clean up any temporary files
286 os.unlink (filename);
288 ######################################################################################
290 def poolify (source, component):
292 component = component + '/';
293 # FIXME: this is nasty
294 component = string.lower(component);
295 component = string.replace(component, 'non-us/', 'non-US/');
296 if source[:3] == "lib":
297 return component + source[:4] + '/' + source + '/'
299 return component + source[:1] + '/' + source + '/'
301 ######################################################################################
303 def move (src, dest, overwrite = 0):
304 if os.path.exists(dest) and os.path.isdir(dest):
307 dest_dir = os.path.dirname(dest);
308 if not os.path.exists(dest_dir):
309 umask = os.umask(00000);
310 os.makedirs(dest_dir, 02775);
312 #print "Moving %s to %s..." % (src, dest);
313 if os.path.exists(dest) and os.path.isdir(dest):
314 dest = dest + '/' + os.path.basename(src);
315 # Don't overwrite unless forced to
316 if os.path.exists(dest):
318 raise file_exists_exc;
320 if not os.access(dest, os.W_OK):
321 raise cant_overwrite_exc
322 shutil.copy2(src, dest);
323 os.chmod(dest, 0664);
326 def copy (src, dest, overwrite = 0):
327 if os.path.exists(dest) and os.path.isdir(dest):
330 dest_dir = os.path.dirname(dest);
331 if not os.path.exists(dest_dir):
332 umask = os.umask(00000);
333 os.makedirs(dest_dir, 02775);
335 #print "Copying %s to %s..." % (src, dest);
336 if os.path.exists(dest) and os.path.isdir(dest):
337 dest = dest + '/' + os.path.basename(src);
338 # Don't overwrite unless forced to
339 if os.path.exists(dest):
341 raise file_exists_exc
343 if not os.access(dest, os.W_OK):
344 raise cant_overwrite_exc
345 shutil.copy2(src, dest);
346 os.chmod(dest, 0664);
348 ######################################################################################
351 res = socket.gethostbyaddr(socket.gethostname());
352 database_hostname = Cnf.get("Config::" + res[0] + "::DatabaseHostname");
353 if database_hostname:
354 return database_hostname;
358 def which_conf_file ():
359 res = socket.gethostbyaddr(socket.gethostname());
360 if Cnf.get("Config::" + res[0] + "::KatieConfig"):
361 return Cnf["Config::" + res[0] + "::KatieConfig"]
363 return default_config;
365 def which_apt_conf_file ():
366 res = socket.gethostbyaddr(socket.gethostname());
367 if Cnf.get("Config::" + res[0] + "::AptConfig"):
368 return Cnf["Config::" + res[0] + "::AptConfig"]
370 return default_apt_config;
372 ######################################################################################
374 # Escape characters which have meaning to SQL's regex comparison operator ('~')
375 # (woefully incomplete)
378 s = string.replace(s, '+', '\\\\+');
379 s = string.replace(s, '.', '\\\\.');
382 ######################################################################################
384 # Perform a substition of template
385 def TemplateSubst(Map,Template):
387 Template = string.replace(Template,x,Map[x]);
390 ######################################################################################
392 def fubar(msg, exit_code=1):
393 sys.stderr.write("E: %s\n" % (msg));
397 sys.stderr.write("W: %s\n" % (msg));
399 ######################################################################################
401 # Returns the user name with a laughable attempt at rfc822 conformancy
402 # (read: removing stray periods).
404 return string.replace(string.split(pwd.getpwuid(os.getuid())[4],',')[0], '.', '');
406 ######################################################################################
416 return ("%d%s" % (c, t))
418 ################################################################################
420 def cc_fix_changes (changes):
421 o = changes.get("architecture", "")
423 del changes["architecture"]
424 changes["architecture"] = {}
425 for j in string.split(o):
426 changes["architecture"][j] = 1
428 # Sort by 'have source', by source name, by source version number, by filename
430 def changes_compare (a, b):
432 a_changes = parse_changes(a, 0)
437 b_changes = parse_changes(b, 0)
441 cc_fix_changes (a_changes);
442 cc_fix_changes (b_changes);
444 # Sort by 'have source'
446 a_has_source = a_changes["architecture"].get("source")
447 b_has_source = b_changes["architecture"].get("source")
448 if a_has_source and not b_has_source:
450 elif b_has_source and not a_has_source:
453 # Sort by source name
455 a_source = a_changes.get("source");
456 b_source = b_changes.get("source");
457 q = cmp (a_source, b_source);
461 # Sort by source version
463 a_version = a_changes.get("version");
464 b_version = b_changes.get("version");
465 q = apt_pkg.VersionCompare(a_version, b_version);
469 # Fall back to sort by filename
473 ################################################################################
475 def find_next_free (dest, too_many=100):
478 while os.path.exists(dest) and extra < too_many:
479 dest = orig_dest + '.' + repr(extra);
481 if extra >= too_many:
482 raise tried_too_hard_exc;
485 ################################################################################
487 def result_join (original, sep = '\t'):
489 for i in xrange(len(original)):
490 if original[i] == None:
493 list.append(original[i]);
494 return string.join(list, sep);
496 ################################################################################
501 ################################################################################
505 Cnf = apt_pkg.newConfiguration();
506 apt_pkg.ReadConfigFileISC(Cnf,default_config);
508 if which_conf_file() != default_config:
509 apt_pkg.ReadConfigFileISC(Cnf,which_conf_file())
511 ################################################################################