2 # Copyright (C) 2000, 2001, 2002 James Troup <james@nocrew.org>
3 # $Id: utils.py,v 1.50 2002-07-14 15:01: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 ################################################################################
21 import commands, os, pwd, re, socket, shutil, string, sys, tempfile;
25 ################################################################################
27 re_comments = re.compile(r"\#.*")
28 re_no_epoch = re.compile(r"^\d*\:")
29 re_no_revision = re.compile(r"\-[^-]*$")
30 re_arch_from_filename = re.compile(r"/binary-[^/]+/")
31 re_extract_src_version = re.compile (r"(\S+)\s*\((.*)\)")
32 re_isadeb = re.compile (r"(.+?)_(.+?)_(.+)\.u?deb$");
33 re_issource = re.compile (r"(.+)_(.+?)\.(orig\.tar\.gz|diff\.gz|tar\.gz|dsc)$");
35 re_single_line_field = re.compile(r"^(\S*)\s*:\s*(.*)");
36 re_multi_line_field = re.compile(r"^\s(.*)");
37 re_taint_free = re.compile(r"^[-+~\.\w]+$");
39 re_parse_maintainer = re.compile(r"^\s*(\S.*\S)\s*\<([^\> \t]+)\>");
41 changes_parse_error_exc = "Can't parse line in .changes file";
42 invalid_dsc_format_exc = "Invalid .dsc file";
43 nk_format_exc = "Unknown Format: in .changes file";
44 no_files_exc = "No Files: field in .dsc file.";
45 cant_open_exc = "Can't read file.";
46 unknown_hostname_exc = "Unknown hostname";
47 cant_overwrite_exc = "Permission denied; can't overwrite existent file."
48 file_exists_exc = "Destination file exists";
49 send_mail_invalid_args_exc = "Both arguments are non-null.";
50 sendmail_failed_exc = "Sendmail invocation failed";
51 tried_too_hard_exc = "Tried too hard to find a free filename.";
53 default_config = "/etc/katie/katie.conf";
54 default_apt_config = "/etc/katie/apt.conf";
56 ######################################################################################
58 def open_file(filename, mode='r'):
60 f = open(filename, mode);
62 raise cant_open_exc, filename
65 ######################################################################################
67 def our_raw_input(prompt=""):
69 sys.stdout.write(prompt);
75 sys.stderr.write('\nUser interrupt (^D).\n');
78 ######################################################################################
82 if c not in string.digits:
86 ######################################################################################
88 def extract_component_from_section(section):
91 if string.find(section, '/') != -1:
92 component = string.split(section, '/')[0];
93 if string.lower(component) == "non-us" and string.count(section, '/') > 0:
94 s = component + '/' + string.split(section, '/')[1];
95 if Cnf.has_key("Component::%s" % s): # Avoid e.g. non-US/libs
98 if string.lower(section) == "non-us":
99 component = "non-US/main";
101 # non-US prefix is case insensitive
102 if string.lower(component)[:6] == "non-us":
103 component = "non-US"+component[6:];
105 # Expand default component
107 if Cnf.has_key("Component::%s" % section):
111 elif component == "non-US":
112 component = "non-US/main";
114 return (section, component);
116 ######################################################################################
118 # dsc_whitespace_rules turns on strict format checking to avoid
119 # allowing in source packages which are unextracable by the
120 # inappropriately fragile dpkg-source.
125 # o The PGP header consists of "-----BEGIN PGP SIGNED MESSAGE-----"
126 # followed by any PGP header data and must end with a blank line.
128 # o The data section must end with a blank line and must be followed by
129 # "-----BEGIN PGP SIGNATURE-----".
131 def parse_changes(filename, dsc_whitespace_rules=0):
132 changes_in = open_file(filename);
135 lines = changes_in.readlines();
138 raise changes_parse_error_exc, "[Empty changes file]";
140 # Reindex by line number so we can easily verify the format of
146 indexed_lines[index] = line[:-1];
148 inside_signature = 0;
150 indices = indexed_lines.keys()
153 while index < max(indices):
155 line = indexed_lines[index];
157 if dsc_whitespace_rules:
159 if index > max(indices):
160 raise invalid_dsc_format_exc, index;
161 line = indexed_lines[index];
162 if string.find(line, "-----BEGIN PGP SIGNATURE") != 0:
163 raise invalid_dsc_format_exc, index;
164 inside_signature = 0;
166 if string.find(line, "-----BEGIN PGP SIGNATURE") == 0:
168 if string.find(line, "-----BEGIN PGP SIGNED MESSAGE") == 0:
169 if dsc_whitespace_rules:
170 inside_signature = 1;
171 while index < max(indices) and line != "":
173 line = indexed_lines[index];
175 slf = re_single_line_field.match(line);
177 field = string.lower(slf.groups()[0]);
178 changes[field] = slf.groups()[1];
182 changes[field] = changes[field] + '\n';
184 mlf = re_multi_line_field.match(line);
187 raise changes_parse_error_exc, "'%s'\n [Multi-line field continuing on from nothing?]" % (line);
188 if first == 1 and changes[field] != "":
189 changes[field] = changes[field] + '\n';
191 changes[field] = changes[field] + mlf.groups()[0] + '\n';
193 error = error + line;
195 if dsc_whitespace_rules and inside_signature:
196 raise invalid_dsc_format_exc, index;
199 changes["filecontents"] = string.join (lines, "");
202 raise changes_parse_error_exc, error;
206 ######################################################################################
208 # Dropped support for 1.4 and ``buggy dchanges 3.4'' (?!) compared to di.pl
210 def build_file_list(changes, is_a_dsc=0):
212 format = changes.get("format", "")
214 format = float(format)
215 if not is_a_dsc and (format < 1.5 or format > 2.0):
216 raise nk_format_exc, format;
218 # No really, this has happened. Think 0 length .dsc file.
219 if not changes.has_key("files"):
222 for i in string.split(changes["files"], "\n"):
226 section = priority = "";
229 (md5, size, name) = s
231 (md5, size, section, priority, name) = s
233 raise changes_parse_error_exc, i
235 if section == "": section = "-"
236 if priority == "": priority = "-"
238 (section, component) = extract_component_from_section(section);
240 files[name] = { "md5sum" : md5,
243 "priority": priority,
244 "component": component }
248 ######################################################################################
250 # Fix the `Maintainer:' field to be an RFC822 compatible address.
251 # cf. Packaging Manual (4.2.4)
253 # 06:28|<Culus> 'The standard sucks, but my tool is supposed to
254 # interoperate with it. I know - I'll fix the suckage
255 # and make things incompatible!'
257 def fix_maintainer (maintainer):
258 m = re_parse_maintainer.match(maintainer);
262 if m != None and len(m.groups()) == 2:
265 if string.find(name, ',') != -1 or string.find(name, '.') != -1:
266 rfc822 = re_parse_maintainer.sub(r"\2 (\1)", maintainer)
267 return (rfc822, name, email)
269 ######################################################################################
271 # sendmail wrapper, takes _either_ a message string or a file as arguments
272 def send_mail (message, filename):
273 # Sanity check arguments
274 if message != "" and filename != "":
275 raise send_mail_invalid_args_exc;
277 # If we've been passed a string dump it into a temporary file
279 filename = tempfile.mktemp();
280 fd = os.open(filename, os.O_RDWR|os.O_CREAT|os.O_EXCL, 0700);
281 os.write (fd, message);
285 (result, output) = commands.getstatusoutput("%s < %s" % (Cnf["Dinstall::SendmailCommand"], filename));
287 raise sendmail_failed_exc, output;
289 # Clean up any temporary files
291 os.unlink (filename);
293 ######################################################################################
295 def poolify (source, component):
297 component = component + '/';
298 # FIXME: this is nasty
299 component = string.lower(component);
300 component = string.replace(component, 'non-us/', 'non-US/');
301 if source[:3] == "lib":
302 return component + source[:4] + '/' + source + '/'
304 return component + source[:1] + '/' + source + '/'
306 ######################################################################################
308 def move (src, dest, overwrite = 0, perms = 0664):
309 if os.path.exists(dest) and os.path.isdir(dest):
312 dest_dir = os.path.dirname(dest);
313 if not os.path.exists(dest_dir):
314 umask = os.umask(00000);
315 os.makedirs(dest_dir, 02775);
317 #print "Moving %s to %s..." % (src, dest);
318 if os.path.exists(dest) and os.path.isdir(dest):
319 dest = dest + '/' + os.path.basename(src);
320 # Don't overwrite unless forced to
321 if os.path.exists(dest):
323 raise file_exists_exc;
325 if not os.access(dest, os.W_OK):
326 raise cant_overwrite_exc
327 shutil.copy2(src, dest);
328 os.chmod(dest, perms);
331 def copy (src, dest, overwrite = 0, perms = 0664):
332 if os.path.exists(dest) and os.path.isdir(dest):
335 dest_dir = os.path.dirname(dest);
336 if not os.path.exists(dest_dir):
337 umask = os.umask(00000);
338 os.makedirs(dest_dir, 02775);
340 #print "Copying %s to %s..." % (src, dest);
341 if os.path.exists(dest) and os.path.isdir(dest):
342 dest = dest + '/' + os.path.basename(src);
343 # Don't overwrite unless forced to
344 if os.path.exists(dest):
346 raise file_exists_exc
348 if not os.access(dest, os.W_OK):
349 raise cant_overwrite_exc
350 shutil.copy2(src, dest);
351 os.chmod(dest, perms);
353 ######################################################################################
356 res = socket.gethostbyaddr(socket.gethostname());
357 database_hostname = Cnf.get("Config::" + res[0] + "::DatabaseHostname");
358 if database_hostname:
359 return database_hostname;
363 def which_conf_file ():
364 res = socket.gethostbyaddr(socket.gethostname());
365 if Cnf.get("Config::" + res[0] + "::KatieConfig"):
366 return Cnf["Config::" + res[0] + "::KatieConfig"]
368 return default_config;
370 def which_apt_conf_file ():
371 res = socket.gethostbyaddr(socket.gethostname());
372 if Cnf.get("Config::" + res[0] + "::AptConfig"):
373 return Cnf["Config::" + res[0] + "::AptConfig"]
375 return default_apt_config;
377 ######################################################################################
379 # Escape characters which have meaning to SQL's regex comparison operator ('~')
380 # (woefully incomplete)
383 s = string.replace(s, '+', '\\\\+');
384 s = string.replace(s, '.', '\\\\.');
387 ######################################################################################
389 # Perform a substition of template
390 def TemplateSubst(map, filename):
391 file = open_file(filename);
392 template = file.read();
394 template = string.replace(template,x,map[x]);
398 ######################################################################################
400 def fubar(msg, exit_code=1):
401 sys.stderr.write("E: %s\n" % (msg));
405 sys.stderr.write("W: %s\n" % (msg));
407 ######################################################################################
409 # Returns the user name with a laughable attempt at rfc822 conformancy
410 # (read: removing stray periods).
412 return string.replace(string.split(pwd.getpwuid(os.getuid())[4],',')[0], '.', '');
414 ######################################################################################
424 return ("%d%s" % (c, t))
426 ################################################################################
428 def cc_fix_changes (changes):
429 o = changes.get("architecture", "")
431 del changes["architecture"]
432 changes["architecture"] = {}
433 for j in string.split(o):
434 changes["architecture"][j] = 1
436 # Sort by source name, source version, 'have source', and then by filename
437 def changes_compare (a, b):
439 a_changes = parse_changes(a);
444 b_changes = parse_changes(b);
448 cc_fix_changes (a_changes);
449 cc_fix_changes (b_changes);
451 # Sort by source name
452 a_source = a_changes.get("source");
453 b_source = b_changes.get("source");
454 q = cmp (a_source, b_source);
458 # Sort by source version
459 a_version = a_changes.get("version");
460 b_version = b_changes.get("version");
461 q = apt_pkg.VersionCompare(a_version, b_version);
465 # Sort by 'have source'
466 a_has_source = a_changes["architecture"].get("source");
467 b_has_source = b_changes["architecture"].get("source");
468 if a_has_source and not b_has_source:
470 elif b_has_source and not a_has_source:
473 # Fall back to sort by filename
476 ################################################################################
478 def find_next_free (dest, too_many=100):
481 while os.path.exists(dest) and extra < too_many:
482 dest = orig_dest + '.' + repr(extra);
484 if extra >= too_many:
485 raise tried_too_hard_exc;
488 ################################################################################
490 def result_join (original, sep = '\t'):
492 for i in xrange(len(original)):
493 if original[i] == None:
496 list.append(original[i]);
497 return string.join(list, sep);
499 ################################################################################
501 def prefix_multi_line_string(str, prefix):
503 for line in string.split(str, '\n'):
504 line = string.strip(line);
506 out = out + "%s%s\n" % (prefix, line);
507 # Strip trailing new line
512 ################################################################################
514 def validate_changes_file_arg(file, fatal=1):
518 if file[-6:] == ".katie":
519 file = file[:-6]+".changes";
521 if file[-8:] != ".changes":
522 error = "invalid file type; not a changes file";
524 if not os.access(file,os.R_OK):
525 if os.path.exists(file):
526 error = "permission denied";
528 error = "file not found";
532 fubar("%s: %s." % (orig_filename, error));
534 warn("Skipping %s - %s" % (orig_filename, error));
539 ################################################################################
542 return (arch != "source" and arch != "all");
544 ################################################################################
546 def join_with_commas_and(list):
547 if len(list) == 0: return "nothing";
548 if len(list) == 1: return list[0];
549 return string.join(list[:-1], ", ") + " and " + list[-1];
551 ################################################################################
556 ################################################################################
558 # Handle -a, -c and -s arguments; returns them as SQL constraints
559 def parse_args(Options):
563 for suite in string.split(Options["Suite"]):
564 suite_id = db_access.get_suite_id(suite);
566 utils.warn("suite '%s' not recognised." % (suite));
568 suite_ids_list.append(suite_id);
570 con_suites = "AND su.id IN (%s)" % string.join(map(str, suite_ids_list), ", ");
572 fubar("No valid suite given.");
577 if Options["Component"]:
578 component_ids_list = [];
579 for component in string.split(Options["Component"]):
580 component_id = db_access.get_component_id(component);
581 if component_id == -1:
582 warn("component '%s' not recognised." % (component));
584 component_ids_list.append(component_id);
585 if component_ids_list:
586 con_components = "AND c.id IN (%s)" % string.join(map(str, component_ids_list), ", ");
588 fubar("No valid component given.");
592 # Process architecture
593 con_architectures = "";
594 if Options["Architecture"]:
597 for architecture in string.split(Options["Architecture"]):
598 if architecture == "source":
601 architecture_id = db_access.get_architecture_id(architecture);
602 if architecture_id == -1:
603 warn("architecture '%s' not recognised." % (architecture));
605 arch_ids_list.append(architecture_id);
607 con_architectures = "AND a.id IN (%s)" % string.join(map(str, arch_ids_list), ", ");
610 fubar("No valid architecture given.");
614 return (con_suites, con_architectures, con_components, check_source);
616 ################################################################################
620 Cnf = apt_pkg.newConfiguration();
621 apt_pkg.ReadConfigFileISC(Cnf,default_config);
623 if which_conf_file() != default_config:
624 apt_pkg.ReadConfigFileISC(Cnf,which_conf_file())
626 ################################################################################