Skip to content
Snippets Groups Projects
run.py 50.6 KiB
Newer Older
Simon McVittie's avatar
Simon McVittie committed
#!/usr/bin/python3

# flatdeb — build Flatpak runtimes from Debian packages
#
# Copyright © 2016-2017 Simon McVittie
# Copyright © 2017 Collabora Ltd.
#
# Partially derived from vectis, copyright © 2015-2017 Simon McVittie
#
# SPDX-License-Identifier: MIT
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

"""
Create Flatpak runtimes from Debian packages.
"""

import argparse
import json
Simon McVittie's avatar
Simon McVittie committed
import logging
Simon McVittie's avatar
Simon McVittie committed
import os
import re
Simon McVittie's avatar
Simon McVittie committed
import subprocess
Simon McVittie's avatar
Simon McVittie committed
import sys
import urllib.parse
from contextlib import ExitStack
Simon McVittie's avatar
Simon McVittie committed
from tempfile import TemporaryDirectory

import yaml
from gi.repository import GLib

try:
    import typing
except ImportError:
    pass
else:
    typing  # silence "unused" warnings

Simon McVittie's avatar
Simon McVittie committed

Simon McVittie's avatar
Simon McVittie committed
logger = logging.getLogger('flatdeb')


# TODO: When flatdeb is packaged/released, replace this with the released
# version in packages/releases
VERSION = None

if VERSION is None:
    _git_version = subprocess.check_output([
        'sh', '-c',
        'cd "$(dirname "$1")" && '
        'git describe '
        '--always '
        '--dirty '
        '--first-parent '
        '--long '
        '--tags '
        '--match="v[0-9]*" '
        '2>/dev/null || :',
        'sh',
        sys.argv[0],
    ])[1:].decode('utf-8').strip()
    VERSION = _git_version

_DEBOS_BASE_RECIPE = os.path.join(
    os.path.dirname(__file__), 'flatdeb', 'debos-base.yaml')
_DEBOS_RUNTIMES_RECIPE = os.path.join(
    os.path.dirname(__file__), 'flatdeb', 'debos-runtimes.yaml')

class AptSource:
    def __init__(
        self,
        kind,
        uri,
        suite,
        components=('main',),
        trusted=False
    ):
        self.kind = kind
        self.uri = uri
        self.suite = suite
        self.components = components
        self.trusted = trusted

    @classmethod
    def from_string(
        cls,
        line,
    ):
        tokens = line.split()
        trusted = False

        if len(tokens) < 4:
            raise ValueError(
                'apt sources must be specified in the form '
                '"deb http://URL SUITE COMPONENT [COMPONENT...]"')

        if tokens[0] not in ('deb', 'deb-src'):
            raise ValueError(
                'apt sources must start with "deb " or "deb-src "')

        if tokens[1] == '[trusted=yes]':
            trusted = True
            tokens = [tokens[0]] + tokens[2:]
        elif tokens[1].startswith('['):
            raise ValueError(
                'The only apt source option supported is [trusted=yes]')

        return cls(
            kind=tokens[0],
            uri=tokens[1],
            suite=tokens[2],
            components=tokens[3:],
            trusted=trusted,
        )

    def __str__(self):
        if self.trusted:
            maybe_options = ' [trusted=yes]'
        else:
            maybe_options = ''

        return '%s%s %s %s %s' % (
            self.kind,
            maybe_options,
            self.uri,
            self.suite,
            ' '.join(self.components),
        )


Simon McVittie's avatar
Simon McVittie committed
class Builder:

    """
    Main object
    """

    __multiarch_tuple_cache = {}    # type: typing.Dict[str, str]
Simon McVittie's avatar
Simon McVittie committed
    def __init__(self):
        #: The Debian suite to use
        self.apt_suite = 'stretch'
        #: The Flatpak branch to use for the runtime, or None for apt_suite
        self.runtime_branch = None
        #: The Flatpak branch to use for the app
        self.app_branch = None
