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