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