Simon McVittie's avatar
Simon McVittie committed
        #: The freedesktop.org cache directory
        self.xdg_cache_dir = os.getenv(
            'XDG_CACHE_HOME', os.path.expanduser('~/.cache'))
Simon McVittie's avatar
Simon McVittie committed
        #: Where to write output
        self.build_area = os.path.join(
            self.xdg_cache_dir, 'flatdeb',
        )
        self.ostree_repo = os.path.join(self.build_area, 'ostree-repo')
Simon McVittie's avatar
Simon McVittie committed

        self.__dpkg_archs = []
Simon McVittie's avatar
Simon McVittie committed
        self.flatpak_arch = None

        self.__primary_dpkg_arch_matches_cache = {}
Simon McVittie's avatar
Simon McVittie committed
        self.suite_details = {}
        self.runtime_details = {}
        self.ostree_mode = 'archive-z2'
        self.export_bundles = False
        self.strip_source_version_suffix = None
        self.apt_keyrings = []
        self.apt_sources = []
Simon McVittie's avatar
Simon McVittie committed

Simon McVittie's avatar
Simon McVittie committed
        self.logger = logger.getChild('Builder')

    @staticmethod
    def yaml_dump_one_line(data, stream=None):
        return yaml.safe_dump(
            data,
            stream=stream,
            default_flow_style=True,
            width=0xFFFFFFFF,
        ).replace('\n', ' ')

Simon McVittie's avatar
Simon McVittie committed
    @staticmethod
    def get_flatpak_arch(arch=None):
        """
        Return the Flatpak architecture name corresponding to uname
        result arch.

        If arch is None, return the Flatpak architecture name
        corresponding to the machine where this script is running.
        """

        if arch is None:
            arch = os.uname()[4]

        if re.match(r'^i.86$', arch):
            return 'i386'
        elif re.match(r'^arm.*', arch):
            if arch.endswith('b'):
                return 'armeb'
            else:
                return 'arm'
        elif arch in ('mips', 'mips64'):
            import struct
            if struct.pack('i', 1).startswith(b'\x01'):
                return arch + 'el'

        return arch

Simon McVittie's avatar
Simon McVittie committed
    @staticmethod
    def other_multiarch(arch):
        """
        Return the other architecture that accompanies the given Debian
        architecture in a multiarch setup, or None.
        """

        if arch == 'amd64':
            return 'i386'
        elif arch == 'arm64':
            return 'armhf'
        else:
            return None

    @staticmethod
    def multiarch_tuple(arch):
        """
        Return the multiarch tuple for the given dpkg architecture name.
        """

        if arch not in Builder.__multiarch_tuple_cache:
            Builder.__multiarch_tuple_cache[arch] = subprocess.check_output([
                'dpkg-architecture',
                '-qDEB_HOST_MULTIARCH',
                '-a{}'.format(arch),
            ]).decode('utf-8').strip()

        return Builder.__multiarch_tuple_cache[arch]

Simon McVittie's avatar
Simon McVittie committed
    @staticmethod
    def dpkg_to_flatpak_arch(arch):
        """
        Return the Flatpak architecture name corresponding to the given
        dpkg architecture name.
        """

        if arch == 'amd64':
            return 'x86_64'
        elif arch == 'arm64':
            return 'aarch64'
        elif arch in ('armel', 'armhf'):
            return 'arm'
        elif arch == 'powerpc':
            return 'ppc'
        elif arch == 'powerpc64':
            return 'ppc64'
        elif arch == 'powerpcel':
            return 'ppcle'
        elif arch == 'ppc64el':
            return 'ppc64le'

        return arch

    @property
    def primary_dpkg_arch(self):
Simon McVittie's avatar
Simon McVittie committed
        """
        The Debian architecture we are building a runtime for, such as
        i386 or amd64.
        """
        return self.__dpkg_archs[0]
Simon McVittie's avatar
Simon McVittie committed

    @property
    def dpkg_archs(self):
        """
        The Debian architectures we support via multiarch, such as
        ['amd64', 'i386'].
        """
        return self.__dpkg_archs
