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