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