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

# flatdeb — build Flatpak runtimes from Debian packages
#
# Copyright 2015-2017 Simon McVittie
# Copyright 2017-2023 Collabora Ltd.
Simon McVittie's avatar
Simon McVittie committed
#
# 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
Simon McVittie's avatar
Simon McVittie committed
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_COLLECT_DBGSYM_RECIPE = os.path.join(
    os.path.dirname(__file__), 'flatdeb', 'debos-collect-dbgsym.yaml')
_DEBOS_COLLECT_SOURCE_RECIPE = os.path.join(
    os.path.dirname(__file__), 'flatdeb', 'debos-collect-source.yaml')
_DEBOS_RUNTIMES_RECIPE = os.path.join(
    os.path.dirname(__file__), 'flatdeb', 'debos-runtimes.yaml')

class AptSource:
    def __init__(
        self,
        kind,                       # type: str
        uri,                        # type: str
        suite,                      # type: str
        components=('main',),       # type: typing.Sequence[str]
        trusted=False
    ):
        self.kind = kind
        self.uri = uri
        self.suite = suite
        self.components = components
        self.trusted = trusted

        # type: (typing.Any) -> bool
        if not isinstance(other, AptSource):
            return False

        if self.kind != other.kind:
            return False

        if self.uri != other.uri:
            return False

        if self.suite != other.suite:
            return False

        if set(self.components) != set(other.components):
            return False

        if self.trusted != other.trusted:
            return False

        return True

    @classmethod
    def multiple_from_string(
        cls,        # type: typing.Type[AptSource]
        line,       # type: str
        # type: (...) -> typing.Iterable[AptSource]
        line = line.strip()
        tokens = line.split()

        if tokens[0] in ('deb', 'deb-src'):
            return (cls.from_string(line),)
        elif tokens[0] == 'both':
            return (
                cls.from_string('deb' + line[4:]),
                cls.from_string('deb-src' + line[4:]),
            )
        else:
            raise ValueError(
                'apt sources must start with "deb ", "deb-src " or "both "')

        cls,        # type: typing.Type[AptSource]
        line,       # type: str
        # type: (...) -> AptSource
        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,
        )

        # type: () -> str
        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:

    """
Loading
Loading full blame...