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