]> git.decadent.org.uk Git - dak.git/blob - dak/generate_releases.py
Merge commit 'lamby/master' into merge
[dak.git] / dak / generate_releases.py
1 #!/usr/bin/env python
2
3 """ Create all the Release files """
4
5 # Copyright (C) 2001, 2002, 2006  Anthony Towns <ajt@debian.org>
6
7 # This program is free software; you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 2 of the License, or
10 # (at your option) any later version.
11
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 # GNU General Public License for more details.
16
17 # You should have received a copy of the GNU General Public License
18 # along with this program; if not, write to the Free Software
19 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20
21 #   ``Bored now''
22
23 ################################################################################
24
25 import sys, os, stat, time
26 import gzip, bz2
27 import apt_pkg
28
29 from daklib import utils
30 from daklib.dak_exceptions import *
31 from daklib.dbconn import *
32
33 ################################################################################
34
35 Cnf = None
36 out = None
37 AptCnf = None
38
39 ################################################################################
40
41 def usage (exit_code=0):
42     print """Usage: dak generate-releases [OPTION]... [SUITE]...
43 Generate Release files (for SUITE).
44
45   -h, --help                 show this help and exit
46   -a, --apt-conf FILE        use FILE instead of default apt.conf
47   -f, --force-touch          ignore Untouchable directives in dak.conf
48
49 If no SUITE is given Release files are generated for all suites."""
50
51     sys.exit(exit_code)
52
53 ################################################################################
54
55 def add_tiffani (files, path, indexstem):
56     index = "%s.diff/Index" % (indexstem)
57     filepath = "%s/%s" % (path, index)
58     if os.path.exists(filepath):
59         #print "ALERT: there was a tiffani file %s" % (filepath)
60         files.append(index)
61
62 def gen_i18n_index (files, tree, sec):
63     path = Cnf["Dir::Root"] + tree + "/"
64     i18n_path = "%s/i18n" % (sec)
65     if os.path.exists("%s/%s" % (path, i18n_path)):
66         index = "%s/Index" % (i18n_path)
67         out = open("%s/%s" % (path, index), "w")
68         out.write("SHA1:\n")
69         for x in os.listdir("%s/%s" % (path, i18n_path)):
70             if x.startswith('Translation-'):
71                 f = open("%s/%s/%s" % (path, i18n_path, x), "r")
72                 size = os.fstat(f.fileno())[6]
73                 f.seek(0)
74                 sha1sum = apt_pkg.sha1sum(f)
75                 f.close()
76                 out.write(" %s %7d %s\n" % (sha1sum, size, x))
77         out.close()
78         files.append(index)
79
80 def compressnames (tree,type,file):
81     compress = AptCnf.get("%s::%s::Compress" % (tree,type), AptCnf.get("Default::%s::Compress" % (type), ". gzip"))
82     result = []
83     cl = compress.split()
84     uncompress = ("." not in cl)
85     for mode in compress.split():
86         if mode == ".":
87             result.append(file)
88         elif mode == "gzip":
89             if uncompress:
90                 result.append("<zcat/.gz>" + file)
91                 uncompress = 0
92             result.append(file + ".gz")
93         elif mode == "bzip2":
94             if uncompress:
95                 result.append("<bzcat/.bz2>" + file)
96                 uncompress = 0
97             result.append(file + ".bz2")
98     return result
99
100 decompressors = { 'zcat' : gzip.GzipFile,
101                   'bzip2' : bz2.BZ2File }
102
103 def print_md5sha_files (tree, files, hashop):
104     path = Cnf["Dir::Root"] + tree + "/"
105     for name in files:
106         hashvalue = ""
107         hashlen = 0
108         try:
109             if name[0] == "<":
110                 j = name.index("/")
111                 k = name.index(">")
112                 (cat, ext, name) = (name[1:j], name[j+1:k], name[k+1:])
113                 file_handle = decompressors[ cat ]( "%s%s%s" % (path, name, ext) )
114                 contents = file_handle.read()
115                 hashvalue = hashop(contents)
116                 hashlen = len(contents)
117             else:
118                 try:
119                     file_handle = utils.open_file(path + name)
120                     hashvalue = hashop(file_handle)
121                     hashlen = os.stat(path + name).st_size
122                 except:
123                     raise
124                 else:
125                     if file_handle:
126                         file_handle.close()
127
128         except CantOpenError:
129             print "ALERT: Couldn't open " + path + name
130         else:
131             out.write(" %s %8d %s\n" % (hashvalue, hashlen, name))
132
133 def print_md5_files (tree, files):
134     print_md5sha_files (tree, files, apt_pkg.md5sum)
135
136 def print_sha1_files (tree, files):
137     print_md5sha_files (tree, files, apt_pkg.sha1sum)
138
139 def print_sha256_files (tree, files):
140     print_md5sha_files (tree, files, apt_pkg.sha256sum)
141
142 def write_release_file (relpath, suite, component, origin, label, arch, version="", suite_suffix="", notautomatic=""):
143     try:
144         if os.access(relpath, os.F_OK):
145             if os.stat(relpath).st_nlink > 1:
146                 os.unlink(relpath)
147         release = open(relpath, "w")
148     except IOError:
149         utils.fubar("Couldn't write to " + relpath)
150
151     release.write("Archive: %s\n" % (suite))
152     if version != "":
153         release.write("Version: %s\n" % (version))
154
155     if suite_suffix:
156         release.write("Component: %s/%s\n" % (suite_suffix,component))
157     else:
158         release.write("Component: %s\n" % (component))
159
160     release.write("Origin: %s\n" % (origin))
161     release.write("Label: %s\n" % (label))
162     if notautomatic != "":
163         release.write("NotAutomatic: %s\n" % (notautomatic))
164     release.write("Architecture: %s\n" % (arch))
165     release.close()
166
167 ################################################################################
168
169 def main ():
170     global Cnf, AptCnf, out
171     out = sys.stdout
172
173     Cnf = utils.get_conf()
174
175     Arguments = [('h',"help","Generate-Releases::Options::Help"),
176                  ('a',"apt-conf","Generate-Releases::Options::Apt-Conf", "HasArg"),
177                  ('f',"force-touch","Generate-Releases::Options::Force-Touch"),
178                 ]
179     for i in [ "help", "apt-conf", "force-touch" ]:
180         if not Cnf.has_key("Generate-Releases::Options::%s" % (i)):
181             Cnf["Generate-Releases::Options::%s" % (i)] = ""
182
183     suites = apt_pkg.ParseCommandLine(Cnf,Arguments,sys.argv)
184     Options = Cnf.SubTree("Generate-Releases::Options")
185
186     if Options["Help"]:
187         usage()
188
189     if not Options["Apt-Conf"]:
190         Options["Apt-Conf"] = utils.which_apt_conf_file()
191
192     AptCnf = apt_pkg.newConfiguration()
193     apt_pkg.ReadConfigFileISC(AptCnf, Options["Apt-Conf"])
194
195     if not suites:
196         suites = Cnf.SubTree("Suite").List()
197
198     for suitename in suites:
199         print "Processing: " + suitename
200         SuiteBlock = Cnf.SubTree("Suite::" + suitename)
201         suiteobj = get_suite(suitename.lower())
202         if not suiteobj:
203             print "ALERT: Cannot find suite %s!" % (suitename.lower())
204             continue
205
206         # Use the canonical name
207         suite = suiteobj.suite_name.lower()
208
209         if suiteobj.untouchable and not Options["Force-Touch"]:
210             print "Skipping: " + suite + " (untouchable)"
211             continue
212
213         origin = suiteobj.origin
214         label = suiteobj.label or suiteobj.origin
215         codename = suiteobj.codename or ""
216         version = ""
217         if suiteobj.version and suiteobj.version != '-':
218             version = suiteobj.version
219         description = suiteobj.description or ""
220
221         architectures = get_suite_architectures(suite, skipall=True, skipsrc=True)
222
223         if SuiteBlock.has_key("NotAutomatic"):
224             notautomatic = "yes"
225         else:
226             notautomatic = ""
227
228         if SuiteBlock.has_key("Components"):
229             components = SuiteBlock.ValueList("Components")
230         else:
231             components = []
232
233         suite_suffix = Cnf.Find("Dinstall::SuiteSuffix")
234         if components and suite_suffix:
235             longsuite = suite + "/" + suite_suffix
236         else:
237             longsuite = suite
238
239         tree = SuiteBlock.get("Tree", "dists/%s" % (longsuite))
240
241         if AptCnf.has_key("tree::%s" % (tree)):
242             pass
243         elif AptCnf.has_key("bindirectory::%s" % (tree)):
244             pass
245         else:
246             aptcnf_filename = os.path.basename(utils.which_apt_conf_file())
247             print "ALERT: suite %s not in %s, nor untouchable!" % (suite, aptcnf_filename)
248             continue
249
250         print Cnf["Dir::Root"] + tree + "/Release"
251         out = open(Cnf["Dir::Root"] + tree + "/Release", "w")
252
253         out.write("Origin: %s\n" % (suiteobj.origin))
254         out.write("Label: %s\n" % (label))
255         out.write("Suite: %s\n" % (suite))
256         if version != "":
257             out.write("Version: %s\n" % (version))
258         if codename != "":
259             out.write("Codename: %s\n" % (codename))
260         out.write("Date: %s\n" % (time.strftime("%a, %d %b %Y %H:%M:%S UTC", time.gmtime(time.time()))))
261
262         if SuiteBlock.has_key("ValidTime"):
263             validtime=float(SuiteBlock["ValidTime"])
264             out.write("Valid-Until: %s\n" % (time.strftime("%a, %d %b %Y %H:%M:%S UTC", time.gmtime(time.time()+validtime))))
265
266         if notautomatic != "":
267             out.write("NotAutomatic: %s\n" % (notautomatic))
268         out.write("Architectures: %s\n" % (" ".join([a.arch_string for a in architectures])))
269         if components:
270             out.write("Components: %s\n" % (" ".join(components)))
271
272         if description:
273             out.write("Description: %s\n" % (description))
274
275         files = []
276
277         if AptCnf.has_key("tree::%s" % (tree)):
278             if AptCnf.has_key("tree::%s::Contents" % (tree)):
279                 pass
280             else:
281                 for x in os.listdir("%s/%s" % (Cnf["Dir::Root"], tree)):
282                     if x.startswith('Contents-'):
283                         if x.endswith('.diff'):
284                             files.append("%s/Index" % (x))
285                         else:
286                             files.append(x)
287
288             for sec in AptCnf["tree::%s::Sections" % (tree)].split():
289                 for arch in AptCnf["tree::%s::Architectures" % (tree)].split():
290                     if arch == "source":
291                         filepath = "%s/%s/Sources" % (sec, arch)
292                         for cfile in compressnames("tree::%s" % (tree), "Sources", filepath):
293                             files.append(cfile)
294                         add_tiffani(files, Cnf["Dir::Root"] + tree, filepath)
295                     else:
296                         disks = "%s/disks-%s" % (sec, arch)
297                         diskspath = Cnf["Dir::Root"]+tree+"/"+disks
298                         if os.path.exists(diskspath):
299                             for dir in os.listdir(diskspath):
300                                 if os.path.exists("%s/%s/md5sum.txt" % (diskspath, dir)):
301                                     files.append("%s/%s/md5sum.txt" % (disks, dir))
302
303                         filepath = "%s/binary-%s/Packages" % (sec, arch)
304                         for cfile in compressnames("tree::%s" % (tree), "Packages", filepath):
305                             files.append(cfile)
306                         add_tiffani(files, Cnf["Dir::Root"] + tree, filepath)
307
308                     if arch == "source":
309                         rel = "%s/%s/Release" % (sec, arch)
310                     else:
311                         rel = "%s/binary-%s/Release" % (sec, arch)
312                     relpath = Cnf["Dir::Root"]+tree+"/"+rel
313                     write_release_file(relpath, suite, sec, origin, label, arch, version, suite_suffix, notautomatic)
314                     files.append(rel)
315                 gen_i18n_index(files, tree, sec)
316
317             if AptCnf.has_key("tree::%s/main" % (tree)):
318                 for dis in ["main", "contrib", "non-free"]:
319                     if not AptCnf.has_key("tree::%s/%s" % (tree, dis)): continue
320                     sec = AptCnf["tree::%s/%s::Sections" % (tree,dis)].split()[0]
321                     if sec != "debian-installer":
322                         print "ALERT: weird non debian-installer section in %s" % (tree)
323
324                     for arch in AptCnf["tree::%s/%s::Architectures" % (tree,dis)].split():
325                         if arch != "source":  # always true
326                             rel = "%s/%s/binary-%s/Release" % (dis, sec, arch)
327                             relpath = Cnf["Dir::Root"]+tree+"/"+rel
328                             write_release_file(relpath, suite, dis, origin, label, arch, version, suite_suffix, notautomatic)
329                             files.append(rel)
330                             for cfile in compressnames("tree::%s/%s" % (tree,dis),
331                                 "Packages",
332                                 "%s/%s/binary-%s/Packages" % (dis, sec, arch)):
333                                 files.append(cfile)
334             elif AptCnf.has_key("tree::%s::FakeDI" % (tree)):
335                 usetree = AptCnf["tree::%s::FakeDI" % (tree)]
336                 sec = AptCnf["tree::%s/main::Sections" % (usetree)].split()[0]
337                 if sec != "debian-installer":
338                     print "ALERT: weird non debian-installer section in %s" % (usetree)
339
340                 for arch in AptCnf["tree::%s/main::Architectures" % (usetree)].split():
341                     if arch != "source":  # always true
342                         for cfile in compressnames("tree::%s/main" % (usetree), "Packages", "main/%s/binary-%s/Packages" % (sec, arch)):
343                             files.append(cfile)
344
345         elif AptCnf.has_key("bindirectory::%s" % (tree)):
346             for cfile in compressnames("bindirectory::%s" % (tree), "Packages", AptCnf["bindirectory::%s::Packages" % (tree)]):
347                 files.append(cfile.replace(tree+"/","",1))
348             for cfile in compressnames("bindirectory::%s" % (tree), "Sources", AptCnf["bindirectory::%s::Sources" % (tree)]):
349                 files.append(cfile.replace(tree+"/","",1))
350         else:
351             print "ALERT: no tree/bindirectory for %s" % (tree)
352
353         out.write("MD5Sum:\n")
354         print_md5_files(tree, files)
355         out.write("SHA1:\n")
356         print_sha1_files(tree, files)
357         out.write("SHA256:\n")
358         print_sha256_files(tree, files)
359
360         out.close()
361         if Cnf.has_key("Dinstall::SigningKeyring"):
362             keyring = "--secret-keyring \"%s\"" % Cnf["Dinstall::SigningKeyring"]
363             if Cnf.has_key("Dinstall::SigningPubKeyring"):
364                 keyring += " --keyring \"%s\"" % Cnf["Dinstall::SigningPubKeyring"]
365
366             arguments = "--no-options --batch --no-tty --armour"
367             if Cnf.has_key("Dinstall::SigningKeyIds"):
368                 signkeyids = Cnf["Dinstall::SigningKeyIds"].split()
369             else:
370                 signkeyids = [""]
371
372             dest = Cnf["Dir::Root"] + tree + "/Release.gpg"
373             if os.path.exists(dest):
374                 os.unlink(dest)
375
376             for keyid in signkeyids:
377                 if keyid != "": defkeyid = "--default-key %s" % keyid
378                 else: defkeyid = ""
379                 os.system("gpg %s %s %s --detach-sign <%s >>%s" %
380                         (keyring, defkeyid, arguments,
381                         Cnf["Dir::Root"] + tree + "/Release", dest))
382
383 #######################################################################################
384
385 if __name__ == '__main__':
386     main()