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