Skip to content
Snippets Groups Projects
collect-source-code 8.52 KiB
Newer Older
#!/usr/bin/python3

# flatdeb — build Flatpak runtimes from Debian packages
#
# Copyright © 2016-2017 Simon McVittie
# Copyright © 2017-2018 Collabora Ltd.
#
# 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.

"""
Fetch source code for packages installed in the given sysroot.
"""

import argparse
import logging
import os
import re
import subprocess
import sys


logger = logging.getLogger('flatdeb.collect-source-code')


class InstalledPackage:
    def __init__(self, fields):
        self.binary = fields[0]
        self.binary_version = fields[1]
        self.source = fields[2]

        if self.source.endswith(')'):
            self.source, self.source_version = self.source.rstrip(')').split(' (')
        else:
            self.source_version = self.binary_version

            if not self.source:
                self.source = self.binary

        self.installed_size = fields[3]

    def __str__(self):
        return '{}_{}'.format(self.binary, self.binary_version)

    def __hash__(self):
        return hash(self.binary) ^ hash(self.binary_version)

    def __eq__(self, other):
        if isinstance(other, InstalledPackage):
            return (
                self.binary,
                self.binary_version,
            ) == (
                other.binary,
                other.binary_version,
            )
        else:
            return NotImplemented


class SourceRequired:
    def __init__(self, source, source_version):
        self.source = source
        self.source_version = source_version

    def __str__(self):
        return 'src:{}_{}'.format(self.source, self.source_version)

    def __hash__(self):
        return hash(self.source) ^ hash(self.source_version)

    def __eq__(self, other):
        if isinstance(other, SourceRequired):
            return (
                self.source,
                self.source_version,
            ) == (
                other.source,
                other.source_version,
            )
        else:
            return NotImplemented


def read_manifest(path):
    ret = []

    with open(path, encoding='utf-8') as reader:
        for line in reader:
            line = line.rstrip('\n')

            if not line:
                continue

            if line.startswith('#'):
                continue

            assert '\t' in line, repr(line)
            ret.append(InstalledPackage(line.rstrip('\n').split('\t')))

    return ret


def read_built_using(path):
    ret = set()

    with open(path, encoding='utf-8') as reader:
        for line in reader:
            line = line.rstrip('\n')

            if line.startswith('#'):
                continue

            package, source, version = line.split('\t')
            s = SourceRequired(source, version)
            logger.info(
                '%s was Built-Using %s',
                package, s)
            ret.add(s)

    return ret


def main():
    parser = argparse.ArgumentParser(
        description='Collect source code',
    )
    parser.add_argument('--strip-source-version-suffix', default='')
    parser.add_argument('sysroot')

    args = parser.parse_args()

    strip_source_version_suffix = None

    if args.strip_source_version_suffix:
        strip_source_version_suffix = re.compile(
            '(?:' + args.strip_source_version_suffix + ')$')

    in_chroot = [
        'systemd-nspawn',
        '--directory={}'.format(args.sysroot),
        '--as-pid2',
        'env',
    ]

    for var in ('ftp_proxy', 'http_proxy', 'https_proxy', 'no_proxy'):
        if var in os.environ:
            in_chroot.append('{}={}'.format(var, os.environ[var]))

    manifest = os.path.join(args.sysroot, 'usr', 'manifest.dpkg')
    platform_manifest = os.path.join(
        args.sysroot, 'usr', 'manifest.dpkg.platform')
    built_using = os.path.join(
        args.sysroot, 'usr', 'manifest.dpkg.built-using')
    platform_built_using = os.path.join(
        args.sysroot, 'usr', 'manifest.dpkg.built-using.platform')

    sdk_packages = read_manifest(manifest)
    packages = sdk_packages[:]
    sources_required = set()

    if os.path.exists(platform_manifest):
        platform_packages = read_manifest(manifest)
    else:
        platform_packages = []

    for p in platform_packages:
        logger.info('Package in Platform: %s', p)

        if p not in sdk_packages:
            logger.warning('Package in Platform but not SDK: %s', p)
            packages.append(p)

    for p in sdk_packages:
        if p not in platform_packages:
            logger.info('Additional package in SDK: %s', p)

    for p in packages:
        sources_required.add(SourceRequired(p.source, p.source_version))

    sources_required |= read_built_using(built_using)

    if os.path.exists(platform_built_using):
        sources_required |= read_built_using(platform_built_using)

    sources = []
    missing_sources = set()

    for s in sources_required:
        source = s.source
        source_version = s.source_version

        # TODO: Is this necessary any more?
        source = source.split(':', 1)[0]

        if strip_source_version_suffix is not None:
            source_version = strip_source_version_suffix.sub(
                '', source_version)

        sources.append('{}={}'.format(source, source_version))

    try:
        subprocess.check_call(in_chroot + [
            'sh', '-euc',
            'dir="$1"; shift; mkdir -p "$dir"; cd "$dir"; "$@"',
            'sh',                       # argv[0]
            '/ostree/source/files',     # working directory
            'apt-get', '-y', '--download-only', '-q', '-q',
            '-oAPT::Get::Only-Source=true', 'source',
        ] + sources)
    except subprocess.CalledProcessError:
        logger.warning(
            'Unable to download some sources as a batch, trying '
            'to download sources individually')

        for source in sources:
            try:
                subprocess.check_call(in_chroot + [
                    'sh', '-euc',
                    'dir="$1"; shift; mkdir -p "$dir"; cd "$dir"; "$@"',
                    'sh',                       # argv[0]
                    '/ostree/source/files',     # working directory
                    'apt-get', '-y', '--download-only', '-q', '-q',
                    '-oAPT::Get::Only-Source=true', 'source',
                    source,
                ])
            except subprocess.CalledProcessError:
                # Non-fatal for now
                logger.warning(
                    'Unable to get source code for %s', source)
                missing_sources.add(source)
                source_package = source.split('=', 1)[0]
                subprocess.call(in_chroot + [
                    'apt-cache', 'showsrc', source_package,
                ])

    if missing_sources:
        logger.warning('Missing source packages:')

        for p in sorted(missing_sources):
            logger.warning('- %s', p)

        logger.warning('Check that this runtime is GPL-compliant!')

if __name__ == '__main__':
    if sys.stderr.isatty():
        try:
            import colorlog
        except ImportError:
            pass
        else:
            formatter = colorlog.ColoredFormatter(
                '%(log_color)s%(levelname)s:%(name)s:%(reset)s %(message)s')
            handler = logging.StreamHandler()
            handler.setFormatter(formatter)
            logging.getLogger().addHandler(handler)
    else:
        logging.basicConfig()

    logging.getLogger().setLevel(logging.DEBUG)

    try:
        main()
    except KeyboardInterrupt:
        raise SystemExit(130)
    except subprocess.CalledProcessError as e:
        logger.error('%s', e)
        raise SystemExit(1)