]> 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 # 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, pg
26 import gzip, bz2
27 import apt_pkg
28 from daklib import utils
29 from daklib import database
30 from daklib.dak_exceptions import *
31
32 ################################################################################
33
34 Cnf = None
35 projectB = 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, projectB, 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     projectB = pg.connect(Cnf["DB::Name"], Cnf["DB::Host"], int(Cnf["DB::Port"]))
196     database.init(Cnf, projectB)
197
198     if not suites:
199         suites = Cnf.SubTree("Suite").List()
200
201     for suite in suites:
202         print "Processing: " + suite
203         SuiteBlock = Cnf.SubTree("Suite::" + suite)
204
205         if database.get_suite_untouchable(suite) and not Options["Force-Touch"]:
206             print "Skipping: " + suite + " (untouchable)"
207             continue
208
209         suite = suite.lower()
210
211         origin = SuiteBlock["Origin"]
212         label = SuiteBlock.get("Label", origin)
213         codename = SuiteBlock.get("CodeName", "")
214
215         version = ""
216         description = ""
217
218         q = projectB.query("SELECT version, description FROM suite WHERE suite_name = '%s'" % (suite))
219         qs = q.getresult()
220         if len(qs) == 1:
221             if qs[0][0] != "-": version = qs[0][0]
222             if qs[0][1]: description = qs[0][1]
223
224         architectures = database.get_suite_architectures(suite)
225         if architectures == None:
226             architectures = []
227
228         if SuiteBlock.has_key("NotAutomatic"):
229             notautomatic = "yes"
230         else:
231             notautomatic = ""
232
233         if SuiteBlock.has_key("Components"):
234             components = SuiteBlock.ValueList("Components")
235         else:
236             components = []
237
238         suite_suffix = Cnf.Find("Dinstall::SuiteSuffix")
239         if components and suite_suffix:
240             longsuite = suite + "/" + suite_suffix
241         else:
242             longsuite = suite
243
244         tree = SuiteBlock.get("Tree", "dists/%s" % (longsuite))
245
246         if AptCnf.has_key("tree::%s" % (tree)):
247             pass
248         elif AptCnf.has_key("bindirectory::%s" % (tree)):
249             pass
250         else:
251             aptcnf_filename = os.path.basename(utils.which_apt_conf_file())
252             print "ALERT: suite %s not in %s, nor untouchable!" % (suite, aptcnf_filename)
253             continue
254
255         print Cnf["Dir::Root"] + tree + "/Release"
256         out = open(Cnf["Dir::Root"] + tree + "/Release", "w")
257
258         out.write("Origin: %s\n" % (origin))
259         out.write("Label: %s\n" % (label))
260         out.write("Suite: %s\n" % (suite))
261         if version != "":
262             out.write("Version: %s\n" % (version))
263         if codename != "":
264             out.write("Codename: %s\n" % (codename))
265         out.write("Date: %s\n" % (time.strftime("%a, %d %b %Y %H:%M:%S UTC", time.gmtime(time.time()))))
266
267         if SuiteBlock.has_key("ValidTime"):
268             validtime=float(SuiteBlock["ValidTime"])
269             out.write("Valid-Until: %s\n" % (time.strftime("%a, %d %b %Y %H:%M:%S UTC", time.gmtime(time.time()+validtime))))
270
271         if notautomatic != "":
272             out.write("NotAutomatic: %s\n" % (notautomatic))
273         out.write("Architectures: %s\n" % (" ".join(filter(utils.real_arch, architectures))))
274         if components:
275             out.write("Components: %s\n" % (" ".join(components)))
276
277         if description:
278             out.write("Description: %s\n" % (description))
279
280         files = []
281
282         if AptCnf.has_key("tree::%s" % (tree)):
283             if AptCnf.has_key("tree::%s::Contents" % (tree)):
284                 pass
285             else:
286                 for x in os.listdir("%s/%s" % (Cnf["Dir::Root"], tree)):
287                     if x.startswith('Contents-'):
288                         if x.endswith('.diff'):
289                             files.append("%s/Index" % (x))
290                         else:
291                             files.append(x)
292
293             for sec in AptCnf["tree::%s::Sections" % (tree)].split():
294                 for arch in AptCnf["tree::%s::Architectures" % (tree)].split():
295                     if arch == "source":
296                         filepath = "%s/%s/Sources" % (sec, arch)
297                         for cfile in compressnames("tree::%s" % (tree), "Sources", filepath):
298                             files.append(cfile)
299                         add_tiffani(files, Cnf["Dir::Root"] + tree, filepath)
300                     else:
301                         disks = "%s/disks-%s" % (sec, arch)
302                         diskspath = Cnf["Dir::Root"]+tree+"/"+disks
303                         if os.path.exists(diskspath):
304                             for dir in os.listdir(diskspath):
305                                 if os.path.exists("%s/%s/md5sum.txt" % (diskspath, dir)):
306                                     files.append("%s/%s/md5sum.txt" % (disks, dir))
307
308                         filepath = "%s/binary-%s/Packages" % (sec, arch)
309                         for cfile in compressnames("tree::%s" % (tree), "Packages", filepath):
310                             files.append(cfile)
311                         add_tiffani(files, Cnf["Dir::Root"] + tree, filepath)
312
313                     if arch == "source":
314                         rel = "%s/%s/Release" % (sec, arch)
315                     else:
316                         rel = "%s/binary-%s/Release" % (sec, arch)
317                     relpath = Cnf["Dir::Root"]+tree+"/"+rel
318                     write_release_file(relpath, suite, sec, origin, label, arch, version, suite_suffix, notautomatic)
319                     files.append(rel)
320                 gen_i18n_index(files, tree, sec)
321
322             if AptCnf.has_key("tree::%s/main" % (tree)):
323                 for dis in ["main", "contrib", "non-free"]:
324                     if not AptCnf.has_key("tree::%s/%s" % (tree, dis)): continue
325                     sec = AptCnf["tree::%s/%s::Sections" % (tree,dis)].split()[0]
326                     if sec != "debian-installer":
327                         print "ALERT: weird non debian-installer section in %s" % (tree)
328
329                     for arch in AptCnf["tree::%s/%s::Architectures" % (tree,dis)].split():
330                         if arch != "source":  # always true
331                             rel = "%s/%s/binary-%s/Release" % (dis, sec, arch)
332                             relpath = Cnf["Dir::Root"]+tree+"/"+rel
333                             write_release_file(relpath, suite, dis, origin, label, arch, version, suite_suffix, notautomatic)
334                             files.append(rel)
335                             for cfile in compressnames("tree::%s/%s" % (tree,dis),
336                                 "Packages",
337                                 "%s/%s/binary-%s/Packages" % (dis, sec, arch)):
338                                 files.append(cfile)
339             elif AptCnf.has_key("tree::%s::FakeDI" % (tree)):
340                 usetree = AptCnf["tree::%s::FakeDI" % (tree)]
341                 sec = AptCnf["tree::%s/main::Sections" % (usetree)].split()[0]
342                 if sec != "debian-installer":
343                     print "ALERT: weird non debian-installer section in %s" % (usetree)
344
345                 for arch in AptCnf["tree::%s/main::Architectures" % (usetree)].split():
346                     if arch != "source":  # always true
347                         for cfile in compressnames("tree::%s/main" % (usetree), "Packages", "main/%s/binary-%s/Packages" % (sec, arch)):
348                             files.append(cfile)
349
350         elif AptCnf.has_key("bindirectory::%s" % (tree)):
351             for cfile in compressnames("bindirectory::%s" % (tree), "Packages", AptCnf["bindirectory::%s::Packages" % (tree)]):
352                 files.append(cfile.replace(tree+"/","",1))
353             for cfile in compressnames("bindirectory::%s" % (tree), "Sources", AptCnf["bindirectory::%s::Sources" % (tree)]):
354                 files.append(cfile.replace(tree+"/","",1))
355         else:
356             print "ALERT: no tree/bindirectory for %s" % (tree)
357
358         out.write("MD5Sum:\n")
359         print_md5_files(tree, files)
360         out.write("SHA1:\n")
361         print_sha1_files(tree, files)
362         out.write("SHA256:\n")
363         print_sha256_files(tree, files)
364
365         out.close()
366         if Cnf.has_key("Dinstall::SigningKeyring"):
367             keyring = "--secret-keyring \"%s\"" % Cnf["Dinstall::SigningKeyring"]
368             if Cnf.has_key("Dinstall::SigningPubKeyring"):
369                 keyring += " --keyring \"%s\"" % Cnf["Dinstall::SigningPubKeyring"]
370
371             arguments = "--no-options --batch --no-tty --armour"
372             if Cnf.has_key("Dinstall::SigningKeyIds"):
373                 signkeyids = Cnf["Dinstall::SigningKeyIds"].split()
374             else:
375                 signkeyids = [""]
376
377             dest = Cnf["Dir::Root"] + tree + "/Release.gpg"
378             if os.path.exists(dest):
379                 os.unlink(dest)
380
381             for keyid in signkeyids:
382                 if keyid != "": defkeyid = "--default-key %s" % keyid
383                 else: defkeyid = ""
384                 os.system("gpg %s %s %s --detach-sign <%s >>%s" %
385                         (keyring, defkeyid, arguments,
386                         Cnf["Dir::Root"] + tree + "/Release", dest))
387
388 #######################################################################################
389
390 if __name__ == '__main__':
391     main()