Simon McVittie's avatar
Simon McVittie committed

    @dpkg_archs.setter
    def dpkg_archs(self, value):
        self.__primary_dpkg_arch_matches_cache = {}
        self.__dpkg_archs = value

    def primary_dpkg_arch_matches(self, arch_spec):
Simon McVittie's avatar
Simon McVittie committed
        """
        Return True if arch_spec matches primary_dpkg_arch (or
        equivalently, if primary_dpkg_arch is one of the architectures
Simon McVittie's avatar
Simon McVittie committed
        described by arch_spec). For example, any-amd64 matches amd64
        but not i386.
        """
        if arch_spec not in self.__primary_dpkg_arch_matches_cache:
            exit_code = subprocess.call(
                ['dpkg-architecture', '--host-arch', self.primary_dpkg_arch,
Simon McVittie's avatar
Simon McVittie committed
                 '--is', arch_spec])
            self.__primary_dpkg_arch_matches_cache[arch_spec] = (
                exit_code == 0
            )
Simon McVittie's avatar
Simon McVittie committed

        return self.__primary_dpkg_arch_matches_cache[arch_spec]
Simon McVittie's avatar
Simon McVittie committed

    def run_command_line(self):
        """
        Run appropriate commands for the command-line arguments
        """
        parser = argparse.ArgumentParser(
            description='Build Flatpak runtimes',
        )
        parser.add_argument('--chdir', default=None)
        parser.add_argument(
            '--ostree-mode', default=self.ostree_mode,
        )
        parser.add_argument(
            '--export-bundles', action='store_true', default=False,
        )
Simon McVittie's avatar
Simon McVittie committed
        parser.add_argument('--build-area', default=self.build_area)
        parser.add_argument('--ostree-repo', default=self.ostree_repo)
Simon McVittie's avatar
Simon McVittie committed
        parser.add_argument('--suite', '-d', default=self.apt_suite)
        parser.add_argument('--architecture', '--arch', '-a')
        parser.add_argument('--runtime-branch', default=self.runtime_branch)
        parser.add_argument('--version', action='store_true')
        parser.add_argument(
            '--replace-apt-source', action='append', default=[])
        parser.add_argument(
            '--remove-apt-source', action='append', default=[])
        parser.add_argument(
            '--add-apt-source', action='append', default=[])
        parser.add_argument(
            '--add-apt-keyring', action='append', default=[])
        parser.add_argument(
            '--generate-sysroot-tarball', action='store_true')
Simon McVittie's avatar
Simon McVittie committed
        subparsers = parser.add_subparsers(dest='command', metavar='command')

        subparser = subparsers.add_parser(
            'base',
            help='Build a fresh base tarball',
        )

        subparser = subparsers.add_parser(
            'runtimes',
            help='Build runtimes',
        )
        subparser.add_argument('yaml_file')
Simon McVittie's avatar
Simon McVittie committed

        subparser = subparsers.add_parser(
            'app',
            help='Build an app',
        )
        subparser.add_argument('--app-branch', default=self.app_branch)
        subparser.add_argument('yaml_manifest')
Simon McVittie's avatar
Simon McVittie committed

        subparser = subparsers.add_parser(
            'print-flatpak-architecture',
            help='Print the Flatpak architecture',
        )

        args = parser.parse_args()

        for replacement in args.replace_apt_source:
            if '=' not in replacement:
                parser.error(
                    '--replace-apt-source argument must be in the form '
                    '"LABEL=deb http://ARCHIVE SUITE COMPONENT[...]"')

        if args.version:
            print('flatdeb {}'.format(VERSION))
            return

        if args.chdir is not None:
            os.chdir(args.chdir)

Simon McVittie's avatar
Simon McVittie committed
        self.build_area = args.build_area
        self.apt_suite = args.suite
        self.runtime_branch = args.runtime_branch
        self.ostree_repo = args.ostree_repo
        self.export_bundles = args.export_bundles
        self.ostree_mode = args.ostree_mode
