File: deb.py

package info (click to toggle)
game-data-packager 67
  • links: PTS, VCS
  • area: contrib
  • in suites: bullseye
  • size: 16,188 kB
  • sloc: python: 10,576; sh: 515; makefile: 491
file content (445 lines) | stat: -rw-r--r-- 16,234 bytes parent folder | download | duplicates (2)
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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
#!/usr/bin/python3
# encoding=utf-8
#
# Copyright © 2014-2016 Simon McVittie <smcv@debian.org>
#           © 2015-2016 Alexandre Detiste <alexandre@detiste.be>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# You can find the GPL license text on a Debian system under
# /usr/share/common-licenses/GPL-2.

import logging
import os
import stat
import subprocess


try:
    from debian.deb822 import Deb822
    from debian.debian_support import Version
except ImportError:
    # make check
    from distutils.version import LooseVersion as Version
    Deb822 = None

from . import (PackagingSystem)
from ..data import (HashedFile)
from ..util import (
        check_output,
        mkdir_p,
        normalize_permissions,
        rm_rf,
        run_as_root)

logger = logging.getLogger(__name__)

class DebPackaging(PackagingSystem):
    BINDIR = '$prefix/games'
    ASSETS = '$datadir/games'
    CHECK_CMD = 'lintian'
    INSTALL_CMD = ['apt-get', 'install']
    # This is only used when cross-building Debian packages on
    # non-Debian, so conservatively assume that they don't have a new
    # enough dpkg-dev for --root-owner-group
    BUILD_DEP = {'dpkg', 'fakeroot', 'python3-debian'}
    PACKAGE_MAP = {
                  'id-shr-extract': 'dynamite',
                  'lha': 'lhasa',
                  '7z': 'p7zip-full',
                  'unrar-nonfree': 'unrar',
                  'zoom': 'zoom-player',
                  'doom': 'doom-engine',
                  'boom': 'boom-engine',
                  'heretic': 'heretic-engine',
                  'hexen': 'hexen-engine',
                  'doomsday-compat': 'doomsday',
                  }
    RENAME_PACKAGES = {
            'libSDL-1.2.so.0': 'libsdl1.2debian',
            'libgcc_s.so.1': 'libgcc1',
            'libjpeg.so.62': 'libjpeg62-turbo | libjpeg62',
    }

    def __init__(self):
        super(DebPackaging, self).__init__()
        self.__installed = None
        self.__available = None
        self._contexts = ('deb', 'generic')

    def read_architecture(self):
        self._architecture = check_output(['dpkg',
                '--print-architecture']).strip().decode('ascii')
        self._foreign_architectures = set(check_output(['dpkg',
                '--print-foreign-architectures']
                    ).strip().decode('ascii').split())

    def is_installed(self, package):
        # FIXME: this shouldn't be hard-coded
        if package == 'doom-engine':
            return (self.is_installed('chocolate-doom')
                 or self.is_installed('prboom-plus')
                 or self.is_installed('doomsday'))
        if package == 'boom-engine':
            return (self.is_installed('prboom-plus')
                 or self.is_installed('doomsday'))
        if package == 'heretic-engine':
            return (self.is_installed('chocolate-heretic')
                 or self.is_installed('doomsday'))
        if package == 'hexen-engine':
            return (self.is_installed('chocolate-hexen')
                 or self.is_installed('doomsday'))

        if os.path.isdir(os.path.join('/usr/share/doc', package)):
            return True

        if self.__installed is None:
            try:
                proc = subprocess.Popen(['dpkg-query', '--show',
                            '--showformat', '${Package}\\n'],
                        universal_newlines=True,
                        stdout=subprocess.PIPE)
            except FileNotFoundError:
                return False

            cache = set()
            for line in proc.stdout:
                cache.add(line.rstrip())
            self.__installed = cache

        return package in self.__installed

    def is_available(self, package):
        if self.__available is None:
            try:
                proc = subprocess.Popen(['apt-cache', 'pkgnames'],
                        universal_newlines=True,
                        stdout=subprocess.PIPE)
            except FileNotFoundError:
                return False

            cache = set()
            for line in proc.stdout:
                cache.add(line.rstrip())
            self.__available = cache

        return package in self.__available

    def current_version(self, package):
        # 'dpkg-query: no packages found matching $package'
        # will leak on stderr if called with an unknown package,
        # but that should never happen
        try:
            return check_output(['dpkg-query', '--show',
              '--showformat', '${Version}', package], universal_newlines=True)
        except FileNotFoundError:
            return None
        except subprocess.CalledProcessError:
            return None

    def available_version(self, package):
        try:
            current_ver = check_output(['apt-cache', 'madison', package],
                                        universal_newlines=True)
        except FileNotFoundError:
            return None
        current_ver = current_ver.splitlines()[0]
        current_ver = current_ver.split('|')[1].strip()
        return current_ver

    def install_packages(self, debs, method=None, gain_root='su'):
        if method and method not in (
                'apt', 'dpkg',
                'gdebi', 'gdebi-gtk', 'gdebi-kde',
                ):
            logger.warning(('Unknown installation method %r, using apt or ' +
                'dpkg instead') % method)
            method = None

        if not method:
            apt_ver = self.current_version('apt')
            if Version(apt_ver.strip()) >= Version('1.1~0'):
                method = 'apt'
            else:
                method = 'dpkg'

        if method == 'apt':
            run_as_root(['apt-get', 'install', '--install-recommends'] +
                    list(debs), gain_root)
        elif method == 'dpkg':
            run_as_root(['dpkg', '-i'] + list(debs), gain_root)
        elif method == 'gdebi':
            run_as_root(['gdebi'] + list(debs), gain_root)
        else:
            # gdebi-gtk etc.
            subprocess.call([method] + list(debs))

    def rename_package(self, p):
        mapped = super(DebPackaging, self).rename_package(p)

        if mapped != p:
            return mapped

        p = p.lower().replace('_', '-')

        if '.so.' in p:
            lib, version = p.split('.so.', 1)

            if lib[-1] in '012345679':
                lib += '-'

            return lib + version

        return p

    def override_lintian(self, destdir, package, tag, args=None):
        assert type(package) is str
        lintiandir = os.path.join(destdir, 'usr/share/lintian/overrides')
        mkdir_p(lintiandir)
        with open(os.path.join(lintiandir, package), 'a', encoding='utf-8') as l:
            rest = [tag]
            if args is not None:
                rest.append(args)
            l.write('%s: %s\n' % (package, ' '.join(rest)))

    def format_relation(self, pr):
        assert not pr.contextual

        if pr.alternatives:
            return ' | '.join([self.format_relation(p)
                for p in pr.alternatives])

        if pr.version is not None:
            # foo (>= 1.0)
            return '%s (%s %s)' % (self.rename_package(pr.package),
                    pr.version_operator, pr.version)

        return self.rename_package(pr.package)

    def __generate_control(self, game, package, destdir, component):
        if Deb822 is None:
            raise FileNotFoundError('Cannot generate .deb packages without '
                    'python3-debian')

        control = Deb822()
        control['Package'] = package.name
        control['Version'] = package.version
        control['Priority'] = 'optional'
        control['Maintainer'] = 'Debian Games Team <pkg-games-devel@lists.alioth.debian.org>'

        installed_size = 0
        # algorithm from https://bugs.debian.org/650077 designed to be
        # filesystem-independent
        for dirpath, dirnames, filenames in os.walk(destdir):
            if dirpath == destdir and 'DEBIAN' in dirnames:
                dirnames.remove('DEBIAN')
            # estimate 1 KiB per directory
            installed_size += len(dirnames)
            for f in filenames:
                stat_res = os.lstat(os.path.join(dirpath, f))
                if (stat.S_ISLNK(stat_res.st_mode) or
                        stat.S_ISREG(stat_res.st_mode)):
                    # take the real size and round up to next 1 KiB
                    installed_size += ((stat_res.st_size + 1023) // 1024)
                else:
                    # this will probably never happen in gdp, but assume
                    # 1 KiB per non-regular, non-directory, non-symlink file
                    installed_size += 1
        control['Installed-Size'] = str(installed_size)

        if component == 'main':
            control['Section'] = package.section
        else:
            control['Section'] = component + '/' + package.section

        if package.architecture == 'all':
            control['Architecture'] = 'all'
            control['Multi-Arch'] = 'foreign'
        else:
            control['Architecture'] = self.get_architecture(
                    package.architecture)

        dep = dict()

        for rel in package.relations:
            if rel == 'build_depends':
                continue

            dep[rel] = self.merge_relations(package, rel)
            logger.debug('%s %s %s', package.name, rel, ', '.join(dep[rel]))

        if package.mutually_exclusive:
            dep['conflicts'] |= package.demo_for
            dep['conflicts'] |= package.better_versions

        if package.mutually_exclusive:
            dep['replaces'] |= dep['provides']

        engine = self.substitute(
                package.engine or game.engine,
                package.name)

        if engine and '>=' in engine:
            engine, ver = engine.split(maxsplit=1)
            ver = ver.strip('(>=) ')
            dep['breaks'].add('%s (<< %s~)' % (engine, ver))

        # We only 'recommends' & not 'depends'; to avoid
        # that GDP-generated packages get removed
        # if engine goes through some gcc/png/ffmpeg/... migration
        # and must be temporarily removed.
        # It's not like 'apt-get install ...' can revert this removal;
        # user may need to dig again for the original media....
        if package.engine:
            dep['recommends'].add(engine)
        elif game.engine and (
            package.section != 'doc'
            and not package.expansion_for
        ):
            dep['recommends'].add(engine)

        if package.expansion_for:
            # check if default heuristic has been overriden in yaml
            for p in dep['depends']:
                if package.expansion_for == p.split()[0]:
                    break
            else:
                dep['depends'].add(package.expansion_for)

        # dependencies derived from *other* package's data
        for other_package in game.packages.values():
            if other_package.expansion_for:
                if package.name == other_package.expansion_for:
                    dep['suggests'].add(other_package.name)
                else:
                    for p in package.relations['provides']:
                        if p.package == other_package.expansion_for:
                            dep['suggests'].add(other_package.name)

            if other_package.mutually_exclusive:
                if package.name in other_package.better_versions:
                    dep['replaces'].add(other_package.name)

                if package.name in other_package.demo_for:
                    dep['replaces'].add(other_package.name)

        # Shortcut: if A Replaces B, A automatically Conflicts B
        dep['conflicts'] |= dep['replaces']

        # keep only strongest depedency
        dep['recommends'] -= dep['depends']
        dep['suggests'] -= dep['recommends']
        dep['suggests'] -= dep['depends']

        for k, v in dep.items():
            if v:
                control[k.title()] = ', '.join(sorted(v))

        if 'Description' not in control:
            short_desc, long_desc = self.generate_description(game, package)
            control['Description'] = (short_desc + '\n ' +
                '\n '.join([(line or '.') for line in long_desc]))

        return control

    def __fill_dest_dir_deb(self, game, package, destdir, md5sums=None,
            component=None):
        if component is None:
            component = package.component

        if component == 'local':
             self.override_lintian(destdir, package.name,
                     'unknown-section', 'local/%s' % package.section)

        for o in package.lintian_overrides:
            self.override_lintian(destdir, package.name, o)

        # same output as in dh_md5sums
        if md5sums is None:
            md5sums = {}

        # we only compute here the md5 we don't have yet,
        # for the (small) GDP-generated files
        for dirpath, dirnames, filenames in os.walk(destdir):
            if os.path.basename(dirpath) == 'DEBIAN':
                continue
            for fn in filenames:
                full = os.path.join(dirpath, fn)
                if os.path.islink(full):
                    continue
                file = full[len(destdir)+1:]
                if file not in md5sums:
                    with open(full, 'rb') as opened:
                        hf = HashedFile.from_file(full, opened)
                        md5sums[file] = hf.md5

        debdir = os.path.join(destdir, 'DEBIAN')
        mkdir_p(debdir)
        md5sums_path = os.path.join(destdir, 'DEBIAN/md5sums')
        with open(md5sums_path, 'w', encoding='utf8') as outfile:
            for file in sorted(md5sums.keys()):
                outfile.write('%s  %s\n' % (md5sums[file], file))
        os.chmod(md5sums_path, 0o644)

        control = os.path.join(destdir, 'DEBIAN/control')
        self.__generate_control(game, package, destdir, component).dump(
                fd=open(control, 'wb'), encoding='utf-8')
        os.chmod(control, 0o644)

    def build_package(self, per_package_dir, game, package, destination,
            compress=True, md5sums=None, component=None):
        destdir = os.path.join(per_package_dir, 'DESTDIR')
        arch = self.get_effective_architecture(package)
        self.__fill_dest_dir_deb(game, package, destdir, md5sums,
                component)
        normalize_permissions(destdir)

        # it had better have a /usr and a DEBIAN directory or
        # something has gone very wrong
        assert os.path.isdir(os.path.join(destdir, 'usr')), destdir
        assert os.path.isdir(os.path.join(destdir, 'DEBIAN')), destdir

        deb_basename = '%s_%s_%s.deb' % (package.name, package.version, arch)

        outfile = os.path.join(os.path.abspath(destination), deb_basename)

        if not compress:
            dpkg_deb_args = ['-Znone']
        elif compress is True:
            dpkg_deb_args = []
        elif isinstance(compress, str):
            dpkg_deb_args = ['-Z' + compress]
        elif isinstance(compress, list):
            dpkg_deb_args = compress[:]

        dpkg_deb_args.insert(0, 'dpkg-deb')

        dpkg_version = Version(self.current_version('dpkg'))

        if dpkg_version >= Version('1.19.0'):
            dpkg_deb_args.append('--root-owner-group')
        else:
            dpkg_deb_args.insert(0, 'fakeroot')

        try:
            logger.info('generating package %s', package.name)
            check_output(
                    dpkg_deb_args +
                    ['-b', 'DESTDIR', outfile],
                    cwd=per_package_dir)
        except subprocess.CalledProcessError as cpe:
            print(cpe.output)
            raise

        rm_rf(destdir)
        return outfile

def get_packaging_system(distro=None):
    return DebPackaging()