]> git.decadent.org.uk Git - dak.git/blob - utils.py
[aj] make SoE work. [me] don't overwrite files ever; use dated sub directories in...
[dak.git] / utils.py
1 # Utility functions
2 # Copyright (C) 2000  James Troup <james@nocrew.org>
3 # $Id: utils.py,v 1.24 2001-05-31 02:19:30 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_begin_pgp_signature = re.compile("^-----BEGIN PGP SIGNATURE");
31 re_begin_pgp_signed_msg = re.compile("^-----BEGIN PGP SIGNED MESSAGE");
32 re_single_line_field = re.compile(r"^(\S*)\s*:\s*(.*)");
33 re_multi_line_description = re.compile(r"^ \.$");
34 re_multi_line_field = re.compile(r"^\s(.*)");
35
36 re_parse_maintainer = re.compile(r"^\s*(\S.*\S)\s*\<([^\> \t]+)\>");
37
38 changes_parse_error_exc = "Can't parse line in .changes file";
39 invalid_dsc_format_exc = "Invalid .dsc file";
40 nk_format_exc = "Unknown Format: in .changes file";
41 no_files_exc = "No Files: field in .dsc file.";
42 cant_open_exc = "Can't read file.";
43 unknown_hostname_exc = "Unknown hostname";
44 cant_overwrite_exc = "Permission denied; can't overwrite existent file."
45 file_exists_exc = "Destination file exists";
46
47 ######################################################################################
48
49 def open_file(filename, mode):
50     try:
51         f = open(filename, mode);
52     except IOError:
53         raise cant_open_exc, filename
54     return f
55
56 ######################################################################################
57
58 # From reportbug
59 def our_raw_input():
60     sys.stdout.flush()
61     try:
62         ret = raw_input()
63         return ret
64     except EOFError:
65         sys.stderr.write('\nUser interrupt (^D).\n')
66         raise SystemExit
67
68 ######################################################################################
69
70 def str_isnum (s):
71     for c in s:
72         if c not in string.digits:
73             return 0;
74     return 1;
75
76 ######################################################################################
77
78 # What a mess.  FIXME
79 def extract_component_from_section(section):
80     component = "";
81     
82     if string.find(section, '/') != -1: 
83         component = string.split(section, '/')[0];
84     if string.lower(component) == "non-us" and string.count(section, '/') > 0:
85         s = string.split(section, '/')[1];
86         if s == "main" or s == "non-free" or s == "contrib": # Avoid e.g. non-US/libs
87             component = string.split(section, '/')[0]+ '/' + string.split(section, '/')[1];
88
89     if string.lower(section) == "non-us":
90         component = "non-US/main";
91             
92     if component == "":
93         component = "main";
94     elif string.lower(component) == "non-us":
95         component = "non-US/main";
96
97     return (section, component);
98
99 ######################################################################################
100
101 # dsc_whitespace_rules turns on strict format checking to avoid
102 # allowing in source packages which are unextracable by the
103 # inappropriately fragile dpkg-source.
104 #
105 # The rules are:
106 #
107 #
108 # o The PGP header consists of "-----BEGIN PGP SIGNED MESSAGE-----"
109 #   followed by any PGP header data and must end with a blank line.
110 #
111 # o The data section must end with a blank line and must be followed by
112 #   "-----BEGIN PGP SIGNATURE-----".
113
114 def parse_changes(filename, dsc_whitespace_rules):
115     changes_in = open_file(filename,'r');
116     error = "";
117     changes = {};
118     lines = changes_in.readlines();
119
120     if lines == []:
121         raise changes_parse_error_exc, "[Empty changes file]";
122
123     # Reindex by line number so we can easily verify the format of
124     # .dsc files...
125     index = 0;
126     indexed_lines = {};
127     for line in lines:
128         index = index + 1;
129         indexed_lines[index] = line[:-1];
130
131     inside_signature = 0;
132
133     indices = indexed_lines.keys()
134     index = 0;
135     while index < max(indices):
136         index = index + 1;
137         line = indexed_lines[index];
138         if line == "":
139             if dsc_whitespace_rules:
140                 index = index + 1;
141                 if index > max(indices):
142                     raise invalid_dsc_format_exc, index;
143                 line = indexed_lines[index];
144                 if not re_begin_pgp_signature.match(line):
145                     raise invalid_dsc_format_exc, index;
146                 inside_signature = 0;
147                 break;
148         if re_begin_pgp_signature.match(line):
149             break;
150         if re_begin_pgp_signed_msg.match(line):
151             if dsc_whitespace_rules:
152                 inside_signature = 1;
153                 while index < max(indices) and line != "":
154                     index = index + 1;
155                     line = indexed_lines[index];
156             continue;
157         slf = re_single_line_field.match(line);
158         if slf:
159             field = string.lower(slf.groups()[0]);
160             changes[field] = slf.groups()[1];
161             first = 1;
162             continue;
163         mld = re_multi_line_description.match(line);
164         if mld:
165             changes[field] = changes[field] + '\n';
166             continue;
167         mlf = re_multi_line_field.match(line);
168         if mlf:
169             if first == 1 and changes[field] != "":
170                 changes[field] = changes[field] + '\n';
171             first = 0;
172             changes[field] = changes[field] + mlf.groups()[0] + '\n';
173             continue;
174         error = error + line;
175
176     if dsc_whitespace_rules and inside_signature:
177         raise invalid_dsc_format_exc, index;
178         
179     changes_in.close();
180     changes["filecontents"] = string.join (lines, "");
181
182     if error != "":
183         raise changes_parse_error_exc, error;
184
185     return changes;
186
187 ######################################################################################
188
189 # Dropped support for 1.4 and ``buggy dchanges 3.4'' (?!) compared to di.pl
190
191 def build_file_list(changes, dsc):
192     files = {}
193     format = changes.get("format", "")
194     if format != "":
195         format = float(format)
196     if dsc == "" and (format < 1.5 or format > 2.0):
197         raise nk_format_exc, changes["format"];
198
199     # No really, this has happened.  Think 0 length .dsc file.
200     if not changes.has_key("files"):
201         raise no_files_exc
202     
203     for i in string.split(changes["files"], "\n"):
204         if i == "":
205             break
206         s = string.split(i)
207         section = priority = "";
208         try:
209             if dsc != "":
210                 (md5, size, name) = s
211             else:
212                 (md5, size, section, priority, name) = s
213         except ValueError:
214             raise changes_parse_error_exc, i
215
216         if section == "": section = "-"
217         if priority == "": priority = "-"
218
219         (section, component) = extract_component_from_section(section);
220         
221         files[name] = { "md5sum" : md5,
222                         "size" : size,
223                         "section": section,
224                         "priority": priority,
225                         "component": component }
226
227     return files
228
229 ######################################################################################
230
231 # Fix the `Maintainer:' field to be an RFC822 compatible address.
232 # cf. Packaging Manual (4.2.4)
233 #
234 # 06:28|<Culus> 'The standard sucks, but my tool is supposed to
235 #                interoperate with it. I know - I'll fix the suckage
236 #                and make things incompatible!'
237         
238 def fix_maintainer (maintainer):
239     m = re_parse_maintainer.match(maintainer);
240     rfc822 = maintainer
241     name = ""
242     email = ""
243     if m != None and len(m.groups()) == 2:
244         name = m.group(1)
245         email = m.group(2)
246         if string.find(name, ',') != -1 or string.find(name, '.') != -1:
247             rfc822 = re_parse_maintainer.sub(r"\2 (\1)", maintainer)
248     return (rfc822, name, email)
249
250 ######################################################################################
251
252 # sendmail wrapper, takes _either_ a message string or a file as arguments
253 def send_mail (message, filename):
254         #### FIXME, how do I get this out of Cnf in katie?
255         sendmail_command = "/usr/sbin/sendmail -odq -oi -t";
256
257         # Sanity check arguments
258         if message != "" and filename != "":
259                 sys.stderr.write ("send_mail() can't be called with both arguments as non-null! (`%s' and `%s')\n%s" % (message, filename))
260                 sys.exit(1)
261         # If we've been passed a string dump it into a temporary file
262         if message != "":
263                 filename = tempfile.mktemp()
264                 fd = os.open(filename, os.O_RDWR|os.O_CREAT|os.O_EXCL, 0700)
265                 os.write (fd, message)
266                 os.close (fd)
267         # Invoke sendmail
268         (result, output) = commands.getstatusoutput("%s < %s" % (sendmail_command, filename))
269         if (result != 0):
270                 sys.stderr.write ("Sendmail invocation (`%s') failed for `%s'!\n%s" % (sendmail_command, filename, output))
271                 sys.exit(result)
272         # Clean up any temporary files
273         if message !="":
274                 os.unlink (filename)
275
276 ######################################################################################
277
278 def poolify (source, component):
279     if component != "":
280         component = component + '/';
281     # FIXME: this is nasty
282     component = string.lower(component);
283     component = string.replace(component, 'non-us/', 'non-US/');
284     if source[:3] == "lib":
285         return component + source[:4] + '/' + source + '/'
286     else:
287         return component + source[:1] + '/' + source + '/'
288
289 ######################################################################################
290
291 def move (src, dest, overwrite = 0):
292     if os.path.exists(dest) and os.path.isdir(dest):
293         dest_dir = dest;
294     else:
295         dest_dir = os.path.dirname(dest);
296     if not os.path.exists(dest_dir):
297         umask = os.umask(00000);
298         os.makedirs(dest_dir, 02775);
299         os.umask(umask);
300     #print "Moving %s to %s..." % (src, dest);
301     if os.path.exists(dest) and os.path.isdir(dest):
302         dest = dest + '/' + os.path.basename(src);
303     # Don't overwrite unless forced to
304     if os.path.exists(dest):
305         if not overwrite:
306             raise file_exists_exc;
307         else:
308             if not os.access(dest, os.W_OK):
309                 raise cant_overwrite_exc
310     shutil.copy2(src, dest);
311     os.chmod(dest, 0664);
312     os.unlink(src);
313
314 def copy (src, dest, overwrite = 0):
315     if os.path.exists(dest) and os.path.isdir(dest):
316         dest_dir = dest;
317     else:
318         dest_dir = os.path.dirname(dest);
319     if not os.path.exists(dest_dir):
320         umask = os.umask(00000);
321         os.makedirs(dest_dir, 02775);
322         os.umask(umask);
323     #print "Copying %s to %s..." % (src, dest);
324     if os.path.exists(dest) and os.path.isdir(dest):
325         dest = dest + '/' + os.path.basename(src);
326     # Don't overwrite unless forced to
327     if os.path.exists(dest):
328         if not overwrite:
329             raise file_exists_exc
330         else:
331             if not os.access(dest, os.W_OK):
332                 raise cant_overwrite_exc
333     shutil.copy2(src, dest);
334     os.chmod(dest, 0664);
335
336 ######################################################################################
337
338 # FIXME: this is inherently nasty.  Can't put this mapping in a conf
339 # file because the conf file depends on the archive.. doh.  Maybe an
340 # archive independent conf file is needed.
341
342 def where_am_i ():
343     res = socket.gethostbyaddr(socket.gethostname());
344     if res[0] == 'pandora.debian.org':
345         return 'non-US';
346     elif res[0] == 'auric.debian.org':
347         return 'ftp-master';
348     else:
349         raise unknown_hostname_exc, res;
350
351 ######################################################################################
352
353 # FIXME: this isn't great either.
354
355 def which_conf_file ():
356     archive = where_am_i ();
357     if archive == 'non-US':
358         return '/org/non-us.debian.org/katie/katie.conf-non-US';
359     elif archive == 'ftp-master':
360         return '/org/ftp.debian.org/katie/katie.conf';
361     else:
362         raise unknown_hostname_exc, archive
363
364 # FIXME: if the above isn't great, this can't be either :)
365
366 def which_apt_conf_file ():
367     archive = where_am_i ();
368     if archive == 'non-US':
369         return '/org/non-us.debian.org/katie/apt.conf-non-US';
370     elif archive == 'ftp-master':
371         return '/org/ftp.debian.org/katie/apt.conf';
372     else:
373         raise unknown_hostname_exc, archive
374
375 ######################################################################################
376
377 # Escape characters which have meaning to SQL's regex comparison operator ('~')
378 # (woefully incomplete)
379
380 def regex_safe (s):
381     s = string.replace(s, '+', '\\\\+');
382     s = string.replace(s, '.', '\\\\.');
383     return s
384
385 ######################################################################################
386
387 # Perform a substition of template 
388 def TemplateSubst(Map,Template):
389     for x in Map.keys():
390         Template = string.replace(Template,x,Map[x]);
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 'have source', by source name, by source version number, by filename
432
433 def changes_compare (a, b):
434     try:
435         a_changes = parse_changes(a, 0)
436     except changes_parse_error_exc, line:
437         return -1;
438
439     try:
440         b_changes = parse_changes(b, 0)
441     except changes_parse_error_exc, line:
442         return 1;
443     
444     cc_fix_changes (a_changes);
445     cc_fix_changes (b_changes);
446
447     # Sort by 'have source'
448
449     a_has_source = a_changes["architecture"].get("source")
450     b_has_source = b_changes["architecture"].get("source")
451     if a_has_source and not b_has_source:
452         return -1;
453     elif b_has_source and not a_has_source:
454         return 1;
455
456     # Sort by source name
457     
458     a_source = a_changes.get("source");
459     b_source = b_changes.get("source");
460     q = cmp (a_source, b_source);
461     if q:
462         return q;
463
464     # Sort by source version
465
466     a_version = a_changes.get("version");
467     b_version = b_changes.get("version");
468     q = apt_pkg.VersionCompare(a_version, b_version);
469     if q:
470         return q
471
472     # Fall back to sort by filename
473
474     return cmp(a, b);
475
476 ################################################################################