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