Simon McVittie's avatar
Simon McVittie committed

        if args.architecture is None:
                    ['dpkg-architecture', '-q', 'DEB_HOST_ARCH'],
                ).decode('utf-8').rstrip('\n')
            ]
Simon McVittie's avatar
Simon McVittie committed
        else:
            self.dpkg_archs = args.architecture.split(',')
Simon McVittie's avatar
Simon McVittie committed

        self.flatpak_arch = self.dpkg_to_flatpak_arch(self.primary_dpkg_arch)
Simon McVittie's avatar
Simon McVittie committed

        self.ensure_build_area()
        os.makedirs(os.path.dirname(self.ostree_repo), exist_ok=True)
Simon McVittie's avatar
Simon McVittie committed

        if args.command is None:
            parser.error('A command is required')

        with open(
                os.path.join('suites', self.apt_suite + '.yaml'),
                encoding='utf-8') as reader:
Simon McVittie's avatar
Simon McVittie committed
            self.suite_details = yaml.safe_load(reader)

        self.strip_source_version_suffix = self.suite_details.get(
            'strip_source_version_suffix', '')
        for source in self.suite_details['sources']:
            keyring = source.get('keyring')

            if keyring is not None:
                self.apt_keyrings.append(keyring)

            uri = source['apt_uri']
            suite = source.get('apt_suite', self.apt_suite)
            suite = suite.replace('*', self.apt_suite)
            components = source.get(
                'apt_components',
                self.suite_details.get('apt_components', ['main'])
            )
            trusted = source.get('apt_trusted', False)

            if 'label' in source:
                replaced = False

                for replacement in reversed(args.replace_apt_source):
                    key, value = replacement.split('=', 1)

                    if key == source['label']:
                        tokens = value.split()

                        if tokens[0] == 'both':
                            self.apt_sources.append(
                                AptSource.from_string('deb' + value[4:]))
                            self.apt_sources.append(
                                AptSource.from_string('deb-src' + value[4:]))
                        else:
                            self.apt_sources.append(
                                AptSource.from_string(value))

                        replaced = True
                        break

                if replaced or source['label'] in args.remove_apt_source:
                    continue

            if source.get('deb', True):
                self.apt_sources.append(AptSource(
                    'deb', uri, suite,
                    components=components,
                    trusted=trusted,
                ))

            if source.get('deb-src', True):
                self.apt_sources.append(AptSource(
                    'deb-src', uri, suite,
                    components=components,
                    trusted=trusted,
                ))

            for addition in args.add_apt_source:
                self.apt_sources.append(AptSource.from_string(addition))

            for addition in args.add_apt_keyring:
                self.apt_keyrings.append(addition)

        if self.apt_sources[0].kind != 'deb':
            parser.error('First apt source must provide .deb packages')

Simon McVittie's avatar
Simon McVittie committed
        getattr(
            self, 'command_' + args.command.replace('-', '_'))(**vars(args))

    def command_print_flatpak_architecture(self, **kwargs):
        print(self.flatpak_arch)

    @property
    def apt_uris(self):
        for source in self.apt_sources:
            yield source.uri
Simon McVittie's avatar
Simon McVittie committed

    def ensure_build_area(self):
        os.makedirs(self.xdg_cache_dir, 0o700, exist_ok=True)
        os.makedirs(self.build_area, 0o755, exist_ok=True)
        os.makedirs(os.path.join(self.build_area, 'tmp'), exist_ok=True)
Simon McVittie's avatar
Simon McVittie committed
    def command_base(self, **kwargs):
        with ExitStack() as stack:
            scratch = stack.enter_context(
                TemporaryDirectory(prefix='flatdeb.')
            )
            self.ensure_build_area()
