]> git.decadent.org.uk Git - dak.git/blob - utils.py
Add parse_args and join_with_commas_and
[dak.git] / utils.py
1 # Utility functions
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 $
4
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.
9
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.
14
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
18
19 ################################################################################
20
21 import commands, os, pwd, re, socket, shutil, string, sys, tempfile;
22 import apt_pkg;
23 import db_access;
24
25 ################################################################################
26
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)$");
34
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]+$");
38
39 re_parse_maintainer = re.compile(r"^\s*(\S.*\S)\s*\<([^\> \t]+)\>");
40
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.";
52
53 default_config = "/etc/katie/katie.conf";
54 default_apt_config = "/etc/katie/apt.conf";
55
56 ######################################################################################
57
58 def open_file(filename, mode='r'):
59     try:
60         f = open(filename, mode);
61     except IOError:
62         raise cant_open_exc, filename
63     return f
64
65 ######################################################################################
66
67 def our_raw_input(prompt=""):
68     if prompt:
69         sys.stdout.write(prompt);
70     sys.stdout.flush();
71     try:
72         ret = raw_input();
73         return ret
74     except EOFError:
75         sys.stderr.write('\nUser interrupt (^D).\n');
76         raise SystemExit;
77
78 ######################################################################################
79
80 def str_isnum (s):
81     for c in s:
82         if c not in string.digits:
83             return 0;
84     return 1;
85
86 ######################################################################################
87
88 def extract_component_from_section(section):
89     component = "";
90
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
96             component = s;
97
98     if string.lower(section) == "non-us":
99         component = "non-US/main";
100
101     # non-US prefix is case insensitive
102     if string.lower(component)[:6] == "non-us":
103         component = "non-US"+component[6:];
104
105     # Expand default component
106     if component == "":
107         if Cnf.has_key("Component::%s" % section):
108             component = section;
109         else:
110             component = "main";
111     elif component == "non-US":
112         component = "non-US/main";
113
114     return (section, component);
115
116 ######################################################################################
117
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.
121 #
122 # The rules are:
123 #
124 #
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.
127 #
128 # o The data section must end with a blank line and must be followed by
129 #   "-----BEGIN PGP SIGNATURE-----".
130
131 def parse_changes(filename, dsc_whitespace_rules=0):
132     changes_in = open_file(filename);
133     error = "";
134     changes = {};
135     lines = changes_in.readlines();
136
137     if not lines:
138         raise changes_parse_error_exc, "[Empty changes file]";
139
140     # Reindex by line number so we can easily verify the format of
141     # .dsc files...
142     index = 0;
143     indexed_lines = {};
144     for line in lines:
145         index = index + 1;
146         indexed_lines[index] = line[:-1];
147
148     inside_signature = 0;
149
150     indices = indexed_lines.keys()
151     index = 0;
152     first = -1;
153     while index < max(indices):
154         index = index + 1;
155         line = indexed_lines[index];
156         if line == "":
157             if dsc_whitespace_rules:
158                 index = index + 1;
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;
165                 break;
166         if string.find(line, "-----BEGIN PGP SIGNATURE") == 0:
167             break;
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 != "":
172                     index = index + 1;
173                     line = indexed_lines[index];
174             continue;
175         slf = re_single_line_field.match(line);
176         if slf:
177             field = string.lower(slf.groups()[0]);
178             changes[field] = slf.groups()[1];
179             first = 1;
180             continue;
181         if line == " .":
182             changes[field] = changes[field] + '\n';
183             continue;
184         mlf = re_multi_line_field.match(line);
185         if mlf:
186             if first == -1:
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';
190             first = 0;
191             changes[field] = changes[field] + mlf.groups()[0] + '\n';
192             continue;
193         error = error + line;
194
195     if dsc_whitespace_rules and inside_signature:
196         raise invalid_dsc_format_exc, index;
197
198     changes_in.close();
199     changes["filecontents"] = string.join (lines, "");
200
201     if error != "":
202         raise changes_parse_error_exc, error;
203
204     return changes;
205
206 ######################################################################################
207
208 # Dropped support for 1.4 and ``buggy dchanges 3.4'' (?!) compared to di.pl
209
210 def build_file_list(changes, is_a_dsc=0):
211     files = {}
212     format = changes.get("format", "")
213     if 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;
217
218     # No really, this has happened.  Think 0 length .dsc file.
219     if not changes.has_key("files"):
220         raise no_files_exc
221
222     for i in string.split(changes["files"], "\n"):
223         if i == "":
224             break
225         s = string.split(i)
226         section = priority = "";
227         try:
228             if is_a_dsc:
229                 (md5, size, name) = s
230             else:
231                 (md5, size, section, priority, name) = s
232         except ValueError:
233             raise changes_parse_error_exc, i
234
235         if section == "": section = "-"
236         if priority == "": priority = "-"
237
238         (section, component) = extract_component_from_section(section);
239
240         files[name] = { "md5sum" : md5,
241                         "size" : size,
242                         "section": section,
243                         "priority": priority,
244                         "component": component }
245
246     return files
247
248 ######################################################################################
249
250 # Fix the `Maintainer:' field to be an RFC822 compatible address.
251 # cf. Packaging Manual (4.2.4)
252 #
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!'
256
257 def fix_maintainer (maintainer):
258     m = re_parse_maintainer.match(maintainer);
259     rfc822 = maintainer
260     name = ""
261     email = ""
262     if m != None and len(m.groups()) == 2:
263         name = m.group(1)
264         email = m.group(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)
268
269 ######################################################################################
270
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;
276
277         # If we've been passed a string dump it into a temporary file
278         if message != "":
279             filename = tempfile.mktemp();
280             fd = os.open(filename, os.O_RDWR|os.O_CREAT|os.O_EXCL, 0700);
281             os.write (fd, message);
282             os.close (fd);
283
284         # Invoke sendmail
285         (result, output) = commands.getstatusoutput("%s < %s" % (Cnf["Dinstall::SendmailCommand"], filename));
286         if (result != 0):
287             raise sendmail_failed_exc, output;
288
289         # Clean up any temporary files
290         if message !="":
291             os.unlink (filename);
292
293 ######################################################################################
294
295 def poolify (source, component):
296     if 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 + '/'
303     else:
304         return component + source[:1] + '/' + source + '/'
305
306 ######################################################################################
307
308 def move (src, dest, overwrite = 0, perms = 0664):
309     if os.path.exists(dest) and os.path.isdir(dest):
310         dest_dir = dest;
311     else:
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);
316         os.umask(umask);
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):
322         if not overwrite:
323             raise file_exists_exc;
324         else:
325             if not os.access(dest, os.W_OK):
326                 raise cant_overwrite_exc
327     shutil.copy2(src, dest);
328     os.chmod(dest, perms);
329     os.unlink(src);
330
331 def copy (src, dest, overwrite = 0, perms = 0664):
332     if os.path.exists(dest) and os.path.isdir(dest):
333         dest_dir = dest;
334     else:
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);
339         os.umask(umask);
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):
345         if not overwrite:
346             raise file_exists_exc
347         else:
348             if not os.access(dest, os.W_OK):
349                 raise cant_overwrite_exc
350     shutil.copy2(src, dest);
351     os.chmod(dest, perms);
352
353 ######################################################################################
354
355 def where_am_i ():
356     res = socket.gethostbyaddr(socket.gethostname());
357     database_hostname = Cnf.get("Config::" + res[0] + "::DatabaseHostname");
358     if database_hostname:
359         return database_hostname;
360     else:
361         return res[0];
362
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"]
367     else:
368         return default_config;
369
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"]
374     else:
375         return default_apt_config;
376
377 ######################################################################################
378
379 # Escape characters which have meaning to SQL's regex comparison operator ('~')
380 # (woefully incomplete)
381
382 def regex_safe (s):
383     s = string.replace(s, '+', '\\\\+');
384     s = string.replace(s, '.', '\\\\.');
385     return s
386
387 ######################################################################################
388
389 # Perform a substition of template
390 def TemplateSubst(map, filename):
391     file = open_file(filename);
392     template = file.read();
393     for x in map.keys():
394         template = string.replace(template,x,map[x]);
395     file.close();
396     return template;
397
398 ######################################################################################
399
400 def fubar(msg, exit_code=1):
401     sys.stderr.write("E: %s\n" % (msg));
402     sys.exit(exit_code);
403
404 def warn(msg):
405     sys.stderr.write("W: %s\n" % (msg));
406
407 ######################################################################################
408
409 # Returns the user name with a laughable attempt at rfc822 conformancy
410 # (read: removing stray periods).
411 def whoami ():
412     return string.replace(string.split(pwd.getpwuid(os.getuid())[4],',')[0], '.', '');
413
414 ######################################################################################
415
416 def size_type (c):
417     t  = " b";
418     if c > 10000:
419         c = c / 1000;
420         t = " Kb";
421     if c > 10000:
422         c = c / 1000;
423         t = " Mb";
424     return ("%d%s" % (c, t))
425
426 ################################################################################
427
428 def cc_fix_changes (changes):
429     o = changes.get("architecture", "")
430     if o != "":
431         del changes["architecture"]
432     changes["architecture"] = {}
433     for j in string.split(o):
434         changes["architecture"][j] = 1
435
436 # Sort by source name, source version, 'have source', and then by filename
437 def changes_compare (a, b):
438     try:
439         a_changes = parse_changes(a);
440     except:
441         return -1;
442
443     try:
444         b_changes = parse_changes(b);
445     except:
446         return 1;
447
448     cc_fix_changes (a_changes);
449     cc_fix_changes (b_changes);
450
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);
455     if q:
456         return q;
457
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);
462     if q:
463         return q;
464
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:
469         return -1;
470     elif b_has_source and not a_has_source:
471         return 1;
472
473     # Fall back to sort by filename
474     return cmp(a, b);
475
476 ################################################################################
477
478 def find_next_free (dest, too_many=100):
479     extra = 0;
480     orig_dest = dest;
481     while os.path.exists(dest) and extra < too_many:
482         dest = orig_dest + '.' + repr(extra);
483         extra = extra + 1;
484     if extra >= too_many:
485         raise tried_too_hard_exc;
486     return dest;
487
488 ################################################################################
489
490 def result_join (original, sep = '\t'):
491     list = [];
492     for i in xrange(len(original)):
493         if original[i] == None:
494             list.append("");
495         else:
496             list.append(original[i]);
497     return string.join(list, sep);
498
499 ################################################################################
500
501 def prefix_multi_line_string(str, prefix):
502     out = "";
503     for line in string.split(str, '\n'):
504         line = string.strip(line);
505         if line:
506             out = out + "%s%s\n" % (prefix, line);
507     # Strip trailing new line
508     if out:
509         out = out[:-1];
510     return out;
511
512 ################################################################################
513
514 def validate_changes_file_arg(file, fatal=1):
515     error = None;
516
517     orig_filename = file
518     if file[-6:] == ".katie":
519         file = file[:-6]+".changes";
520
521     if file[-8:] != ".changes":
522         error = "invalid file type; not a changes file";
523     else:
524         if not os.access(file,os.R_OK):
525             if os.path.exists(file):
526                 error = "permission denied";
527             else:
528                 error = "file not found";
529
530     if error:
531         if fatal:
532             fubar("%s: %s." % (orig_filename, error));
533         else:
534             warn("Skipping %s - %s" % (orig_filename, error));
535             return None;
536     else:
537         return file;
538
539 ################################################################################
540
541 def real_arch(arch):
542     return (arch != "source" and arch != "all");
543
544 ################################################################################
545
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];
550
551 ################################################################################
552
553 def get_conf():
554         return Cnf;
555
556 ################################################################################
557
558 # Handle -a, -c and -s arguments; returns them as SQL constraints
559 def parse_args(Options):
560     # Process suite
561     if Options["Suite"]:
562         suite_ids_list = [];
563         for suite in string.split(Options["Suite"]):
564             suite_id = db_access.get_suite_id(suite);
565             if suite_id == -1:
566                 utils.warn("suite '%s' not recognised." % (suite));
567             else:
568                 suite_ids_list.append(suite_id);
569         if suite_ids_list:
570             con_suites = "AND su.id IN (%s)" % string.join(map(str, suite_ids_list), ", ");
571         else:
572             fubar("No valid suite given.");
573     else:
574         con_suites = "";
575
576     # Process component
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));
583             else:
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), ", ");
587         else:
588             fubar("No valid component given.");
589     else:
590         con_components = "";
591
592     # Process architecture
593     con_architectures = "";
594     if Options["Architecture"]:
595         arch_ids_list = [];
596         check_source = 0;
597         for architecture in string.split(Options["Architecture"]):
598             if architecture == "source":
599                 check_source = 1;
600             else:
601                 architecture_id = db_access.get_architecture_id(architecture);
602                 if architecture_id == -1:
603                     warn("architecture '%s' not recognised." % (architecture));
604                 else:
605                     arch_ids_list.append(architecture_id);
606         if arch_ids_list:
607             con_architectures = "AND a.id IN (%s)" % string.join(map(str, arch_ids_list), ", ");
608         else:
609             if not check_source:
610                 fubar("No valid architecture given.");
611     else:
612         check_source = 1;
613
614     return (con_suites, con_architectures, con_components, check_source);
615
616 ################################################################################
617
618 apt_pkg.init()
619
620 Cnf = apt_pkg.newConfiguration();
621 apt_pkg.ReadConfigFileISC(Cnf,default_config);
622
623 if which_conf_file() != default_config:
624         apt_pkg.ReadConfigFileISC(Cnf,which_conf_file())
625
626 ################################################################################