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