Skip to content
Snippets Groups Projects
purge-conffiles 3.81 KiB
Newer Older
#!/usr/bin/python3
# flatdeb — build Flatpak runtimes from Debian packages
#
# Copyright © 2016-2017 Simon McVittie
# Copyright © 2017-2019 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.

import argparse
import logging
import os
import subprocess
import sys

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


logger = logging.getLogger('flatdeb.purge-conffiles')


def main():
    # type: (...) -> None

    parser = argparse.ArgumentParser(
        description='Purge leftover configuration files'
    )
    parser.add_argument('sysroot')

    args = parser.parse_args()

    in_chroot = [
        'systemd-nspawn',
        '--directory={}'.format(args.sysroot),
        '--as-pid2',
        '--tmpfs=/run/lock',
        'env',
        'DEBIAN_FRONTEND=noninteractive',
        'SUDO_FORCE_REMOVE=yes',
    ]

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

    logger.info('Purging leftover configuration files:')

    unwanted = set()        # type: typing.Set[str]

    with subprocess.Popen(in_chroot + [
        'dpkg-query',
        '--show',
        '-f', r'${Status}:${Package}\n',
    ], stdout=subprocess.PIPE, universal_newlines=True) as dpkg_query:
        for line in dpkg_query.stdout:
            if line == '\n':
                continue

            if ':' not in line:
                raise AssertionError('dpkg-query produced {!r}'.format(line))

            status, package = line.rsplit(':')

            if status.endswith(' config-files'):
                logger.info('- %s', package)
                unwanted.add(package)

        if dpkg_query.wait() != 0:
            raise subprocess.CalledProcessError(
                returncode=dpkg_query.returncode,
                cmd=dpkg_query.args,
            )

    if unwanted:
        subprocess.check_call(in_chroot + [
            'dpkg',
            '--purge',
            '--force-depends',
            '--force-remove-essential',
        ] + list(unwanted))


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)