Skip to content
Snippets Groups Projects
run.py 99.4 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 typing
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


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 SignedBy:
    def __str__(self) -> str:
        raise NotImplementedError


class SignedByFingerprint(SignedBy):
    def __init__(self, fingerprint: str, subkeys: bool = True) -> None:
        self.fingerprint = fingerprint
        self.subkeys = subkeys

    def __str__(self):
        return '{}{}'.format(
            self.fingerprint,
            '!' if not self.subkeys else '',
        )


class SignedByKeyring(SignedBy):
    def __init__(self, path: str) -> None:
        self.path = path

    def __str__(self):
        return self.path


class AptSource:
    def __init__(
        self,
        kind,                       # type: str
        uri,                        # type: str
        suite,                      # type: str
        components=('main',),       # type: typing.Sequence[str]
        signed_by=(),               # type: typing.Sequence[SignedBy]
        trusted=False
    ):
        self.kind = kind
        self.uri = uri
        self.suite = suite
        self.components = components
        self.signed_by = set(signed_by)
        # 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 set(self.signed_by) != set(other.signed_by):
            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
        signed_by: typing.List[str] = []
        rest: typing.List[str] = []
        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].startswith('['):
            for i in range(1, len(tokens)):
                token = tokens[i].lstrip('[')
                option = token.rstrip(']')

                if option == 'trusted=yes':
                    trusted = True
                elif option.startswith('signed-by='):
Loading
Loading full blame...