Simon McVittie's avatar
Simon McVittie committed

            # debootstrap only supports one suite, so we use the first
            apt_suite = self.apt_sources[0].suite
            dest_recipe = os.path.join(scratch, 'flatdeb.yaml')
            shutil.copyfile(_DEBOS_BASE_RECIPE, dest_recipe)

            for helper in (
                'add-foreign-architectures',
                'clean-up-base',
                'clean-up-before-pack',
                'disable-services',
                'usrmerge',
                'write-manifest',
                dest = os.path.join(scratch, helper)
                shutil.copyfile(
                    os.path.join(
                        os.path.dirname(__file__),
                        'flatdeb',
                        helper,
                    ),
                    dest,
                )
            os.makedirs(
                os.path.join(
                    scratch, 'suites', apt_suite, 'overlay', 'etc',
                    'apt', 'trusted.gpg.d',

            tarball = 'base-{}-{}.tar.gz'.format(
                self.apt_suite,
                ','.join(self.dpkg_archs),
            )
            output = os.path.join(self.build_area, tarball)

            script = self.suite_details.get('debootstrap_script')
Simon McVittie's avatar
Simon McVittie committed

            if script is not None:
                # TODO: flatdeb has historically used a configurable
                # debootstrap_script, but debos doesn't support scripts other
                # than 'unstable'. Does the Debian script work for precise and
                # produce the same results as the 'precise' script?
                # https://github.com/go-debos/debos/issues/16
                logger.debug(
                    'Ignoring /usr/share/debootstrap/scripts/%s', script)
Simon McVittie's avatar
Simon McVittie committed

            self.configure_apt(
                os.path.join(scratch, 'suites', apt_suite, 'overlay'))
Simon McVittie's avatar
Simon McVittie committed

            argv = [
                'debos',
                '--artifactdir={}'.format(self.build_area),
                '-t', 'architecture:{}'.format(self.primary_dpkg_arch),
                '-t', 'suite:{}'.format(apt_suite),
                '-t', 'mirror:{}'.format(
                ),
                '-t', 'ospack:{}'.format(tarball + '.new'),
                '-t', 'manifest_prefix:base-{}-{}'.format(
                    self.apt_suite,
                    ','.join(self.dpkg_archs),
                ),
                '-t', 'foreignarchs:{}'.format(
                    ' '.join(self.dpkg_archs[1:]),
                ),
                '-t', 'mergedusr:{}'.format(
                    str(
                        self.suite_details.get('can_merge_usr', False),
                    ).lower(),
                ),
            ]
            for keyring in self.apt_keyrings:
                if os.path.exists(os.path.join('suites', keyring)):
                    keyring = os.path.join('suites', keyring)
                elif os.path.exists(keyring):
                    pass
                else:
                    raise RuntimeError('Cannot open {}'.format(keyring))

                dest = os.path.join(
                    scratch, 'suites', apt_suite, 'overlay',
                    'etc', 'apt', 'trusted.gpg.d',
                    os.path.basename(keyring),
                )
                shutil.copyfile(keyring, dest)

                argv.append('-t')
                argv.append(
                    'keyring:suites/{}/overlay/etc/apt/trusted.gpg.d/'
                    '{}'.format(
                        apt_suite,
                        os.path.basename(keyring),
                    )
                )

                # debootstrap only supports one keyring and one apt source,
                # so we take the first one
                break

            components = self.apt_sources[0].components

            if components:
                argv.append('-t')
                argv.append('components:{}'.format(
                    self.yaml_dump_one_line(components)))

            argv.append(dest_recipe)
Simon McVittie's avatar
Simon McVittie committed

            os.rename(output + '.new', output)
Simon McVittie's avatar
Simon McVittie committed

    def ensure_local_repo(self):
        os.makedirs(os.path.dirname(self.ostree_repo), 0o755, exist_ok=True)
            'ostree',
            '--repo=' + self.ostree_repo,
            'init',
            '--mode={}'.format(self.ostree_mode),
Simon McVittie's avatar
Simon McVittie committed
        ])

    def command_runtimes(
        self,
        *,
        yaml_file,
        generate_sysroot_tarball=False,
        **kwargs
    ):
        self.ensure_local_repo()
Simon McVittie's avatar
Simon McVittie committed

        if self.runtime_branch is None:
            self.runtime_branch = self.apt_suite

        with open(yaml_file, encoding='utf-8') as reader:
Simon McVittie's avatar
Simon McVittie committed
            self.runtime_details = yaml.safe_load(reader)

        tarball = 'base-{}-{}.tar.gz'.format(
            self.apt_suite,
            ','.join(self.dpkg_archs),
Simon McVittie's avatar
Simon McVittie committed
        )

        with ExitStack() as stack:
            scratch = stack.enter_context(
                TemporaryDirectory(prefix='flatdeb.')
            )
            self.ensure_build_area()
Simon McVittie's avatar
Simon McVittie committed

            dest_recipe = os.path.join(scratch, 'flatdeb.yaml')
            shutil.copyfile(_DEBOS_RUNTIMES_RECIPE, dest_recipe)
Simon McVittie's avatar
Simon McVittie committed

            for helper in (
                'clean-up-base',
                'collect-source-code',
                'disable-services',
                'hard-link-alternatives',
                'make-flatpak-friendly',
                'platformize',
                'prepare-runtime',
                'purge-conffiles',
                'put-ldconfig-in-path',
                'usrmerge',
                'write-manifest',
            ):
                dest = os.path.join(scratch, helper)
                shutil.copyfile(
                    os.path.join(
                        os.path.dirname(__file__),
                        'flatdeb',
                        helper,
                    ),
                    dest,
                )
Simon McVittie's avatar
Simon McVittie committed

            prefix = self.runtime_details['id_prefix']

            # Do the Platform first, because we download its source
            # packages as part of preparing the Sdk
            for sdk in (False, True):
                packages = list(self.runtime_details.get('add_packages', []))

                for p in self.runtime_details.get(
                    'add_packages_multiarch', []
                ):
                    for a in self.dpkg_archs:
                        packages.append(p + ':' + a)

                if sdk:
                    runtime = prefix + '.Sdk'
                else:
                    runtime = prefix + '.Platform'

                ostree_prefix = '{}-ostree-{}-{}'.format(
                    runtime,
                    ','.join(self.dpkg_archs),
                    self.runtime_branch,
                )
                out_tarball = ostree_prefix + '.tar.gz'

                argv = [
                    'debos',
                    '--artifactdir={}'.format(self.build_area),
                    '--scratchsize=8G',
                    '-t', 'architecture:{}'.format(self.primary_dpkg_arch),
                    '-t', 'flatpak_arch:{}'.format(self.flatpak_arch),
                    '-t', 'suite:{}'.format(self.apt_suite),
                    '-t', 'ospack:{}'.format(tarball),
                    '-t', 'ostree_prefix:{}'.format(ostree_prefix),
                    '-t', 'ostree_tarball:{}'.format(out_tarball + '.new'),
                    '-t', 'runtime:{}'.format(runtime),
                    '-t', 'runtime_branch:{}'.format(self.runtime_branch),
                    '-t', 'strip_source_version_suffix:{}'.format(
                        self.strip_source_version_suffix),
                ]

                if packages:
                    logger.info('Installing packages:')
                    packages.sort()

                    for p in packages:
                        logger.info('- %s', p)

                    argv.append('-t')
                    argv.append('packages:{}'.format(
                        self.yaml_dump_one_line(packages)))

                    dest = os.path.join(scratch, 'runtimes', runtime)
                    os.makedirs(dest, 0o755, exist_ok=True)
                    dest = os.path.join(dest, 'packages.yaml')

                    with open(dest, 'w', encoding='utf-8') as writer:
                        yaml.safe_dump(packages, stream=writer)

                script = self.runtime_details.get('post_script', '')

                if script:
                    dest = os.path.join(scratch, 'post_script')

                    with open(dest, 'w', encoding='utf-8') as writer:
                        writer.write('#!/bin/sh\n')
                        writer.write(script)
                        writer.write('\n')

                    os.chmod(dest, 0o755)
                    argv.append('-t')
                    argv.append('post_script:post_script')

                if sdk:
                    sources_prefix = '{}-sources-{}-{}'.format(
                        runtime,
                        ','.join(self.dpkg_archs),
                        self.runtime_branch,
                    )
                    sources_tarball = sources_prefix + '.tar.gz'
                    if generate_sysroot_tarball:
                        sysroot_prefix = '{}-sysroot-{}-{}'.format(
                            runtime,
                            ','.join(self.dpkg_archs),
                            self.runtime_branch,
                        )
                        sysroot_tarball = sysroot_prefix + '.tar.gz'
                        argv.append('-t')
                        argv.append('sysroot_prefix:{}'.format(sysroot_prefix))
                        argv.append('-t')
                        argv.append(
                            'sysroot_tarball:{}'.format(
                                sysroot_tarball + '.new'))
                    else:
                        sysroot_prefix = None
                        sysroot_tarball = None
                    sdk_details = self.runtime_details.get('sdk', {})
                    sdk_packages = list(sdk_details.get('add_packages', []))
                    argv.append('-t')
                    argv.append('sdk:yes')
                    argv.append('-t')
                    argv.append('sources_tarball:' + sources_tarball + '.new')
                    argv.append('-t')
                    argv.append('sources_prefix:' + sources_prefix)

                    for p in sdk_details.get('add_packages_multiarch', []):
                        for a in self.dpkg_archs:
                            sdk_packages.append(p + ':' + a)

                    if sdk_packages:
                        logger.info('Installing extra packages for SDK:')
                        sdk_packages.sort()

                        for p in sdk_packages:
                            logger.info('- %s', p)

                        argv.append('-t')
                        argv.append(
                            'sdk_packages:{}'.format(
                                self.yaml_dump_one_line(sdk_packages)))

                        dest = os.path.join(scratch, 'runtimes', runtime)
                        os.makedirs(dest, 0o755, exist_ok=True)
                        dest = os.path.join(dest, 'sdk_packages.yaml')

                        with open(dest, 'w', encoding='utf-8') as writer:
                            yaml.safe_dump(sdk_packages, stream=writer)

                    script = sdk_details.get('post_script', '')

                    if script:
                        dest = os.path.join(scratch, 'sdk_post_script')

                        with open(dest, 'w', encoding='utf-8') as writer:
                            writer.write('#!/bin/sh\n')
                            writer.write(script)
                            writer.write('\n')

                        os.chmod(dest, 0o755)
                        argv.append('-t')
                        argv.append('sdk_post_script:sdk_post_script')
                else:   # not sdk
                    platform_details = self.runtime_details.get('platform', {})
                    script = platform_details.get('post_script', '')

                    if script:
                        dest = os.path.join(scratch, 'platform_post_script')

                        with open(dest, 'w', encoding='utf-8') as writer:
                            writer.write('#!/bin/sh\n')
                            writer.write(script)
                            writer.write('\n')

                        os.chmod(dest, 0o755)
                        argv.append('-t')
                        argv.append(
                            'platform_post_script:platform_post_script')
                overlay = os.path.join(scratch, 'runtimes', runtime, 'overlay')
                self.create_flatpak_manifest_overlay(
                    overlay, prefix, runtime, sdk=sdk)

                argv.append(dest_recipe)
                    if sysroot_prefix is not None:
                        assert sysroot_tarball is not None
                        output = os.path.join(self.build_area, sysroot_tarball)
                        os.rename(output + '.new', output)

                        output = os.path.join(
                            self.build_area, sysroot_prefix + '.Dockerfile')

                        with open(
                            os.path.join(
                                os.path.dirname(__file__), 'flatdeb',
                                'Dockerfile.in'),
                            'r',
                            encoding='utf-8',
                        ) as reader:
                            content = reader.read()

                        content = content.replace(
                            '@sysroot_tarball@', sysroot_tarball)

                        with open(
                            output + '.new', 'w', encoding='utf-8'
                        ) as writer:
                            writer.write(content)

                        os.rename(output + '.new', output)

                    logger.info('Committing %s to OSTree', sources_tarball)
                    output = os.path.join(self.build_area, sources_tarball)
                    os.rename(output + '.new', output)
                    subprocess.check_call([
                        'time',
                        'ostree',
                        '--repo=' + self.ostree_repo,
                        'commit',
                        '--branch=runtime/{}.Sources/{}/{}'.format(
                            runtime,
                            self.flatpak_arch,
                            self.runtime_branch,
                        ),
                        '--subject=Update',
                        '--tree=tar={}'.format(output),
                        '--fsync=false',
                        '--tar-autocreate-parents',
                    ])

                output = os.path.join(self.build_area, out_tarball)
                logger.info('Committing %s to OSTree', out_tarball)
                os.rename(output + '.new', output)
                subprocess.check_call([
                    'time',
                    'ostree',
                    '--repo=' + self.ostree_repo,
                    'commit',
                    '--branch=runtime/{}/{}/{}'.format(
                        runtime,
                        self.flatpak_arch,
                        self.runtime_branch,
                    ),
                    '--subject=Update',
                    '--tree=tar={}'.format(output),
                    '--fsync=false',
                    '--tar-autocreate-parents',
                ])

            # Don't keep the history in this working repository:
            # if history is desired, mirror the commits into a public
            # repository and maintain history there.
                'time',
                'ostree',
                '--repo=' + self.ostree_repo,
                'prune',
                '--refs-only',
                '--depth=1',
            ])
