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