Beispiel #1
0
def get_options(path=None):
    """
    Return the global configuration options. This method also expands the user home folder
    specified by '~'. In addition, the yaml config file is validated after parse.
    If the path is not specified, the ~/.cleanmymac.yaml configuration file is looked up, if not
    found, the global configuration is set to an empty dict.

    :param path: optional path to a yaml configuration file
    :type path: str
    :return: a python object containing the actual configuration
    :rtype: dict
    """
    cfg = {}
    if not path:
        path = os.path.join(os.path.expanduser('~'), GLOBAL_CONFIG_FILE)
    path = os.path.abspath(path)
    debug_param('global config', path)
    if not os.path.exists(path):
        warn('global configuration file not found, proceeding without.')
    else:
        with open(path, 'r+') as cfg:
            cfg = load(cfg)
    return validate_yaml_config(cfg)
Beispiel #2
0
def get_options(path=None):
    """
    Return the global configuration options. This method also expands the user home folder
    specified by '~'. In addition, the yaml config file is validated after parse.
    If the path is not specified, the ~/.cleanmymac.yaml configuration file is looked up, if not
    found, the global configuration is set to an empty dict.

    :param path: optional path to a yaml configuration file
    :type path: str
    :return: a python object containing the actual configuration
    :rtype: dict
    """
    cfg = {}
    if not path:
        path = os.path.join(os.path.expanduser('~'), GLOBAL_CONFIG_FILE)
    path = os.path.abspath(path)
    debug_param('global config', path)
    if not os.path.exists(path):
        warn('global configuration file not found, proceeding without.')
    else:
        with open(path, 'r+') as cfg:
            cfg = load(cfg)
    return validate_yaml_config(cfg)
Beispiel #3
0
def cli(update, dry_run, quiet, pretty_print, strict, list_targets,
        stop_on_error, config, targets_path, targets, **kwargs):
    """
    the main **run** method, responsible for creating the parser and executing the main logic in
    **cleanmymac**

    :param bool update: perform update of targets (if applicable)
    :param bool dry_run: do not execute the actions, but log the result
    :param bool quiet: quiet mode (no output), show a progressbar instead
    :param bool pretty_print: enable pretty printing with colors
    :param bool strict: if set enforce strict(er) rules when validating targets
    :param bool list_targets: list the installed targets
    :param bool stop_on_error: abort the execution on first error
    :param str config: the configuration path
    :param str targets_path: extra targets paths
    :param list targets: the targets
    """
    disable_logger('sarge')
    targets = tuple([target.lower() for target in targets])

    set_pretty_print(pretty_print)

    debug_param('update', update)
    debug_param('dry run', dry_run)
    debug_param('quiet mode', quiet)
    debug_param('pretty print', pretty_print)
    debug_param('strict mode', strict)
    debug_param('list available targets', list_targets)
    debug_param('stop on error', stop_on_error)
    debug_param('global config path', config)
    debug_param('extra targets path', targets_path)
    debug_param('targets', targets)
    debug('')

    all_targets = dict(iter_targets())
    if is_debug():
        debug("Detailed information about registered targets")
        debug(get_targets_as_table(simple=False, fancy=False))

    if dry_run:
        verbose = True
    else:
        verbose = not quiet
    debug_param('verbose', verbose)

    if targets:
        target_names = set(targets)
    else:
        target_names = set(all_targets.keys())

    if update:
        echo_warn(
            'updating may result in an increase of the total space taken by the cleanup targets',
            verbose=verbose)

    echo_info('found {0} registered cleanup targets'.format(len(all_targets)),
              verbose=verbose)

    config = get_options(path=config)
    # register extra targets if any
    for pth in _config_targets_path(config):
        register_yaml_targets(pth)
    if targets_path and os.path.isdir(targets_path):
        register_yaml_targets(targets_path)

    if list_targets:
        echo_warn(get_targets_as_table(simple=True, fancy=True))
    else:
        with progressbar(verbose,
                         all_targets.items(),
                         label='Processing cleanup targets:',
                         width=40) as all_targets_bar:
            free_space_before = get_disk_usage('/', unit=UNIT_MB).free

            for name, target_initializer in all_targets_bar:
                echo_info(_HORIZONTAL_RULE, verbose=verbose)
                if name not in target_names:
                    debug('skipping target "{0}"'.format(name))
                    continue
                echo_target('\ncleaning: {0}'.format(name.upper()),
                            verbose=verbose)
                target_cfg = config[name] if name in config else None
                debug("got target configuration: {0}".format(
                    pformat(target_cfg)))

                try:
                    target = target_initializer(target_cfg,
                                                update=update,
                                                verbose=verbose,
                                                strict=strict)

                    if not isinstance(target, Target):
                        error(
                            'expected an instance of Target, instead got: {0}'.
                            format(target))
                        continue

                    if dry_run:
                        echo_warn(target.describe())
                    else:
                        target()
                except Exception, ex:
                    error(
                        'could not cleanup target "{0}". Reason:\n{1}'.format(
                            name, ex))
                    if stop_on_error:
                        break

                if not verbose:
                    sleep(
                        PROGRESSBAR_ADVANCE_DELAY
                    )  # nicer progress bar display for fast executing targets

            free_space_after = get_disk_usage('/', unit=UNIT_MB).free
            if not dry_run:
                echo_info('\ncleanup complete', verbose=verbose)
                echo_success('\nfreed {0:.3f} MB of disk space'.format(
                    free_space_after - free_space_before),
                             verbose=True,
                             nl=verbose)
