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