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