~stefanor/+junk/reverse-deps

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
#!/usr/bin/env python

# Copyright: 2011, Stefano Rivera <stefanor@ubuntu.com>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
# REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
# AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
# INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
# LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
# OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
# PERFORMANCE OF THIS SOFTWARE.

import bz2
import os
import sqlite3
import sys
import tempfile
import urllib2
import zlib

import lzma

from distro_info import DebianDistroInfo, UbuntuDistroInfo
try:
    from debian.deb822 import Packages, Sources, Release
except ImportError:
    from debian_bundle.deb822 import Packages, Sources, Release

UBUNTU_MIRROR = 'http://archive.ubuntu.com/ubuntu'
UBUNTU_PORTS_MIRROR = 'http://ports.ubuntu.com'
UBUNTU_PRIMARY_ARCHS = ('source', 'amd64', 'i386')
UBUNTU_COMPONENTS = ('main', 'universe', 'multiverse', 'restricted')
UBUNTU_RELEASES = tuple(UbuntuDistroInfo().supported())

DEBIAN_MIRROR = 'http://ftp.debian.org/debian'
DEBIAN_COMPONENTS = ('main', 'contrib', 'non-free')
DEBIAN_RELEASES = tuple(DebianDistroInfo().supported())

SRC_RELATIONSHIPS = ('Build-Depends', 'Build-Depends-Indep')
BIN_RELATIONSHIPS = ('Depends', 'Recommends', 'Suggests',
                     'Pre-Depends',
                     'Conflicts', 'Breaks', 'Replaces',
                     'Enhances')

if '-q' in sys.argv:
    UBUNTU_MIRROR = 'http://localhost/ubuntu'
    UBUNTU_COMPONENTS = ('main',)
    UBUNTU_RELEASES = ('lucid', 'precise')
    DEBIAN_RELEASES = ()

release_files = {}


def urlopen_decompress(url):
    raw = urllib2.urlopen(url)
    data = raw.read()
    if url.endswith('.xz'):
        data = lzma.decompress(data)
    elif url.endswith('.bz2'):
        data = bz2.decompress(data)
    elif url.endswith('.gz'):
        data = zlib.decompress(data, 16 + zlib.MAX_WBITS)
    raw.close()
    return data


def write_to_tempfile(data):
    tmpfile = tempfile.TemporaryFile()
    tmpfile.write(data)
    tmpfile.seek(0)
    return tmpfile


def base_url(release, arch=None):
    if release in UBUNTU_RELEASES:
        if arch not in UBUNTU_PRIMARY_ARCHS:
            return UBUNTU_PORTS_MIRROR
        else:
            return UBUNTU_MIRROR
    elif release in DEBIAN_RELEASES:
        return DEBIAN_MIRROR
    else:
        raise Exception('Unknown release %s' % release)


def source_url(release, component, arch):
    if arch == 'source':
        snippet = os.path.join(component, 'source', 'Sources')
    else:
        snippet = os.path.join(component, 'binary-%s' % arch, 'Packages')
    release_f = release_file(release)
    contents = release_f.get('SHA256',
                             release_f.get('SHA1', release_f.get('MD5Sum')))

    found = False
    for compression in ('.xz', '.bz2', '.gz', ''):
        for entry in contents:
            if entry['name'] == snippet + compression:
                snippet += compression
                found = True
                break
        if found:
            break
    else:
        raise Exception("%s not found in Release" % snippet)

    url = os.path.join(base_url(release, arch), 'dists', release, snippet)
    return url


def release_file(release):
    if release not in release_files:
        url = os.path.join(base_url(release), 'dists', release, 'Release')
        f = urllib2.urlopen(url)
        try:
            release_files[release] = Release(f.read())
        finally:
            f.close()
    return release_files[release]


def architectures(release):
    return ['source'] + release_file(release)['architectures'].split(' ')


def components(release):
    if release in UBUNTU_RELEASES:
        return UBUNTU_COMPONENTS
    elif release in DEBIAN_RELEASES:
        return DEBIAN_COMPONENTS
    else:
        raise Exception('Unknown release %s' % release)


