]> git.decadent.org.uk Git - dak.git/blob - utils.py
Don't change the value of None
[dak.git] / utils.py
1 # Utility functions
2 # Copyright (C) 2000, 2001  James Troup <james@nocrew.org>
3 # $Id: utils.py,v 1.34 2001-09-27 01:24:15 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, pwd, re, socket, shutil, stat, string, sys, tempfile
20 import apt_pkg
21
22 re_comments = re.compile(r"\#.*")
23 re_no_epoch = re.compile(r"^\d*\:")
24 re_no_revision = re.compile(r"\-[^-]*$")
25 re_arch_from_filename = re.compile(r"/binary-[^/]+/")
26 re_extract_src_version = re.compile (r"(\S+)\s*\((.*)\)")
27 re_isadeb = re.compile (r".*\.u?deb$");
28 re_issource = re.compile (r"(.+)_(.+?)\.(orig\.tar\.gz|diff\.gz|tar\.gz|dsc)");
29
30 re_single_line_field = re.compile(r"^(\S*)\s*:\s*(.*)");
31 re_multi_line_field = re.compile(r"^\s(.*)");
32
33 re_parse_maintainer = re.compile(r"^\s*(\S.*\S)\s*\<([^\> \t]+)\>");
34
35 changes_parse_error_exc = "Can't parse line in .changes file";
36 invalid_dsc_format_exc = "Invalid .dsc file";
37 nk_format_exc = "Unknown Format: in .changes file";
38 no_files_exc = "No Files: field in .dsc file.";
39 cant_open_exc = "Can't read file.";
40 unknown_hostname_exc = "Unknown hostname";
41 cant_overwrite_exc = "Permission denied; can't overwrite existent file."
42 file_exists_exc = "Destination file exists";
43 send_mail_invalid_args_exc = "Both arguments are non-null.";
44 sendmail_failed_exc = "Sendmail invocation failed";
45 tried_too_hard_exc = "Tried too hard to find a free filename.";
46
47 # Valid components; used by extract_component_from_section() because
48 # it doesn't know about Conf from it's caller.  FIXME
49
50 valid_components = {
51     "main": "",
52     "contrib": "",
53     "non-free": ""
54     };
55
56 default_config = "/etc/katie/katie.conf";
57 default_apt_config = "/etc/katie/apt.conf";
58 DefaultCnf = apt_pkg.newConfiguration();
59 apt_pkg.ReadConfigFileISC(DefaultCnf,default_config);
60
61 ######################################################################################
62
63 def open_file(filename, mode='r'):
64     try:
65         f = open(filename, mode);
66     except IOError:
67         raise cant_open_exc, filename
68     return f
69
70 def touch_file(filename):
71     fd = os.open(filename, os.O_RDONLY | os.O_CREAT);
72     os.close(fd);
73
74 ######################################################################################
75
76 # From reportbug
77 def our_raw_input():
78     sys.stdout.flush()
79     try:
80         ret = raw_input()
81         return ret
82     except EOFError:
83         sys.stderr.write('\nUser interrupt (^D).\n')
84         raise SystemExit
85
86 ######################################################################################
87
88 def str_isnum (s):
89     for c in s:
90         if c not in string.digits:
91             return 0;
92     return 1;
93
94 ######################################################################################
95
96 # Prefix and components hardcoded into this like a good'un; need to unhardcod at some
97 # stage. [FIXME]
98
99 def extract_component_from_section(section):
100     component = "";
101
102     if string.find(section, '/') != -1:
103         component = string.split(section, '/')[0];
104     if string.lower(component) == "non-us" and string.count(section, '/') > 0:
105         s = string.split(section, '/')[1];
106         if valid_components.has_key(s): # Avoid e.g. non-US/libs
107             component = string.split(section, '/')[0]+ '/' + string.split(section, '/')[1];
108
109     if string.lower(section) == "non-us":
110         component = "non-US/main";
111
112     # non-US prefix is case insensitive
113     if string.lower(component)[:6] == "non-us":
114         component = "non-US"+component[6:];
115
116     # Expand default component
117     if component == "":
118         if valid_components.has_key(section):
119             component = section;
120         else:
121             component = "main";
122     elif component == "non-US":
123         component = "non-US/main";
124
125     return (section, component);
126
127 ######################################################################################
128
129 # dsc_whitespace_rules turns on strict format checking to avoid
130 # allowing in source packages which are unextracable by the
131 # inappropriately fragile dpkg-source.
132 #
133 # The rules are:
134 #
135 #
136 # o The PGP header consists of "-----BEGIN PGP SIGNED MESSAGE-----"
137 #   followed by any PGP header data and must end with a blank line.
138 #
139 # o The data section must end with a blank line and must be followed by
140 #   "-----BEGIN PGP SIGNATURE-----".
141
142 def parse_changes(filename, dsc_whitespace_rules):
143     changes_in = open_file(filename,'r');
144     error = "";
145     changes = {};
146     lines = changes_in.readlines();
147
148     if lines == []:
149         raise changes_parse_error_exc, "[Empty changes file]";
150
151     # Reindex by line number so we can easily verify the format of
152     # .dsc files...
153     index = 0;
154     indexed_lines = {};
155     for line in lines:
156         index = index + 1;
157         indexed_lines[index] = line[:-1];
158
159     inside_signature = 0;
160
161     indices = indexed_lines.keys()
162     index = 0;
163     while index < max(indices):
164         index = index + 1;
165         line = indexed_lines[index];
166         if line == "":
167             if dsc_whitespace_rules:
168                 index = index + 1;
169                 if index > max(indices):
170                     raise invalid_dsc_format_exc, index;
171                 line = indexed_lines[index];
172                 if line[:24] != "-----BEGIN PGP SIGNATURE":
173                     raise invalid_dsc_format_exc, index;
174                 inside_signature = 0;
175                 break;
176         if line[:24] == "-----BEGIN PGP SIGNATURE":
177             break;
178         if line[:29] == "-----BEGIN PGP SIGNED MESSAGE":
179             if dsc_whitespace_rules:
180                 inside_signature = 1;
181                 while index < max(indices) and line != "":
182                     index = index + 1;
183                     line = indexed_lines[index];
184             continue;
185         slf = re_single_line_field.match(line);
186         if slf:
187             field = string.lower(slf.groups()[0]);
188             changes[field] = slf.groups()[1];
189             first = 1;
190             continue;
191         if line == " .":
192             changes[field] = changes[field] + '\n';
193             continue;
194         mlf = re_multi_line_field.match(line);
195         if mlf:
196             if first == 1 and changes[field] != "":
197                 changes[field] = changes[field] + '\n';
198             first = 0;
199             changes[field] = changes[field] + mlf.groups()[0] + '\n';
200             continue;
201         error = error + line;
202
203     if dsc_whitespace_rules and inside_signature:
204         raise invalid_dsc_format_exc, index;
205
206     changes_in.close();
207     changes["filecontents"] = string.join (lines, "");
208
209     if error != "":
210         raise changes_parse_error_exc, error;
211
212     return changes;
213
214 ######################################################################################
215
216 # Dropped support for 1.4 and ``buggy dchanges 3.4'' (?!) compared to di.pl
217
218 def build_file_list(changes, dsc):
219     files = {}
220     format = changes.get("format", "")
221     if format != "":
222         format = float(format)
223     if dsc == "" and (format < 1.5 or format > 2.0):
224         raise nk_format_exc, format;
225
226     # No really, this has happened.  Think 0 length .dsc file.
227     if not changes.has_key("files"):
228         raise no_files_exc
229
230     for i in string.split(changes["files"], "\n"):
231         if i == "":
232             break
233         s = string.split(i)
234         section = priority = "";
235         try:
236             if dsc != "":
237                 (md5, size, name) = s
238             else:
239                 (md5, size, section, priority, name) = s
240         except ValueError:
241             raise changes_parse_error_exc, i
242
243         if section == "": section = "-"
244         if priority == "": priority = "-"
245
246         (section, component) = extract_component_from_section(section);
247
248         files[name] = { "md5sum" : md5,
249                         "size" : size,
250                         "section": section,
251                         "priority": priority,
252                         "component": component }
253
254     return files
255
256 ######################################################################################
257
258 # Fix the `Maintainer:' field to be an RFC822 compatible address.
259 # cf. Packaging Manual (4.2.4)
260 #
261 # 06:28|<Culus> 'The standard sucks, but my tool is supposed to
262 #                interoperate with it. I know - I'll fix the suckage
263 #                and make things incompatible!'
264
265 def fix_maintainer (maintainer):
266     m = re_parse_maintainer.match(maintainer);
267     rfc822 = maintainer
268     name = ""
269     email = ""
270     if m != None and len(m.groups()) == 2:
271         name = m.group(1)
272         email = m.group(2)
273         if string.find(name, ',') != -1 or string.find(name, '.') != -1:
274             rfc822 = re_parse_maintainer.sub(r"\2 (\1)", maintainer)
275     return (rfc822, name, email)
276
277 ######################################################################################
278
279 # sendmail wrapper, takes _either_ a message string or a file as arguments
280 def send_mail (message, filename):
281         #### FIXME, how do I get this out of Cnf in katie?
282         sendmail_command = "/usr/sbin/sendmail -odq -oi -t";
283
284         # Sanity check arguments
285         if message != "" and filename != "":
286             raise send_mail_invalid_args_exc;
287
288         # If we've been passed a string dump it into a temporary file
289         if message != "":
290             filename = tempfile.mktemp();
291             fd = os.open(filename, os.O_RDWR|os.O_CREAT|os.O_EXCL, 0700);
292             os.write (fd, message);
293             os.close (fd);
294
295         # Invoke sendmail
296         (result, output) = commands.getstatusoutput("%s < %s" % (sendmail_command, filename));
297         if (result != 0):
298             raise sendmail_failed_exc, output;
299
300         # Clean up any temporary files
301         if message !="":
302             os.unlink (filename);
303
304 ######################################################################################
305
306 def poolify (source, component):
307     if component != "":
308         component = component + '/';
309     # FIXME: this is nasty
310     component = string.lower(component);
311     component = string.replace(component, 'non-us/', 'non-US/');
312     if source[:3] == "lib":
313         return component + source[:4] + '/' + source + '/'
314     else:
315         return component + source[:1] + '/' + source + '/'
316
317 ######################################################################################
318
319 def move (src, dest, overwrite = 0):
320     if os.path.exists(dest) and os.path.isdir(dest):
321         dest_dir = dest;
322     else:
323         dest_dir = os.path.dirname(dest);
324     if not os.path.exists(dest_dir):
325         umask = os.umask(00000);
326         os.makedirs(dest_dir, 02775);
327         os.umask(umask);
328     #print "Moving %s to %s..." % (src, dest);
329     if os.path.exists(dest) and os.path.isdir(dest):
330         dest = dest + '/' + os.path.basename(src);
331     # Don't overwrite unless forced to
332     if os.path.exists(dest):
333         if not overwrite:
334             raise file_exists_exc;
335         else:
336             if not os.access(dest, os.W_OK):
337                 raise cant_overwrite_exc
338     shutil.copy2(src, dest);
339     os.chmod(dest, 0664);
340     os.unlink(src);
341
342 def copy (src, dest, overwrite = 0):
343     if os.path.exists(dest) and os.path.isdir(dest):
344         dest_dir = dest;
345     else:
346         dest_dir = os.path.dirname(dest);
347     if not os.path.exists(dest_dir):
348         umask = os.umask(00000);
349         os.makedirs(dest_dir, 02775);
350         os.umask(umask);
351     #print "Copying %s to %s..." % (src, dest);
352     if os.path.exists(dest) and os.path.isdir(dest):
353         dest = dest + '/' + os.path.basename(src);
354     # Don't overwrite unless forced to
355     if os.path.exists(dest):
356         if not overwrite:
357             raise file_exists_exc
358         else:
359             if not os.access(dest, os.W_OK):
360                 raise cant_overwrite_exc
361     shutil.copy2(src, dest);
362     os.chmod(dest, 0664);
363
364 ######################################################################################
365
366 def where_am_i ():
367     res = socket.gethostbyaddr(socket.gethostname());
368     database_hostname = DefaultCnf.get("Config::" + res[0] + "::DatabaseHostname");
369     if database_hostname:
370         return database_hostname;
371     else:
372         return res[0];
373
374 def which_conf_file ():
375     res = socket.gethostbyaddr(socket.gethostname());
376     if DefaultCnf.get("Config::" + res[0] + "::KatieConfig"):
377         return DefaultCnf["Config::" + res[0] + "::KatieConfig"]
378     else:
379         return default_config;
380
381 def which_apt_conf_file ():
382     res = socket.gethostbyaddr(socket.gethostname());
383     if DefaultCnf.get("Config::" + res[0] + "::AptConfig"):
384         return DefaultCnf["Config::" + res[0] + "::AptConfig"]
385     else:
386         return default_apt_config;
387
388 ######################################################################################
389
390 # Escape characters which have meaning to SQL's regex comparison operator ('~')
391 # (woefully incomplete)
392
393 def regex_safe (s):
394     s = string.replace(s, '+', '\\\\+');
395     s = string.replace(s, '.', '\\\\.');
396     return s
397
398 ######################################################################################
399
400 # Perform a substition of template
401 def TemplateSubst(Map,Template):
402     for x in Map.keys():
403         Template = string.replace(Template,x,Map[x]);
404     return Template;
405
406 ######################################################################################
407
408 def fubar(msg, exit_code=1):
409     sys.stderr.write("E: %s\n" % (msg));
410     sys.exit(exit_code);
411
412 def warn(msg):
413     sys.stderr.write("W: %s\n" % (msg));
414
415 ######################################################################################
416
417 # Returns the user name with a laughable attempt at rfc822 conformancy
418 # (read: removing stray periods).
419 def whoami ():
420     return string.replace(string.split(pwd.getpwuid(os.getuid())[4],',')[0], '.', '');
421
422 ######################################################################################
423
424 def size_type (c):
425     t  = " b";
426     if c > 10000:
427         c = c / 1000;
428         t = " Kb";
429     if c > 10000:
430         c = c / 1000;
431         t = " Mb";
432     return ("%d%s" % (c, t))
433
434 ################################################################################
435
436 def cc_fix_changes (changes):
437     o = changes.get("architecture", "")
438     if o != "":
439         del changes["architecture"]
440     changes["architecture"] = {}
441     for j in string.split(o):
442         changes["architecture"][j] = 1
443
444 # Sort by 'have source', by source name, by source version number, by filename
445
446 def changes_compare (a, b):
447     try:
448         a_changes = parse_changes(a, 0)
449     except:
450         return -1;
451
452     try:
453         b_changes = parse_changes(b, 0)
454     except:
455         return 1;
456
457     cc_fix_changes (a_changes);
458     cc_fix_changes (b_changes);
459
460     # Sort by 'have source'
461
462     a_has_source = a_changes["architecture"].get("source")
463     b_has_source = b_changes["architecture"].get("source")
464     if a_has_source and not b_has_source:
465         return -1;
466     elif b_has_source and not a_has_source:
467         return 1;
468
469     # Sort by source name
470
471     a_source = a_changes.get("source");
472     b_source = b_changes.get("source");
473     q = cmp (a_source, b_source);
474     if q:
475         return q;
476
477     # Sort by source version
478
479     a_version = a_changes.get("version");
480     b_version = b_changes.get("version");
481     q = apt_pkg.VersionCompare(a_version, b_version);
482     if q:
483         return q
484
485     # Fall back to sort by filename
486
487     return cmp(a, b);
488
489 ################################################################################
490
491 def find_next_free (dest, too_many=100):
492     extra = 0;
493     orig_dest = dest;
494     while os.path.exists(dest) and extra < too_many:
495         dest = orig_dest + '.' + repr(extra);
496         extra = extra + 1;
497     if extra >= too_many:
498         raise tried_too_hard_exc;
499     return dest;
500
501 ################################################################################
502
503 def result_join (original, sep = '\t'):
504     list = [];
505     for i in xrange(len(original)):
506         if original[i] == None:
507             list.append("");
508         else:
509             list.append(original[i]);
510     return string.join(list, sep);
511
512 ################################################################################