]> 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 hashfuncs = { 'MD5' : apt_pkg.md5sum,
112               'SHA1' : apt_pkg.sha1sum,
113               'SHA256' : apt_pkg.sha256sum }
114
115 def print_hash_files (tree, files, hashop):
116     path = Cnf["Dir::Root"] + tree + "/"
117     for name in files:
118         hashvalue = ""
119         hashlen = 0
120         try:
121             if name[0] == "<":
122                 j = name.index("/")
123                 k = name.index(">")
124                 (cat, ext, name) = (name[1:j], name[j+1:k], name[k+1:])
125                 file_handle = decompressors[ cat ]( "%s%s%s" % (path, name, ext) )
126                 contents = file_handle.read()
127                 hashvalue = hashfuncs[ hashop ](contents)
128                 hashlen = len(contents)
129             else:
130                 try:
131                     file_handle = utils.open_file(path + name)
132                     hashvalue = hashfuncs[ hashop ](file_handle)
133                     hashlen = os.stat(path + name).st_size
134                 except:
135                     raise
136                 else:
137                     if file_handle:
138                         file_handle.close()
139
140         except CantOpenError:
141             print "ALERT: Couldn't open " + path + name
142         except IOError:
143             print "ALERT: IOError when reading %s" % (path + name)
144             raise
145         else:
146             out.write(" %s %8d %s\n" % (hashvalue, hashlen, name))
147
148 def write_release_file (relpath, suite, component, origin, label, arch, version="", suite_suffix="", notautomatic="", butautomaticupgrades=""):
149     try:
150         if os.access(relpath, os.F_OK):
151             if os.stat(relpath).st_nlink > 1:
152                 os.unlink(relpath)
153         release = open(relpath, "w")
154     except IOError:
155         utils.fubar("Couldn't write to " + relpath)
156
157     release.write("Archive: %s\n" % (suite))
158     if version != "":
159         release.write("Version: %s\n" % (version))
160
161     if suite_suffix:
162         release.write("Component: %s/%s\n" % (suite_suffix,component))
163     else:
164         release.write("Component: %s\n" % (component))
165
166     release.write("Origin: %s\n" % (origin))
167     release.write("Label: %s\n" % (label))
168     if notautomatic != "":
169         release.write("NotAutomatic: %s\n" % (notautomatic))
170     if butautomaticupgrades != "":
171         release.write("ButAutomaticUpgrades: %s\n" % (butautomaticupgrades))
172     release.write("Architecture: %s\n" % (arch))
173     release.close()
174
175 ################################################################################
176
177 def main ():
178     global Cnf, AptCnf, out
179     out = sys.stdout
180
181     Cnf = utils.get_conf()
182     cnf = Config()
183
184     Arguments = [('h',"help","Generate-Releases::Options::Help"),
185                  ('a',"apt-conf","Generate-Releases::Options::Apt-Conf", "HasArg"),
186                  ('f',"force-touch","Generate-Releases::Options::Force-Touch"),
187                 ]
188     for i in [ "help", "apt-conf", "force-touch" ]:
189         if not Cnf.has_key("Generate-Releases::Options::%s" % (i)):
190             Cnf["Generate-Releases::Options::%s" % (i)] = ""
191
192     suites = apt_pkg.ParseCommandLine(Cnf,Arguments,sys.argv)
193     Options = Cnf.SubTree("Generate-Releases::Options")
194
195     if Options["Help"]:
196         usage()
197
198     if not Options["Apt-Conf"]:
199         Options["Apt-Conf"] = utils.which_apt_conf_file()
200
201     AptCnf = apt_pkg.newConfiguration()
202     apt_pkg.ReadConfigFileISC(AptCnf, Options["Apt-Conf"])
203
204     if not suites:
205         suites = Cnf.SubTree("Suite").List()
206
207     for suitename in suites:
208         print "Processing: " + suitename
209         SuiteBlock = Cnf.SubTree("Suite::" + suitename)
210         suiteobj = get_suite(suitename.lower())
211         if not suiteobj:
212             print "ALERT: Cannot find suite %s!" % (suitename.lower())
213             continue
214
215         # Use the canonical name
216         suite = suiteobj.suite_name.lower()
217
218         if suiteobj.untouchable and not Options["Force-Touch"]:
219             print "Skipping: " + suite + " (untouchable)"
220             continue
221
222         origin = suiteobj.origin
223         label = suiteobj.label or suiteobj.origin
224         codename = suiteobj.codename or ""
225         version = ""
226         if suiteobj.version and suiteobj.version != '-':
227             version = suiteobj.version
228         description = suiteobj.description or ""
229
230         architectures = get_suite_architectures(suite, skipall=True, skipsrc=True)
231
232         if suiteobj.notautomatic:
233             notautomatic = "yes"
234         else:
235             notautomatic = ""
236
237         if suiteobj.butautomaticupgrades:
238             butautomaticupgrades = "yes"
239         else:
240             butautomaticupgrades = ""
241
242         if SuiteBlock.has_key("Components"):
243             components = SuiteBlock.ValueList("Components")
244         else:
245             components = []
246
247         suite_suffix = Cnf.Find("Dinstall::SuiteSuffix")
248         if components and suite_suffix:
249             longsuite = suite + "/" + suite_suffix
250         else:
251             longsuite = suite
252
253         tree = SuiteBlock.get("Tree", "dists/%s" % (longsuite))
254
255         if AptCnf.has_key("tree::%s" % (tree)):
256             pass
257         elif AptCnf.has_key("bindirectory::%s" % (tree)):
258             pass
259         else:
260             aptcnf_filename = os.path.basename(utils.which_apt_conf_file())
261             print "ALERT: suite %s not in %s, nor untouchable!" % (suite, aptcnf_filename)
262             continue
263
264         print Cnf["Dir::Root"] + tree + "/Release"
265         out = open(Cnf["Dir::Root"] + tree + "/Release", "w")
266
267         out.write("Origin: %s\n" % (suiteobj.origin))
268         out.write("Label: %s\n" % (label))
269         out.write("Suite: %s\n" % (suite))
270         if version != "":
271             out.write("Version: %s\n" % (version))
272         if codename != "":
273             out.write("Codename: %s\n" % (codename))
274         out.write("Date: %s\n" % (time.strftime("%a, %d %b %Y %H:%M:%S UTC", time.gmtime(time.time()))))
275
276         if suiteobj.validtime:
277             validtime=float(suiteobj.validtime)
278             out.write("Valid-Until: %s\n" % (time.strftime("%a, %d %b %Y %H:%M:%S UTC", time.gmtime(time.time()+validtime))))
279
280         if notautomatic != "":
281             out.write("NotAutomatic: %s\n" % (notautomatic))
282         if butautomaticupgrades != "":
283             out.write("ButAutomaticUpgrades: %s\n" % (butautomaticupgrades))
284         out.write("Architectures: %s\n" % (" ".join([a.arch_string for a in architectures])))
285         if components:
286             out.write("Components: %s\n" % (" ".join(components)))
287
288         if description:
289             out.write("Description: %s\n" % (description))
290
291         files = []
292
293         if AptCnf.has_key("tree::%s" % (tree)):
294             if AptCnf.has_key("tree::%s::Contents" % (tree)):
295                 pass
296             else:
297                 for x in os.listdir("%s/%s" % (Cnf["Dir::Root"], tree)):
298                     if x.startswith('Contents-'):
299                         if x.endswith('.diff'):
300                             files.append("%s/Index" % (x))
301                         else:
302                             files.append(x)
303
304             for sec in AptCnf["tree::%s::Sections" % (tree)].split():
305                 for arch in AptCnf["tree::%s::Architectures" % (tree)].split():
306                     if arch == "source":
307                         filepath = "%s/%s/Sources" % (sec, arch)
308                         for cfile in compressnames("tree::%s" % (tree), "Sources", filepath):
309                             files.append(cfile)
310                         add_tiffani(files, Cnf["Dir::Root"] + tree, filepath)
311                     else:
312                         installer = "%s/installer-%s" % (sec, arch)
313                         installerpath = Cnf["Dir::Root"]+tree+"/"+installer
314                         if os.path.exists(installerpath):
315                             for directory in os.listdir(installerpath):
316                                 if os.path.exists("%s/%s/images/MD5SUMS" % (installerpath, directory)):
317                                     files.append("%s/%s/images/MD5SUMS" % (installer, directory))
318
319                         filepath = "%s/binary-%s/Packages" % (sec, arch)
320                         for cfile in compressnames("tree::%s" % (tree), "Packages", filepath):
321                             files.append(cfile)
322                         add_tiffani(files, Cnf["Dir::Root"] + tree, filepath)
323
324                     if arch == "source":
325                         rel = "%s/%s/Release" % (sec, arch)
326                     else:
327                         rel = "%s/binary-%s/Release" % (sec, arch)
328                     relpath = Cnf["Dir::Root"]+tree+"/"+rel
329                     write_release_file(relpath, suite, sec, origin, label, arch, version, suite_suffix, notautomatic, butautomaticupgrades)
330                     files.append(rel)
331                 gen_i18n_index(files, tree, sec)
332
333             if AptCnf.has_key("tree::%s/main" % (tree)):
334                 for dis in ["main", "contrib", "non-free"]:
335                     if not AptCnf.has_key("tree::%s/%s" % (tree, dis)): continue
336                     sec = AptCnf["tree::%s/%s::Sections" % (tree,dis)].split()[0]
337                     if sec != "debian-installer":
338                         print "ALERT: weird non debian-installer section in %s" % (tree)
339
340                     for arch in AptCnf["tree::%s/%s::Architectures" % (tree,dis)].split():
341                         if arch != "source":  # always true
342                             rel = "%s/%s/binary-%s/Release" % (dis, sec, arch)
343                             relpath = Cnf["Dir::Root"]+tree+"/"+rel
344                             write_release_file(relpath, suite, dis, origin, label, arch, version, suite_suffix, notautomatic, butautomaticupgrades)
345                             files.append(rel)
346                             for cfile in compressnames("tree::%s/%s" % (tree,dis),
347                                 "Packages",
348                                 "%s/%s/binary-%s/Packages" % (dis, sec, arch)):
349                                 files.append(cfile)
350             elif AptCnf.has_key("tree::%s::FakeDI" % (tree)):
351                 usetree = AptCnf["tree::%s::FakeDI" % (tree)]
352                 sec = AptCnf["tree::%s/main::Sections" % (usetree)].split()[0]
353                 if sec != "debian-installer":
354                     print "ALERT: weird non debian-installer section in %s" % (usetree)
355
356                 for arch in AptCnf["tree::%s/main::Architectures" % (usetree)].split():
357                     if arch != "source":  # always true
358                         for cfile in compressnames("tree::%s/main" % (usetree), "Packages", "main/%s/binary-%s/Packages" % (sec, arch)):
359                             files.append(cfile)
360
361         elif AptCnf.has_key("bindirectory::%s" % (tree)):
362             for cfile in compressnames("bindirectory::%s" % (tree), "Packages", AptCnf["bindirectory::%s::Packages" % (tree)]):
363                 files.append(cfile.replace(tree+"/","",1))
364             for cfile in compressnames("bindirectory::%s" % (tree), "Sources", AptCnf["bindirectory::%s::Sources" % (tree)]):
365                 files.append(cfile.replace(tree+"/","",1))
366         else:
367             print "ALERT: no tree/bindirectory for %s" % (tree)
368
369         for hashvalue in cnf.SubTree("Generate-Releases").List():
370             if suite in [ i.lower() for i in cnf.ValueList("Generate-Releases::%s" % (hashvalue)) ]:
371                 out.write("%s:\n" % (hashvalue))
372                 print_hash_files(tree, files, hashvalue)
373
374         out.close()
375         if Cnf.has_key("Dinstall::SigningKeyring"):
376             keyring = "--secret-keyring \"%s\"" % Cnf["Dinstall::SigningKeyring"]
377             if Cnf.has_key("Dinstall::SigningPubKeyring"):
378                 keyring += " --keyring \"%s\"" % Cnf["Dinstall::SigningPubKeyring"]
379
380             arguments = "--no-options --batch --no-tty --armour"
381             signkeyids=cnf.signingkeyids.split()
382
383             dest = Cnf["Dir::Root"] + tree + "/Release.gpg"
384             if os.path.exists(dest):
385                 os.unlink(dest)
386             inlinedest = Cnf["Dir::Root"] + tree + "/InRelease"
387             if os.path.exists(inlinedest):
388                 os.unlink(inlinedest)
389
390             for keyid in signkeyids:
391                 if keyid != "":
392                     defkeyid = "--default-key %s" % keyid
393                 else:
394                     defkeyid = ""
395                 os.system("gpg %s %s %s --detach-sign <%s >>%s" %
396                         (keyring, defkeyid, arguments,
397                         Cnf["Dir::Root"] + tree + "/Release", dest))
398                 os.system("gpg %s %s %s --clearsign <%s >>%s" %
399                         (keyring, defkeyid, arguments,
400                         Cnf["Dir::Root"] + tree + "/Release", inlinedest))
401
402 #######################################################################################
403
404 if __name__ == '__main__':
405     main()