def main():
    try:
        os.unlink('rdepends-new.db')
    except OSError:
        pass

    conn = sqlite3.connect('rdepends-new.db')
    cur = conn.cursor()
    cur.execute("PRAGMA synchronous=OFF;")
    cur.execute("PRAGMA journal_mode=OFF;")
    cur.execute("""CREATE TABLE relationships (
                       id INTEGER PRIMARY KEY,
                       relationship TEXT NOT NULL,
                       UNIQUE (relationship)
                   );
    """)
    cur.execute("""CREATE TABLE releases (
                       id INTEGER PRIMARY KEY,
                       release TEXT NOT NULL,
                       UNIQUE (release)
                   );
    """)
    cur.execute("""CREATE TABLE archs (
                       id INTEGER PRIMARY KEY,
                       arch TEXT NOT NULL,
                       UNIQUE (arch)
                   );
    """)
    cur.execute("""CREATE TABLE packages (
                       id INTEGER PRIMARY KEY,
                       package TEXT NOT NULL,
                       binary BOOLEAN NOT NULL,
                       UNIQUE (package, binary)
                   );
    """)
    cur.execute("""CREATE TABLE src_binary (
                       release INTEGER NOT NULL,
                       source INTEGER NOT NULL,
                       binary INTEGER NOT NULL,
                       UNIQUE (release, source, binary),
                       FOREIGN KEY (release) REFERENCES releases(id),
                       FOREIGN KEY (source) REFERENCES packages(id),
                       FOREIGN KEY (binary) REFERENCES packages(id)
                   );
    """)
    cur.execute("""CREATE TABLE components (
                       id INTEGER PRIMARY KEY,
                       component TEXT NOT NULL,
                       UNIQUE (component)
                   );
    """)
    cur.execute("""CREATE TABLE pkg_components (
                       package INTEGER NOT NULL,
                       release INTEGER NOT NULL,
                       component INTEGER NOT NULL,
                       UNIQUE (package, release)
                       FOREIGN KEY (package) REFERENCES packages(id),
                       FOREIGN KEY (release) REFERENCES releases(id),
                       FOREIGN KEY (component) REFERENCES components(id)
                   );
    """)
    cur.execute("""CREATE TABLE rdepends (
                       package INTEGER NOT NULL,
                       dependency INTEGER NOT NULL,
                       relationship INTEGER NOT NULL,
                       release INTEGER NOT NULL,
                       arch INTEGER NOT NULL,
                       FOREIGN KEY (package) REFERENCES packages(id),
                       FOREIGN KEY (dependency) REFERENCES packages(id),
                       FOREIGN KEY (relationship) REFERENCES relationships(id),
                       FOREIGN KEY (release) REFERENCES releases(id),
                       FOREIGN KEY (arch) REFERENCES archs(id),
                       PRIMARY KEY (dependency, release, arch, relationship,
                                    package)
                   );
    """)
    conn.commit()

    relationshipids = {}
    for rel in BIN_RELATIONSHIPS + SRC_RELATIONSHIPS:
        cur.execute("INSERT INTO relationships (relationship) VALUES (?);",
                    (rel,))
        relationshipids[rel] = cur.lastrowid

    archids = {}
    archnames = set()
    for release in DEBIAN_RELEASES + UBUNTU_RELEASES:
        archnames.update(architectures(release))
    for arch in archnames:
        cur.execute("INSERT INTO archs (arch) VALUES (?);", (arch,))
        archids[arch] = cur.lastrowid

    componentids = {}
    for component in set(UBUNTU_COMPONENTS + DEBIAN_COMPONENTS):
        cur.execute("INSERT INTO components (component) VALUES (?);",
                    (component,))
        componentids[component] = cur.lastrowid
    conn.commit()

    pkgids = {}

    def add_packages(pkgs, binary):
        for pkg in pkgs:
            if (pkg, binary) in pkgids:
                continue
            cur.execute("""INSERT INTO packages (package, binary)
                           VALUES (?, ?);""", (pkg, binary))
            pkgids[(pkg, binary)] = cur.lastrowid

    for release in UBUNTU_RELEASES + DEBIAN_RELEASES:
        cur.execute("INSERT INTO releases (release) VALUES (?);",
                    (release,))
        releaseid = cur.lastrowid
        conn.commit()
        for arch in architectures(release):
            archid = archids[arch]
            if arch == 'source':
                parser = Sources
                fields = SRC_RELATIONSHIPS
            else:
                parser = Packages
                fields = BIN_RELATIONSHIPS

            for component in components(release):
                print release, arch, component
                componentid = componentids[component]
                url = source_url(release, component, arch)

                try:
                    data = urlopen_decompress(url)
                except urllib2.HTTPError, e:
                    raise Exception("HTTP Error %i on %s" % (e.code, url))

                packagefile = write_to_tempfile(data)
                parsed = parser.iter_paragraphs(packagefile)

                for package in parsed:
                    name = package['Package']
                    binary = arch != 'source'

                    if (name, binary) not in pkgids:
                        add_packages((name,), binary)
                    pkgid = pkgids[(name, binary)]
                    cur.execute("""
                        INSERT OR IGNORE INTO pkg_components
                          (package, release, component)
                        VALUES (?, ?, ?);""",
                        (pkgid, releaseid, componentid))

                    if not binary:
                        binaries = package['Binary'].split(u', ')
                        add_packages(binaries, True)
                        cur.executemany("""
                            INSERT OR IGNORE INTO src_binary (release, source, binary)
                            VALUES (?, ?, ?);""",
                            [(releaseid, pkgid, pkgids[(binary, True)])
                             for binary in binaries])

                    for field in fields:
                        relid = relationshipids[field]
                        deps = set()
                        for dep in package.relations[field]:
                            for alternate in dep:
                                deps.add(alternate['name'])

                        add_packages(deps, True)

                        cur.executemany("""
                            INSERT OR IGNORE INTO rdepends
                              (package, dependency, relationship, release,
                               arch)
                            VALUES
                              (?, ?, ?, ?, ?);""",
                            [(pkgid, pkgids[(dep, True)], relid, releaseid,
                              archid)
                             for dep in deps])
                conn.commit()
                packagefile.close()

    cur.execute("PRAGMA synchronous=FULL;")
    cur.execute("ANALYZE;")
    conn.commit()
    conn.close()
    os.rename('rdepends-new.db', 'rdepends.db')

if __name__ == '__main__':
    main()