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