Simon McVittie's avatar
Simon McVittie committed

                'time',
Simon McVittie's avatar
Simon McVittie committed
                'flatpak',
                'build-update-repo',
                self.ostree_repo,
Simon McVittie's avatar
Simon McVittie committed
            ])

            if self.export_bundles:
                for suffix in ('.Platform', '.Sdk'):
                    bundle = '{}-{}-{}.bundle'.format(
                        prefix + suffix,
                        ','.join(self.dpkg_archs),
                        self.runtime_branch,
                    )
                    output = os.path.join(self.build_area, bundle)

                        'time',
                        'flatpak',
                        'build-bundle',
                        '--runtime',
                        self.ostree_repo,
                        output + '.new',
                        prefix + suffix,
                        self.runtime_branch,
Simon McVittie's avatar
Simon McVittie committed

                    os.rename(output + '.new', output)
Simon McVittie's avatar
Simon McVittie committed

    def configure_apt(self, overlay):
Simon McVittie's avatar
Simon McVittie committed
        """
        Configure apt. We only do this once, so that all chroots
        created from the same base have their version numbers
        aligned.
        """
        os.makedirs(os.path.join(overlay, 'etc', 'apt'), 0o755, exist_ok=True)
Simon McVittie's avatar
Simon McVittie committed

        with open(
            os.path.join(overlay, 'etc', 'apt', 'sources.list'),
            'w',
            encoding='utf-8'
        ) as writer:
            for source in self.apt_sources:
                writer.write('{}\n'.format(source))

            for keyring in self.apt_keyrings:
                if os.path.exists(os.path.join('suites', keyring)):
                    keyring = os.path.join('suites', keyring)
                elif os.path.exists(keyring):
                    pass
                    raise RuntimeError('Cannot open {}'.format(keyring))

                shutil.copyfile(
                    os.path.abspath(keyring),
                    os.path.join(
                        overlay,
                        'etc', 'apt', 'trusted.gpg.d',
                        os.path.basename(keyring),
                    ),
                )
Simon McVittie's avatar
Simon McVittie committed

    def create_flatpak_manifest_overlay(
        self,
        overlay,
        prefix,
        runtime,
        sdk=False,
    ):
        metadata = os.path.join(overlay, 'metadata')
        os.makedirs(os.path.dirname(metadata), 0o755, exist_ok=True)

        keyfile = GLib.KeyFile()