]> git.decadent.org.uk Git - dak.git/blob - utils.py
update for 2.2r7
[dak.git] / utils.py
1 # Utility functions
2 # Copyright (C) 2000, 2001, 2002  James Troup <james@nocrew.org>
3 # $Id: utils.py,v 1.49 2002-07-12 15:09:57 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 import commands, os, pwd, re, socket, shutil, string, sys, tempfile
20 import apt_pkg
21
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)$");
29
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]+$");
33
34 re_parse_maintainer = re.compile(r"^\s*(\S.*\S)\s*\<([^\> \t]+)\>");
35
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.";
47
48 default_config = "/etc/katie/katie.conf";
49 default_apt_config = "/etc/katie/apt.conf";
50
51 ######################################################################################
52
53 def open_file(filename, mode='r'):
54     try:
55         f = open(filename, mode);
56     except IOError:
57         raise cant_open_exc, filename
58     return f
59
60 ######################################################################################
61
62 def our_raw_input(prompt=""):
63     if prompt:
64         sys.stdout.write(prompt);
65     sys.stdout.flush();
66     try:
67         ret = raw_input();
68         return ret
69     except EOFError:
70         sys.stderr.write('\nUser interrupt (^D).\n');
71         raise SystemExit;
72
73 ######################################################################################
74
75 def str_isnum (s):
76     for c in s:
77         if c not in string.digits:
78             return 0;
79     return 1;
80
81 ######################################################################################
82
83 def extract_component_from_section(section):
84     component = "";
85
86     if string.find(section, '/') != -1:
87         component = string.split(section, '/')[0];
88     if string.lower(component) == "non-us" and string.count(section, '/') > 0:
89         s = component + '/' + string.split(section, '/')[1];
90         if Cnf.has_key("Component::%s" % s): # Avoid e.g. non-US/libs
91             component = s;
92
93     if string.lower(section) == "non-us":
94         component = "non-US/main";
95
96     # non-US prefix is case insensitive
97     if string.lower(component)[:6] == "non-us":
98         component = "non-US"+component[6:];
99
100     # Expand default component
101     if component == "":
102         if Cnf.has_key("Component::%s" % section):
103             component = section;
104         else:
105             component = "main";
106     elif component == "non-US":
107         component = "non-US/main";
108
109     return (section, component);
110
111 ######################################################################################
112
113 # dsc_whitespace_rules turns on strict format checking to avoid
114 # allowing in source packages which are unextracable by the
115 # inappropriately fragile dpkg-source.
116 #
117 # The rules are:
118 #
119 #
120 # o The PGP header consists of "-----BEGIN PGP SIGNED MESSAGE-----"
121 #   followed by any PGP header data and must end with a blank line.
122 #
123 # o The data section must end with a blank line and must be followed by
124 #   "-----BEGIN PGP SIGNATURE-----".
125
126 def parse_changes(filename, dsc_whitespace_rules=0):
127     changes_in = open_file(filename);
128     error = "";
129     changes = {};
130     lines = changes_in.readlines();
131
132     if not lines:
133         raise changes_parse_error_exc, "[Empty changes file]";
134
135     # Reindex by line number so we can easily verify the format of
136     # .dsc files...
137     index = 0;
138     indexed_lines = {};
139     for line in lines:
140         index = index + 1;
141         indexed_lines[index] = line[:-1];
142
143     inside_signature = 0;
144
145     indices = indexed_lines.keys()
146     index = 0;
147     first = -1;
148     while index < max(indices):
149         index = index + 1;
150         line = indexed_lines[index];
151         if line == "":
152             if dsc_whitespace_rules:
153                 index = index + 1;
154                 if index > max(indices):
155                     raise invalid_dsc_format_exc, index;
156                 line = indexed_lines[index];
157                 if string.find(line, "-----BEGIN PGP SIGNATURE") != 0:
158                     raise invalid_dsc_format_exc, index;
159                 inside_signature = 0;
160                 break;
161         if string.find(line, "-----BEGIN PGP SIGNATURE") == 0:
162             break;
163         if string.find(line, "-----BEGIN PGP SIGNED MESSAGE") == 0:
164             if dsc_whitespace_rules:
165                 inside_signature = 1;
166                 while index < max(indices) and line != "":
167                     index = index + 1;
168                     line = indexed_lines[index];
169             continue;
170         slf = re_single_line_field.match(line);
171         if slf:
172             field = string.lower(slf.groups()[0]);
173             changes[field] = slf.groups()[1];
174             first = 1;
175             continue;
176         if line == " .":
177             changes[field] = changes[field] + '\n';
178             continue;
179         mlf = re_multi_line_field.match(line);
180         if mlf:
181             if first == -1:
182                 raise changes_parse_error_exc, "'%s'\n [Multi-line field continuing on from nothing?]" % (line);
183             if first == 1 and changes[field] != "":
184                 changes[field] = changes[field] + '\n';
185             first = 0;
186             changes[field] = changes[field] + mlf.groups()[0] + '\n';
187             continue;
188         error = error + line;
189
190     if dsc_whitespace_rules and inside_signature:
191         raise invalid_dsc_format_exc, index;
192
193     changes_in.close();
194     changes["filecontents"] = string.join (lines, "");
195
196     if error != "":
197         raise changes_parse_error_exc, error;
198
199     return changes;
200
201 ######################################################################################
202
203 # Dropped support for 1.4 and ``buggy dchanges 3.4'' (?!) compared to di.pl
204
205 def build_file_list(changes, is_a_dsc=0):
206     files = {}
207     format = changes.get("format", "")
208     if format != "":
209         format = float(format)
210     if not is_a_dsc and (format < 1.5 or format > 2.0):
211         raise nk_format_exc, format;
212
213     # No really, this has happened.  Think 0 length .dsc file.
214     if not changes.has_key("files"):
215         raise no_files_exc
216
217     for i in string.split(changes["files"], "\n"):
218         if i == "":
219             break
220         s = string.split(i)
221         section = priority = "";
222         try:
223             if is_a_dsc:
224                 (md5, size, name) = s
225             else:
226                 (md5, size, section, priority, name) = s
227         except ValueError:
228             raise changes_parse_error_exc, i
229
230         if section == "": section = "-"
231         if priority == "": priority = "-"
232
233         (section, component) = extract_component_from_section(section);
234
235         files[name] = { "md5sum" : md5,
236                         "size" : size,
237                         "section": section,
238                         "priority": priority,
239                         "component": component }
240
241     return files
242
243 ######################################################################################
244
245 # Fix the `Maintainer:' field to be an RFC822 compatible address.
246 # cf. Packaging Manual (4.2.4)
247 #
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!'
251
252 def fix_maintainer (maintainer):
253     m = re_parse_maintainer.match(maintainer);
254     rfc822 = maintainer
255     name = ""
256     email = ""
257     if m != None and len(m.groups()) == 2:
258         name = m.group(1)
259         email = m.group(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)
263
264 ######################################################################################
265
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;
271
272         # If we've been passed a string dump it into a temporary file
273         if message != "":
274             filename = tempfile.mktemp();
275             fd = os.open(filename, os.O_RDWR|os.O_CREAT|os.O_EXCL, 0700);
276             os.write (fd, message);
277             os.close (fd);
278
279         # Invoke sendmail
280         (result, output) = commands.getstatusoutput("%s < %s" % (Cnf["Dinstall::SendmailCommand"], filename));
281         if (result != 0):
282             raise sendmail_failed_exc, output;
283
284         # Clean up any temporary files
285         if message !="":
286             os.unlink (filename);
287
288 ######################################################################################
289
290 def poolify (source, component):
291     if 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 + '/'
298     else:
299         return component + source[:1] + '/' + source + '/'
300
301 ######################################################################################
302
303 def move (src, dest, overwrite = 0, perms = 0664):
304     if os.path.exists(dest) and os.path.isdir(dest):
305         dest_dir = dest;
306     else:
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);
311         os.umask(umask);
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):
317         if not overwrite:
318             raise file_exists_exc;
319         else:
320             if not os.access(dest, os.W_OK):
321                 raise cant_overwrite_exc
322     shutil.copy2(src, dest);
323     os.chmod(dest, perms);
324     os.unlink(src);
325
326 def copy (src, dest, overwrite = 0, perms = 0664):
327     if os.path.exists(dest) and os.path.isdir(dest):
328         dest_dir = dest;
329     else:
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);
334         os.umask(umask);
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):
340         if not overwrite:
341             raise file_exists_exc
342         else:
343             if not os.access(dest, os.W_OK):
344                 raise cant_overwrite_exc
345     shutil.copy2(src, dest);
346     os.chmod(dest, perms);
347
348 ######################################################################################
349
350 def where_am_i ():
351     res = socket.gethostbyaddr(socket.gethostname());
352     database_hostname = Cnf.get("Config::" + res[0] + "::DatabaseHostname");
353     if database_hostname:
354         return database_hostname;
355     else:
356         return res[0];
357
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"]
362     else:
363         return default_config;
364
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"]
369     else:
370         return default_apt_config;
371
372 ######################################################################################
373
374 # Escape characters which have meaning to SQL's regex comparison operator ('~')
375 # (woefully incomplete)
376
377 def regex_safe (s):
378     s = string.replace(s, '+', '\\\\+');
379     s = string.replace(s, '.', '\\\\.');
380     return s
381
382 ######################################################################################
383
384 # Perform a substition of template
385 def TemplateSubst(map, filename):
386     file = open_file(filename);
387     template = file.read();
388     for x in map.keys():
389         template = string.replace(template,x,map[x]);
390     file.close();
391     return template;
392
393 ######################################################################################
394
395 def fubar(msg, exit_code=1):
396     sys.stderr.write("E: %s\n" % (msg));
397     sys.exit(exit_code);
398
399 def warn(msg):
400     sys.stderr.write("W: %s\n" % (msg));
401
402 ######################################################################################
403
404 # Returns the user name with a laughable attempt at rfc822 conformancy
405 # (read: removing stray periods).
406 def whoami ():
407     return string.replace(string.split(pwd.getpwuid(os.getuid())[4],',')[0], '.', '');
408
409 ######################################################################################
410
411 def size_type (c):
412     t  = " b";
413     if c > 10000:
414         c = c / 1000;
415         t = " Kb";
416     if c > 10000:
417         c = c / 1000;
418         t = " Mb";
419     return ("%d%s" % (c, t))
420
421 ################################################################################
422
423 def cc_fix_changes (changes):
424     o = changes.get("architecture", "")
425     if o != "":
426         del changes["architecture"]
427     changes["architecture"] = {}
428     for j in string.split(o):
429         changes["architecture"][j] = 1
430
431 # Sort by source name, source version, 'have source', and then by filename
432 def changes_compare (a, b):
433     try:
434         a_changes = parse_changes(a);
435     except:
436         return -1;
437
438     try:
439         b_changes = parse_changes(b);
440     except:
441         return 1;
442
443     cc_fix_changes (a_changes);
444     cc_fix_changes (b_changes);
445
446     # Sort by source name
447     a_source = a_changes.get("source");
448     b_source = b_changes.get("source");
449     q = cmp (a_source, b_source);
450     if q:
451         return q;
452
453     # Sort by source version
454     a_version = a_changes.get("version");
455     b_version = b_changes.get("version");
456     q = apt_pkg.VersionCompare(a_version, b_version);
457     if q:
458         return q;
459
460     # Sort by 'have source'
461     a_has_source = a_changes["architecture"].get("source");
462     b_has_source = b_changes["architecture"].get("source");
463     if a_has_source and not b_has_source:
464         return -1;
465     elif b_has_source and not a_has_source:
466         return 1;
467
468     # Fall back to sort by filename
469     return cmp(a, b);
470
471 ################################################################################
472
473 def find_next_free (dest, too_many=100):
474     extra = 0;
475     orig_dest = dest;
476     while os.path.exists(dest) and extra < too_many:
477         dest = orig_dest + '.' + repr(extra);
478         extra = extra + 1;
479     if extra >= too_many:
480         raise tried_too_hard_exc;
481     return dest;
482
483 ################################################################################
484
485 def result_join (original, sep = '\t'):
486     list = [];
487     for i in xrange(len(original)):
488         if original[i] == None:
489             list.append("");
490         else:
491             list.append(original[i]);
492     return string.join(list, sep);
493
494 ################################################################################
495
496 def prefix_multi_line_string(str, prefix):
497     out = "";
498     for line in string.split(str, '\n'):
499         line = string.strip(line);
500         if line:
501             out = out + "%s%s\n" % (prefix, line);
502     # Strip trailing new line
503     if out:
504         out = out[:-1];
505     return out;
506
507 ################################################################################
508
509 def validate_changes_file_arg(file, fatal=1):
510     error = None;
511
512     orig_filename = file
513     if file[-6:] == ".katie":
514         file = file[:-6]+".changes";
515
516     if file[-8:] != ".changes":
517         error = "invalid file type; not a changes file";
518     else:
519         if not os.access(file,os.R_OK):
520             if os.path.exists(file):
521                 error = "permission denied";
522             else:
523                 error = "file not found";
524
525     if error:
526         if fatal:
527             fubar("%s: %s." % (orig_filename, error));
528         else:
529             warn("Skipping %s - %s" % (orig_filename, error));
530             return None;
531     else:
532         return file;
533
534 ################################################################################
535
536 def real_arch(arch):
537     return (arch != "source" and arch != "all");
538
539 ################################################################################
540
541 def get_conf():
542         return Cnf;
543
544 ################################################################################
545
546 apt_pkg.init()
547
548 Cnf = apt_pkg.newConfiguration();
549 apt_pkg.ReadConfigFileISC(Cnf,default_config);
550
551 if which_conf_file() != default_config:
552         apt_pkg.ReadConfigFileISC(Cnf,which_conf_file())
553
554 ################################################################################