]> git.decadent.org.uk Git - dak.git/blob - utils.py
add optional prompt argument to our_raw_input; use it.
[dak.git] / utils.py
1 # Utility functions
2 # Copyright (C) 2000, 2001  James Troup <james@nocrew.org>
3 # $Id: utils.py,v 1.39 2002-02-22 02:19:26 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 def touch_file(filename):
61     fd = os.open(filename, os.O_RDONLY | os.O_CREAT);
62     os.close(fd);
63
64 ######################################################################################
65
66 def our_raw_input(prompt=""):
67     if prompt:
68         sys.stdout.write(prompt);
69     sys.stdout.flush();
70     try:
71         ret = raw_input();
72         return ret
73     except EOFError:
74         sys.stderr.write('\nUser interrupt (^D).\n');
75         raise SystemExit;
76
77 ######################################################################################
78
79 def str_isnum (s):
80     for c in s:
81         if c not in string.digits:
82             return 0;
83     return 1;
84
85 ######################################################################################
86
87 def extract_component_from_section(section):
88     component = "";
89
90     if string.find(section, '/') != -1:
91         component = string.split(section, '/')[0];
92     if string.lower(component) == "non-us" and string.count(section, '/') > 0:
93         s = component + '/' + string.split(section, '/')[1];
94         if Cnf.has_key("Component::%s" % s): # Avoid e.g. non-US/libs
95             component = s;
96
97     if string.lower(section) == "non-us":
98         component = "non-US/main";
99
100     # non-US prefix is case insensitive
101     if string.lower(component)[:6] == "non-us":
102         component = "non-US"+component[6:];
103
104     # Expand default component
105     if component == "":
106         if Cnf.has_key("Component::%s" % section):
107             component = section;
108         else:
109             component = "main";
110     elif component == "non-US":
111         component = "non-US/main";
112
113     return (section, component);
114
115 ######################################################################################
116
117 # dsc_whitespace_rules turns on strict format checking to avoid
118 # allowing in source packages which are unextracable by the
119 # inappropriately fragile dpkg-source.
120 #
121 # The rules are:
122 #
123 #
124 # o The PGP header consists of "-----BEGIN PGP SIGNED MESSAGE-----"
125 #   followed by any PGP header data and must end with a blank line.
126 #
127 # o The data section must end with a blank line and must be followed by
128 #   "-----BEGIN PGP SIGNATURE-----".
129
130 def parse_changes(filename, dsc_whitespace_rules):
131     changes_in = open_file(filename);
132     error = "";
133     changes = {};
134     lines = changes_in.readlines();
135
136     if not lines:
137         raise changes_parse_error_exc, "[Empty changes file]";
138
139     # Reindex by line number so we can easily verify the format of
140     # .dsc files...
141     index = 0;
142     indexed_lines = {};
143     for line in lines:
144         index = index + 1;
145         indexed_lines[index] = line[:-1];
146
147     inside_signature = 0;
148
149     indices = indexed_lines.keys()
150     index = 0;
151     while index < max(indices):
152         index = index + 1;
153         line = indexed_lines[index];
154         if line == "":
155             if dsc_whitespace_rules:
156                 index = index + 1;
157                 if index > max(indices):
158                     raise invalid_dsc_format_exc, index;
159                 line = indexed_lines[index];
160                 if string.find(line, "-----BEGIN PGP SIGNATURE") != 0:
161                     raise invalid_dsc_format_exc, index;
162                 inside_signature = 0;
163                 break;
164         if string.find(line, "-----BEGIN PGP SIGNATURE") == 0:
165             break;
166         if string.find(line, "-----BEGIN PGP SIGNED MESSAGE") == 0:
167             if dsc_whitespace_rules:
168                 inside_signature = 1;
169                 while index < max(indices) and line != "":
170                     index = index + 1;
171                     line = indexed_lines[index];
172             continue;
173         slf = re_single_line_field.match(line);
174         if slf:
175             field = string.lower(slf.groups()[0]);
176             changes[field] = slf.groups()[1];
177             first = 1;
178             continue;
179         if line == " .":
180             changes[field] = changes[field] + '\n';
181             continue;
182         mlf = re_multi_line_field.match(line);
183         if mlf:
184             if first == 1 and changes[field] != "":
185                 changes[field] = changes[field] + '\n';
186             first = 0;
187             changes[field] = changes[field] + mlf.groups()[0] + '\n';
188             continue;
189         error = error + line;
190
191     if dsc_whitespace_rules and inside_signature:
192         raise invalid_dsc_format_exc, index;
193
194     changes_in.close();
195     changes["filecontents"] = string.join (lines, "");
196
197     if error != "":
198         raise changes_parse_error_exc, error;
199
200     return changes;
201
202 ######################################################################################
203
204 # Dropped support for 1.4 and ``buggy dchanges 3.4'' (?!) compared to di.pl
205
206 def build_file_list(changes, dsc):
207     files = {}
208     format = changes.get("format", "")
209     if format != "":
210         format = float(format)
211     if dsc == "" and (format < 1.5 or format > 2.0):
212         raise nk_format_exc, format;
213
214     # No really, this has happened.  Think 0 length .dsc file.
215     if not changes.has_key("files"):
216         raise no_files_exc
217
218     for i in string.split(changes["files"], "\n"):
219         if i == "":
220             break
221         s = string.split(i)
222         section = priority = "";
223         try:
224             if dsc != "":
225                 (md5, size, name) = s
226             else:
227                 (md5, size, section, priority, name) = s
228         except ValueError:
229             raise changes_parse_error_exc, i
230
231         if section == "": section = "-"
232         if priority == "": priority = "-"
233
234         (section, component) = extract_component_from_section(section);
235
236         files[name] = { "md5sum" : md5,
237                         "size" : size,
238                         "section": section,
239                         "priority": priority,
240                         "component": component }
241
242     return files
243
244 ######################################################################################
245
246 # Fix the `Maintainer:' field to be an RFC822 compatible address.
247 # cf. Packaging Manual (4.2.4)
248 #
249 # 06:28|<Culus> 'The standard sucks, but my tool is supposed to
250 #                interoperate with it. I know - I'll fix the suckage
251 #                and make things incompatible!'
252
253 def fix_maintainer (maintainer):
254     m = re_parse_maintainer.match(maintainer);
255     rfc822 = maintainer
256     name = ""
257     email = ""
258     if m != None and len(m.groups()) == 2:
259         name = m.group(1)
260         email = m.group(2)
261         if string.find(name, ',') != -1 or string.find(name, '.') != -1:
262             rfc822 = re_parse_maintainer.sub(r"\2 (\1)", maintainer)
263     return (rfc822, name, email)
264
265 ######################################################################################
266
267 # sendmail wrapper, takes _either_ a message string or a file as arguments
268 def send_mail (message, filename):
269         # Sanity check arguments
270         if message != "" and filename != "":
271             raise send_mail_invalid_args_exc;
272
273         # If we've been passed a string dump it into a temporary file
274         if message != "":
275             filename = tempfile.mktemp();
276             fd = os.open(filename, os.O_RDWR|os.O_CREAT|os.O_EXCL, 0700);
277             os.write (fd, message);
278             os.close (fd);
279
280         # Invoke sendmail
281         (result, output) = commands.getstatusoutput("%s < %s" % (Cnf["Dinstall::SendmailCommand"], filename));
282         if (result != 0):
283             raise sendmail_failed_exc, output;
284
285         # Clean up any temporary files
286         if message !="":
287             os.unlink (filename);
288
289 ######################################################################################
290
291 def poolify (source, component):
292     if component != "":
293         component = component + '/';
294     # FIXME: this is nasty
295     component = string.lower(component);
296     component = string.replace(component, 'non-us/', 'non-US/');
297     if source[:3] == "lib":
298         return component + source[:4] + '/' + source + '/'
299     else:
300         return component + source[:1] + '/' + source + '/'
301
302 ######################################################################################
303
304 def move (src, dest, overwrite = 0):
305     if os.path.exists(dest) and os.path.isdir(dest):
306         dest_dir = dest;
307     else:
308         dest_dir = os.path.dirname(dest);
309     if not os.path.exists(dest_dir):
310         umask = os.umask(00000);
311         os.makedirs(dest_dir, 02775);
312         os.umask(umask);
313     #print "Moving %s to %s..." % (src, dest);
314     if os.path.exists(dest) and os.path.isdir(dest):
315         dest = dest + '/' + os.path.basename(src);
316     # Don't overwrite unless forced to
317     if os.path.exists(dest):
318         if not overwrite:
319             raise file_exists_exc;
320         else:
321             if not os.access(dest, os.W_OK):
322                 raise cant_overwrite_exc
323     shutil.copy2(src, dest);
324     os.chmod(dest, 0664);
325     os.unlink(src);
326
327 def copy (src, dest, overwrite = 0):
328     if os.path.exists(dest) and os.path.isdir(dest):
329         dest_dir = dest;
330     else:
331         dest_dir = os.path.dirname(dest);
332     if not os.path.exists(dest_dir):
333         umask = os.umask(00000);
334         os.makedirs(dest_dir, 02775);
335         os.umask(umask);
336     #print "Copying %s to %s..." % (src, dest);
337     if os.path.exists(dest) and os.path.isdir(dest):
338         dest = dest + '/' + os.path.basename(src);
339     # Don't overwrite unless forced to
340     if os.path.exists(dest):
341         if not overwrite:
342             raise file_exists_exc
343         else:
344             if not os.access(dest, os.W_OK):
345                 raise cant_overwrite_exc
346     shutil.copy2(src, dest);
347     os.chmod(dest, 0664);
348
349 ######################################################################################
350
351 def where_am_i ():
352     res = socket.gethostbyaddr(socket.gethostname());
353     database_hostname = Cnf.get("Config::" + res[0] + "::DatabaseHostname");
354     if database_hostname:
355         return database_hostname;
356     else:
357         return res[0];
358
359 def which_conf_file ():
360     res = socket.gethostbyaddr(socket.gethostname());
361     if Cnf.get("Config::" + res[0] + "::KatieConfig"):
362         return Cnf["Config::" + res[0] + "::KatieConfig"]
363     else:
364         return default_config;
365
366 def which_apt_conf_file ():
367     res = socket.gethostbyaddr(socket.gethostname());
368     if Cnf.get("Config::" + res[0] + "::AptConfig"):
369         return Cnf["Config::" + res[0] + "::AptConfig"]
370     else:
371         return default_apt_config;
372
373 ######################################################################################
374
375 # Escape characters which have meaning to SQL's regex comparison operator ('~')
376 # (woefully incomplete)
377
378 def regex_safe (s):
379     s = string.replace(s, '+', '\\\\+');
380     s = string.replace(s, '.', '\\\\.');
381     return s
382
383 ######################################################################################
384
385 # Perform a substition of template
386 def TemplateSubst(Map,Template):
387     for x in Map.keys():
388         Template = string.replace(Template,x,Map[x]);
389     return Template;
390
391 ######################################################################################
392
393 def fubar(msg, exit_code=1):
394     sys.stderr.write("E: %s\n" % (msg));
395     sys.exit(exit_code);
396
397 def warn(msg):
398     sys.stderr.write("W: %s\n" % (msg));
399
400 ######################################################################################
401
402 # Returns the user name with a laughable attempt at rfc822 conformancy
403 # (read: removing stray periods).
404 def whoami ():
405     return string.replace(string.split(pwd.getpwuid(os.getuid())[4],',')[0], '.', '');
406
407 ######################################################################################
408
409 def size_type (c):
410     t  = " b";
411     if c > 10000:
412         c = c / 1000;
413         t = " Kb";
414     if c > 10000:
415         c = c / 1000;
416         t = " Mb";
417     return ("%d%s" % (c, t))
418
419 ################################################################################
420
421 def cc_fix_changes (changes):
422     o = changes.get("architecture", "")
423     if o != "":
424         del changes["architecture"]
425     changes["architecture"] = {}
426     for j in string.split(o):
427         changes["architecture"][j] = 1
428
429 # Sort by 'have source', by source name, by source version number, by filename
430
431 def changes_compare (a, b):
432     try:
433         a_changes = parse_changes(a, 0)
434     except:
435         return -1;
436
437     try:
438         b_changes = parse_changes(b, 0)
439     except:
440         return 1;
441
442     cc_fix_changes (a_changes);
443     cc_fix_changes (b_changes);
444
445     # Sort by 'have source'
446
447     a_has_source = a_changes["architecture"].get("source")
448     b_has_source = b_changes["architecture"].get("source")
449     if a_has_source and not b_has_source:
450         return -1;
451     elif b_has_source and not a_has_source:
452         return 1;
453
454     # Sort by source name
455
456     a_source = a_changes.get("source");
457     b_source = b_changes.get("source");
458     q = cmp (a_source, b_source);
459     if q:
460         return q;
461
462     # Sort by source version
463
464     a_version = a_changes.get("version");
465     b_version = b_changes.get("version");
466     q = apt_pkg.VersionCompare(a_version, b_version);
467     if q:
468         return q
469
470     # Fall back to sort by filename
471
472     return cmp(a, b);
473
474 ################################################################################
475
476 def find_next_free (dest, too_many=100):
477     extra = 0;
478     orig_dest = dest;
479     while os.path.exists(dest) and extra < too_many:
480         dest = orig_dest + '.' + repr(extra);
481         extra = extra + 1;
482     if extra >= too_many:
483         raise tried_too_hard_exc;
484     return dest;
485
486 ################################################################################
487
488 def result_join (original, sep = '\t'):
489     list = [];
490     for i in xrange(len(original)):
491         if original[i] == None:
492             list.append("");
493         else:
494             list.append(original[i]);
495     return string.join(list, sep);
496
497 def plural (x):
498     if x > 1:
499         return "s";
500     else:
501         return "";
502
503 ################################################################################
504
505 def get_conf():
506         return Cnf;
507
508 ################################################################################
509
510 apt_pkg.init()
511
512 Cnf = apt_pkg.newConfiguration();
513 apt_pkg.ReadConfigFileISC(Cnf,default_config);
514
515 if which_conf_file() != default_config:
516         apt_pkg.ReadConfigFileISC(Cnf,which_conf_file())
517
518 ################################################################################