Skip to content
Snippets Groups Projects
apt-install 4.02 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.

"""
Install the given packages.

This is basically debos' apt action, but with more debugging, and without
doing `apt-get update`.
"""

import argparse
import logging
import subprocess
import sys
import yaml

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


logger = logging.getLogger('flatdeb.apt-install')


def main():
    parser = argparse.ArgumentParser(
        description='Install the given packages'
    )
    parser.add_argument(
        '--with-recommends', action='store_true', dest='recommends',
        default=False)
    parser.add_argument(
        '--without-recommends', action='store_false', dest='recommends',
        default=False)
    parser.add_argument(
        '--debug', action='store_true', default=False)
    parser.add_argument('sysroot')
    parser.add_argument('package_files', nargs='+')

    args = parser.parse_args()

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

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

    options = []        # type: typing.List[str]
    packages = []       # type: typing.List[str]
    if args.debug:
        options.append('-oDebug::pkgDepCache::AutoInstall=true')
        options.append('-oDebug::pkgDepCache::Marker=true')
        options.append('-oDebug::pkgPolicy=true')
        options.append('-oDebug::pkgProblemResolver=true')
        options.append('-oDebug::pkgProblemResolver::ShowScores=true')

    if not args.recommends:
        options.append('--no-install-recommends')

    for p in args.package_files:
        with open(p, encoding='utf-8') as reader:
            packages.extend(yaml.safe_load(reader))

    subprocess.check_call(in_chroot + [
        'apt-get', '-y',
    ] + options + ['install'] + packages)

    subprocess.check_call(in_chroot + [
        'apt-get', 'clean',
    ])

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)