lrossett / centos / centpkg

Forked from centos/centpkg 3 years ago
Clone
Blob Blame History Raw
import os
import sys
import argparse
import logging
import configparser

import pyrpkg.utils
import pyrpkg

import centpkg.api as centapi


class Commands(pyrpkg.Commands):
    def __init__(self, *args, **kwargs):
        """Init the object and some configuration details."""
        super(Commands, self).__init__(*args, **kwargs)

    @pyrpkg.utils.cached_property
    def lookasidecache(self):
        """A helper to interact with the lookaside cache

        We override this because we need a different download path.
        """
        return centapi.lookaside.CentOSLookasideCache(
            self.lookasidehash, self.lookaside, self.lookaside_cgi)


def get_log(client):
    """
    Returns a logging level based on client params.
    :param client: pyrpkg.cli.cliClient
    :return: str
    """
    if client.args.v:
        return logging.DEBUG
    if client.args.q:
        return logging.WARNING
    return logging.INFO


def run(*args, **kwargs):
    """
    Runs centpkg command based on args and kwargs.
    It will use sys.argv as cli arguments if no args or kwargs are provided.

    :param args: list
    :param kwargs: dict
    :return: None
    """
    cli_name = kwargs.get('cli_name', 'centpkg')
    parser = argparse.ArgumentParser(add_help=False)

    parser.add_argument(
        '-C', '--config', help='Specify a config file to use',
        default=f'/etc/{cli_name}/{cli_name}.conf')
    (args, other) = parser.parse_known_args()

    if not os.path.exists(args.config) and not other[-1] in ['--help', '-h']:
        sys.stderr.write(f'Invalid config file {cli_name} {args.config}\n')
        sys.exit(1)

    config = configparser.SafeConfigParser()
    config.read(args.config)

    client = centapi.cli.CentPkgCli(config)
    client.do_imports(cli_name)
    client.parse_cmdline()

    if not client.args.path:
        try:
            client.args.path = pyrpkg.utils.getcwd()
        except Exception:
            sys.stderr.write('Could not get current path, have you deleted it?\n')
            sys.exit(1)

    log = pyrpkg.log
    client.setupLogging(log)
    log.setLevel(get_log(client))

    try:
        sys.exit(client.args.command())
    except KeyboardInterrupt:
        pass