Beispiel #4
0
def cli(update, dry_run, quiet, pretty_print, strict, list_targets, stop_on_error, config, targets_path, targets, **kwargs):
    """
    the main **run** method, responsible for creating the parser and executing the main logic in
    **cleanmymac**

    :param bool update: perform update of targets (if applicable)
    :param bool dry_run: do not execute the actions, but log the result
    :param bool quiet: quiet mode (no output), show a progressbar instead
    :param bool pretty_print: enable pretty printing with colors
    :param bool strict: if set enforce strict(er) rules when validating targets
    :param bool list_targets: list the installed targets
    :param bool stop_on_error: abort the execution on first error
    :param str config: the configuration path
    :param str targets_path: extra targets paths
    :param list targets: the targets
    """
    disable_logger('sarge')
    targets = tuple([target.lower() for target in targets])

    set_pretty_print(pretty_print)

    debug_param('update', update)
    debug_param('dry run', dry_run)
    debug_param('quiet mode', quiet)
    debug_param('pretty print', pretty_print)
    debug_param('strict mode', strict)
    debug_param('list available targets', list_targets)
    debug_param('stop on error', stop_on_error)
    debug_param('global config path', config)
    debug_param('extra targets path', targets_path)
    debug_param('targets', targets)
    debug('')

    all_targets = dict(iter_targets())
    if is_debug():
        debug("Detailed information about registered targets")
        debug(get_targets_as_table(simple=False, fancy=False))

    if dry_run:
        verbose = True
    else:
        verbose = not quiet
    debug_param('verbose', verbose)

    if targets:
        target_names = set(targets)
    else:
        target_names = set(all_targets.keys())

    if update:
        echo_warn('updating may result in an increase of the total space taken by the cleanup targets', verbose=verbose)

    echo_info('found {0} registered cleanup targets'.format(len(all_targets)), verbose=verbose)

    config = get_options(path=config)
    # register extra targets if any
    for pth in _config_targets_path(config):
        register_yaml_targets(pth)
    if targets_path and os.path.isdir(targets_path):
        register_yaml_targets(targets_path)

    if list_targets:
        echo_warn(get_targets_as_table(simple=True, fancy=True))
    else:
        with progressbar(verbose, all_targets.items(), label='Processing cleanup targets:',
                         width=40) as all_targets_bar:
            free_space_before = get_disk_usage('/', unit=UNIT_MB).free

            for name, target_initializer in all_targets_bar:
                echo_info(_HORIZONTAL_RULE, verbose=verbose)
                if name not in target_names:
                    debug('skipping target "{0}"'.format(name))
                    continue
                echo_target('\ncleaning: {0}'.format(name.upper()), verbose=verbose)
                target_cfg = config[name] if name in config else None
                debug("got target configuration: {0}".format(pformat(target_cfg)))

                try:
                    target = target_initializer(target_cfg, update=update, verbose=verbose, strict=strict)

                    if not isinstance(target, Target):
                        error('expected an instance of Target, instead got: {0}'.format(target))
                        continue

                    if dry_run:
                        echo_warn(target.describe())
                    else:
                        target()
                except Exception, ex:
                    error('could not cleanup target "{0}". Reason:\n{1}'.format(name, ex))
                    if stop_on_error:
                        break

                if not verbose:
                    sleep(PROGRESSBAR_ADVANCE_DELAY)  # nicer progress bar display for fast executing targets

            free_space_after = get_disk_usage('/', unit=UNIT_MB).free
            if not dry_run:
                echo_info('\ncleanup complete', verbose=verbose)
                echo_success('\nfreed {0:.3f} MB of disk space'.format(free_space_after - free_space_before),
                             verbose=True, nl=verbose)