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