]> git.decadent.org.uk Git - dak.git/blob - dak/generate_releases.py
Merge commit 'ftpmaster/master'
[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 compressnames (tree,type,file):
63     compress = AptCnf.get("%s::%s::Compress" % (tree,type), AptCnf.get("Default::%s::Compress" % (type), ". gzip"))
64     result = []
65     cl = compress.split()
66     uncompress = ("." not in cl)
67     for mode in compress.split():
68         if mode == ".":
69             result.append(file)
70         elif mode == "gzip":
71             if uncompress:
72                 result.append("<zcat/.gz>" + file)
73                 uncompress = 0
74             result.append(file + ".gz")
75         elif mode == "bzip2":
76             if uncompress:
77                 result.append("<bzcat/.bz2>" + file)
78                 uncompress = 0
79             result.append(file + ".bz2")
80     return result
81
82 decompressors = { 'zcat' : gzip.GzipFile,
83                   'bzip2' : bz2.BZ2File }
84
85 def print_md5sha_files (tree, files, hashop):
86     path = Cnf["Dir::Root"] + tree + "/"
87     for name in files:
88         hashvalue = ""
89         hashlen = 0
90         try:
91             if name[0] == "<":
92                 j = name.index("/")
93                 k = name.index(">")
94                 (cat, ext, name) = (name[1:j], name[j+1:k], name[k+1:])
95                 file_handle = decompressors[ cat ]( "%s%s%s" % (path, name, ext) )
96                 contents = file_handle.read()
97                 hashvalue = hashop(contents)
98                 hashlen = len(contents)
99             else:
100                 try:
101                     file_handle = utils.open_file(path + name)
102                     hashvalue = hashop(file_handle)
103                     hashlen = os.stat(path + name).st_size
104                 except:
105                     raise
106                 else:
107                     if file_handle:
108                         file_handle.close()
109
110         except CantOpenError:
111             print "ALERT: Couldn't open " + path + name
112         else:
113             out.write(" %s %8d %s\n" % (hashvalue, hashlen, name))
114
115 def print_md5_files (tree, files):
116     print_md5sha_files (tree, files, apt_pkg.md5sum)
117
118 def print_sha1_files (tree, files):
119     print_md5sha_files (tree, files, apt_pkg.sha1sum)
120
121 def print_sha256_files (tree, files):
122     print_md5sha_files (tree, files, apt_pkg.sha256sum)
123
124 def write_release_file (relpath, suite, component, origin, label, arch, version="", suite_suffix="", notautomatic=""):
125     try:
126         if os.access(relpath, os.F_OK):
127             if os.stat(relpath).st_nlink > 1:
128                 os.unlink(relpath)
129         release = open(relpath, "w")
130     except IOError:
131         utils.fubar("Couldn't write to " + relpath)
132
133     release.write("Archive: %s\n" % (suite))
134     if version != "":
135         release.write("Version: %s\n" % (version))
136
137     if suite_suffix:
138         release.write("Component: %s/%s\n" % (suite_suffix,component))
139     else:
140         release.write("Component: %s\n" % (component))
141
142     release.write("Origin: %s\n" % (origin))
143     release.write("Label: %s\n" % (label))
144     if notautomatic != "":
145         release.write("NotAutomatic: %s\n" % (notautomatic))
146     release.write("Architecture: %s\n" % (arch))
147     release.close()
148
149 ################################################################################
150
151 def main ():
152     global Cnf, AptCnf, projectB, out
153     out = sys.stdout
154
155     Cnf = utils.get_conf()
156
157     Arguments = [('h',"help","Generate-Releases::Options::Help"),
158                  ('a',"apt-conf","Generate-Releases::Options::Apt-Conf", "HasArg"),
159                  ('f',"force-touch","Generate-Releases::Options::Force-Touch"),
160                 ]
161     for i in [ "help", "apt-conf", "force-touch" ]:
162         if not Cnf.has_key("Generate-Releases::Options::%s" % (i)):
163             Cnf["Generate-Releases::Options::%s" % (i)] = ""
164
165     suites = apt_pkg.ParseCommandLine(Cnf,Arguments,sys.argv)
166     Options = Cnf.SubTree("Generate-Releases::Options")
167
168     if Options["Help"]:
169         usage()
170
171     if not Options["Apt-Conf"]:
172         Options["Apt-Conf"] = utils.which_apt_conf_file()
173
174     AptCnf = apt_pkg.newConfiguration()
175     apt_pkg.ReadConfigFileISC(AptCnf, Options["Apt-Conf"])
176
177     projectB = pg.connect(Cnf["DB::Name"], Cnf["DB::Host"], int(Cnf["DB::Port"]))
178     database.init(Cnf, projectB)
179
180     if not suites:
181         suites = Cnf.SubTree("Suite").List()
182
183     for suite in suites:
184         print "Processing: " + suite
185         SuiteBlock = Cnf.SubTree("Suite::" + suite)
186
187         if database.get_suite_untouchable(suite) and not Options["Force-Touch"]:
188             print "Skipping: " + suite + " (untouchable)"
189             continue
190
191         suite = suite.lower()
192
193         origin = SuiteBlock["Origin"]
194         label = SuiteBlock.get("Label", origin)
195         codename = SuiteBlock.get("CodeName", "")
196
197         version = ""
198         description = ""
199
200         q = projectB.query("SELECT version, description FROM suite WHERE suite_name = '%s'" % (suite))
201         qs = q.getresult()
202         if len(qs) == 1:
203             if qs[0][0] != "-": version = qs[0][0]
204             if qs[0][1]: description = qs[0][1]
205
206         architectures = database.get_suite_architectures(suite)
207         if architectures == None:
208             architectures = []
209
210         if SuiteBlock.has_key("NotAutomatic"):
211             notautomatic = "yes"
212         else:
213             notautomatic = ""
214
215         if SuiteBlock.has_key("Components"):
216             components = SuiteBlock.ValueList("Components")
217         else:
218             components = []
219
220         suite_suffix = Cnf.Find("Dinstall::SuiteSuffix")
221         if components and suite_suffix:
222             longsuite = suite + "/" + suite_suffix
223         else:
224             longsuite = suite
225
226         tree = SuiteBlock.get("Tree", "dists/%s" % (longsuite))
227
228         if AptCnf.has_key("tree::%s" % (tree)):
229             pass
230         elif AptCnf.has_key("bindirectory::%s" % (tree)):
231             pass
232         else:
233             aptcnf_filename = os.path.basename(utils.which_apt_conf_file())
234             print "ALERT: suite %s not in %s, nor untouchable!" % (suite, aptcnf_filename)
235             continue
236
237         print Cnf["Dir::Root"] + tree + "/Release"
238         out = open(Cnf["Dir::Root"] + tree + "/Release", "w")
239
240         out.write("Origin: %s\n" % (origin))
241         out.write("Label: %s\n" % (label))
242         out.write("Suite: %s\n" % (suite))
243         if version != "":
244             out.write("Version: %s\n" % (version))
245         if codename != "":
246             out.write("Codename: %s\n" % (codename))
247         out.write("Date: %s\n" % (time.strftime("%a, %d %b %Y %H:%M:%S UTC", time.gmtime(time.time()))))
248
249         if SuiteBlock.has_key("ValidTime"):
250             validtime=float(SuiteBlock["ValidTime"])
251             out.write("Valid-Until: %s\n" % (time.strftime("%a, %d %b %Y %H:%M:%S UTC", time.gmtime(time.time()+validtime))))
252
253         if notautomatic != "":
254             out.write("NotAutomatic: %s\n" % (notautomatic))
255         out.write("Architectures: %s\n" % (" ".join(filter(utils.real_arch, architectures))))
256         if components:
257             out.write("Components: %s\n" % (" ".join(components)))
258
259         if description:
260             out.write("Description: %s\n" % (description))
261
262         files = []
263
264         if AptCnf.has_key("tree::%s" % (tree)):
265             if AptCnf.has_key("tree::%s::Contents" % (tree)):
266                 pass
267             else:
268                 for x in os.listdir("%s/%s" % (Cnf["Dir::Root"], tree)):
269                     if x.startswith('Contents-'):
270                         files.append(x)
271
272             for sec in AptCnf["tree::%s::Sections" % (tree)].split():
273                 for arch in AptCnf["tree::%s::Architectures" % (tree)].split():
274                     if arch == "source":
275                         filepath = "%s/%s/Sources" % (sec, arch)
276                         for cfile in compressnames("tree::%s" % (tree), "Sources", filepath):
277                             files.append(cfile)
278                         add_tiffani(files, Cnf["Dir::Root"] + tree, filepath)
279                     else:
280                         disks = "%s/disks-%s" % (sec, arch)
281                         diskspath = Cnf["Dir::Root"]+tree+"/"+disks
282                         if os.path.exists(diskspath):
283                             for dir in os.listdir(diskspath):
284                                 if os.path.exists("%s/%s/md5sum.txt" % (diskspath, dir)):
285                                     files.append("%s/%s/md5sum.txt" % (disks, dir))
286
287                         filepath = "%s/binary-%s/Packages" % (sec, arch)
288                         for cfile in compressnames("tree::%s" % (tree), "Packages", filepath):
289                             files.append(cfile)
290                         add_tiffani(files, Cnf["Dir::Root"] + tree, filepath)
291
292                     if arch == "source":
293                         rel = "%s/%s/Release" % (sec, arch)
294                     else:
295                         rel = "%s/binary-%s/Release" % (sec, arch)
296                     relpath = Cnf["Dir::Root"]+tree+"/"+rel
297                     write_release_file(relpath, suite, sec, origin, label, arch, version, suite_suffix, notautomatic)
298                     files.append(rel)
299
300             if AptCnf.has_key("tree::%s/main" % (tree)):
301                 for dis in ["main", "contrib", "non-free"]:
302                     if not AptCnf.has_key("tree::%s/%s" % (tree, dis)): continue
303                     sec = AptCnf["tree::%s/%s::Sections" % (tree,dis)].split()[0]
304                     if sec != "debian-installer":
305                         print "ALERT: weird non debian-installer section in %s" % (tree)
306
307                     for arch in AptCnf["tree::%s/%s::Architectures" % (tree,dis)].split():
308                         if arch != "source":  # always true
309                             rel = "%s/%s/binary-%s/Release" % (dis, sec, arch)
310                             relpath = Cnf["Dir::Root"]+tree+"/"+rel
311                             write_release_file(relpath, suite, dis, origin, label, arch, version, suite_suffix, notautomatic)
312                             files.append(rel)
313                             for cfile in compressnames("tree::%s/%s" % (tree,dis),
314                                 "Packages",
315                                 "%s/%s/binary-%s/Packages" % (dis, sec, arch)):
316                                 files.append(cfile)
317             elif AptCnf.has_key("tree::%s::FakeDI" % (tree)):
318                 usetree = AptCnf["tree::%s::FakeDI" % (tree)]
319                 sec = AptCnf["tree::%s/main::Sections" % (usetree)].split()[0]
320                 if sec != "debian-installer":
321                     print "ALERT: weird non debian-installer section in %s" % (usetree)
322
323                 for arch in AptCnf["tree::%s/main::Architectures" % (usetree)].split():
324                     if arch != "source":  # always true
325                         for cfile in compressnames("tree::%s/main" % (usetree), "Packages", "main/%s/binary-%s/Packages" % (sec, arch)):
326                             files.append(cfile)
327
328         elif AptCnf.has_key("bindirectory::%s" % (tree)):
329             for cfile in compressnames("bindirectory::%s" % (tree), "Packages", AptCnf["bindirectory::%s::Packages" % (tree)]):
330                 files.append(cfile.replace(tree+"/","",1))
331             for cfile in compressnames("bindirectory::%s" % (tree), "Sources", AptCnf["bindirectory::%s::Sources" % (tree)]):
332                 files.append(cfile.replace(tree+"/","",1))
333         else:
334             print "ALERT: no tree/bindirectory for %s" % (tree)
335
336         out.write("MD5Sum:\n")
337         print_md5_files(tree, files)
338         out.write("SHA1:\n")
339         print_sha1_files(tree, files)
340         out.write("SHA256:\n")
341         print_sha256_files(tree, files)
342
343         out.close()
344         if Cnf.has_key("Dinstall::SigningKeyring"):
345             keyring = "--secret-keyring \"%s\"" % Cnf["Dinstall::SigningKeyring"]
346             if Cnf.has_key("Dinstall::SigningPubKeyring"):
347                 keyring += " --keyring \"%s\"" % Cnf["Dinstall::SigningPubKeyring"]
348
349             arguments = "--no-options --batch --no-tty --armour"
350             if Cnf.has_key("Dinstall::SigningKeyIds"):
351                 signkeyids = Cnf["Dinstall::SigningKeyIds"].split()
352             else:
353                 signkeyids = [""]
354
355             dest = Cnf["Dir::Root"] + tree + "/Release.gpg"
356             if os.path.exists(dest):
357                 os.unlink(dest)
358
359             for keyid in signkeyids:
360                 if keyid != "": defkeyid = "--default-key %s" % keyid
361                 else: defkeyid = ""
362                 os.system("gpg %s %s %s --detach-sign <%s >>%s" %
363                         (keyring, defkeyid, arguments,
364                         Cnf["Dir::Root"] + tree + "/Release", dest))
365
366 #######################################################################################
367
368 if __name__ == '__main__':
369     main()