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