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