Mini Shell

Direktori : /opt/sharedrads/cms_tools/
Upload File :
Current File : //opt/sharedrads/cms_tools/common.py

#! /opt/imh-python/bin/python3
"""Common setup for cms_tools"""
# Author: Daniel K

import sys
import logging
from argparse import ArgumentParser
from logging.handlers import SysLogHandler
from rads import setup_logging

from cms_tools.cms import CMSFind, load_modules

from cms_tools.helpers import find_start_path


LOGGER = logging.getLogger(__name__)


def parse_args(with_interactivity=False):
    '''
    Parse command line arguments
    '''

    parser = ArgumentParser(description=__doc__)
    # fmt: off
    parser.add_argument(
        "-m", "--modules", metavar='MODULE', action='store', nargs='+',
        help="Search only for specified modules.",
    )
    parser.add_argument(
        "-l", "--list", action='store_true',
        help="List available modules and quit.",
    )
    parser.add_argument(
        "-d", "--depth", action='store', type=int, default=0,
        help="Set the maximum depth to search. "
        "The default is 1 if path is set, or 8 otherwise.",
    )
    output_group = parser.add_mutually_exclusive_group()
    output_group.add_argument(
        '-v', '--verbose', dest='loglevel',
        action='store_const', const='debug',
        help="Use verbose logging.",
    )
    output_group.add_argument(
        '-q', '--quiet', dest='loglevel',
        action='store_const', const='critical',
        help='Log only critical errors',
    )
    output_group.add_argument(
        '--loglevel', dest='loglevel',
        choices=['error', 'info', 'debug', 'warning', 'critical'],
        help="Specify the verbosity of logging output. "
        "The default is 'warning'.",
    )
    parser.add_argument(
        "-o", "--output", action='store', default='',
        help="Output logging to the specified file.",
    )
    if with_interactivity:
        parser.add_argument(
            "-i", "--interactive", action='count',
            help="Increase interactivity.",
        )
    parser.add_argument(
        'user_path',
        metavar='(USER|PATH)',
        nargs='?',
        help="cPanel user or path. Path must be in a user's home directory, "
        "and may not be a relative path.",
    )
    # fmt: on
    args = parser.parse_args()

    if args.loglevel is None:
        logging_level = logging.WARNING
    else:
        logging_level = getattr(logging, args.loglevel.upper())

    if args.output == '':
        setup_syslog_logging(loglevel=logging_level)
    else:
        setup_logging(path=args.output, loglevel=logging_level, print_out=False)

    if args.list:
        cms_search = CMSFind('List modules', 0)
        modules_list = load_modules(cms_search, args.modules)
        print("Available modules: %s" % ', '.join(modules_list))
        sys.exit(0)

    path = find_start_path(args.user_path)

    if path is None:
        sys.exit(1)

    if args.depth == 0:
        if '/' in path:
            depth = 8
        else:
            depth = 1
    else:
        depth = args.depth

    if with_interactivity:
        interactivity = args.interactive
    else:
        interactivity = 0

    return depth, path, args.modules, interactivity


def setup_syslog_logging(loglevel: int):
    logger = logging.getLogger()
    logger.setLevel(loglevel)
    out_fmt = logging.Formatter(fmt='%(levelname)s: %(message)s')
    log_fmt = logging.Formatter(fmt='cms_tools: %(levelname)s: %(message)s')
    stdout = logging.StreamHandler(stream=sys.stdout)
    stdout.setFormatter(out_fmt)
    stdout.setLevel(loglevel)
    syslog = SysLogHandler(address='/dev/log')
    syslog.setFormatter(log_fmt)
    syslog.setLevel(loglevel)
    logger.addHandler(syslog)
    return logger


def cms_tools_setup(allow_interactivity=False):
    '''Common setup for cms_tools, returning the CMS_Find instance'''

    (max_depth, start_path, include_modules, interactivity) = parse_args(
        allow_interactivity
    )

    cms_search = CMSFind(start_path, max_depth, interactivity)

    load_modules(cms_search, include_modules)

    LOGGER.debug(
        "Starting path: %s, Maxumim depth: %d",
        start_path,
        max_depth,
    )

    return cms_search

Zerion Mini Shell 1.0