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