Esempio n. 1
0
def test_make_pass_decorator_args(runner):
    """
    Test to check that make_pass_decorator doesn't consume arguments based on
    invocation order.
    """
    class Foo(object):
        title = 'foocmd'

    pass_foo = click.make_pass_decorator(Foo)

    @click.group()
    @click.pass_context
    def cli(ctx):
        ctx.obj = Foo()

    @cli.command()
    @click.pass_context
    @pass_foo
    def test1(foo, ctx):
        click.echo(foo.title)

    @cli.command()
    @pass_foo
    @click.pass_context
    def test2(ctx, foo):
        click.echo(foo.title)

    result = runner.invoke(cli, ['test1'])
    assert not result.exception
    assert result.output == 'foocmd\n'

    result = runner.invoke(cli, ['test2'])
    assert not result.exception
    assert result.output == 'foocmd\n'
Esempio n. 2
0
def pass_client(f):
    """Decorator that passes a :class:`~ethclient.APIClient` instance and
    handles unsuccessful requests as well as failed connections by printing an
    error message.
    """
    raw_pass_client = click.make_pass_decorator(APIClient)
    return raw_pass_client(handle_connection_errors(f))
Esempio n. 3
0
def test_ensure_context_objects(runner):
    class Foo(object):
        def __init__(self):
            self.title = 'default'

    pass_foo = click.make_pass_decorator(Foo, ensure=True)

    @click.group()
    @pass_foo
    def cli(foo):
        pass

    @cli.command()
    @pass_foo
    def test(foo):
        click.echo(foo.title)

    result = runner.invoke(cli, ['test'])
    assert not result.exception
    assert result.output == 'default\n'
Esempio n. 4
0
def test_get_context_objects_no_ensuring(runner):
    class Foo(object):
        def __init__(self):
            self.title = 'default'

    pass_foo = click.make_pass_decorator(Foo)

    @click.group()
    @click.pass_context
    def cli(ctx):
        ctx.obj = Foo()
        ctx.obj.title = 'test'

    @cli.command()
    @pass_foo
    def test(foo):
        click.echo(foo.title)

    result = runner.invoke(cli, ['test'])
    assert not result.exception
    assert result.output == 'test\n'
Esempio n. 5
0
def test_get_context_objects_missing(runner):
    class Foo(object):
        pass

    pass_foo = click.make_pass_decorator(Foo)

    @click.group()
    @click.pass_context
    def cli(ctx):
        pass

    @cli.command()
    @pass_foo
    def test(foo):
        click.echo(foo.title)

    result = runner.invoke(cli, ['test'])
    assert result.exception is not None
    assert isinstance(result.exception, RuntimeError)
    assert "Managed to invoke callback without a context object " \
        "of type 'Foo' existing" in str(result.exception)
Esempio n. 6
0
        self._loaded_app = rv
        return rv

    @contextmanager
    def conditional_context(self, with_context=True):
        """Creates an application context or not, depending on the
        given parameter but always works as context manager.
        """
        if with_context:
            with self.load_app().app_context() as ctx:
                yield ctx
        else:
            yield None


pass_script_info = click.make_pass_decorator(ScriptInfo)


def without_appcontext(f):
    """Marks a click callback so that it does not get a app context
    created.  This only works for commands directly registered to
    the toplevel system.  This really is only useful for very
    special commands like the runserver one.
    """
    f.__flask_without_appcontext__ = True
    return f


class FlaskGroup(click.Group):
    """Special subclass of the a regular click group that supports
    loading more commands from the configured Flask app.
Esempio n. 7
0
# coding: utf-8
from operator import itemgetter
import urllib
import webbrowser

import click

from .github import GitHub

pass_github = click.make_pass_decorator(GitHub)


class GitHubCli(object):
    """Encapsulates the GitHubCli.

    Attributes:
        * None.
    """
    @click.group()
    @click.pass_context
    def cli(ctx):
        """Main entry point for GitHubCli.

        Args:
            * ctx: An instance of click.core.Context that stores an instance
                 of GitHub used to interact with the GitHub API.

        Returns:
            None.
        """
        # Create a GitHub object and remember it as as the context object.
Esempio n. 8
0
    def modify(
        self,
        href: str,
        add_content: Optional[List[str]] = None,
        remove_content: Optional[List[str]] = None,
        base_version: Optional[str] = None,
    ) -> Any:
        body: Dict[str, Any] = {}
        if add_content is not None:
            body["add_content_units"] = add_content
        if remove_content is not None:
            body["remove_content_units"] = remove_content
        if base_version is not None:
            body["base_version"] = base_version
        return self.pulp_ctx.call(
            self.MODIFY_ID,
            parameters={self.HREF: href},
            body=body,
        )


EntityFieldDefinition = Union[None, str, PulpEntityContext]
##############################################################################
# Decorator to access certain contexts


pass_pulp_context = click.make_pass_decorator(PulpContext)
pass_entity_context = click.make_pass_decorator(PulpEntityContext)
pass_repository_context = click.make_pass_decorator(PulpRepositoryContext)
pass_repository_version_context = click.make_pass_decorator(PulpRepositoryVersionContext)
Esempio n. 9
0
                if target.startswith(os.path.join(self.home, venv) + '/'):
                    return venv

        for script in os.listdir(self.bin_dir):
            exe = os.path.join(self.bin_dir, script)
            target = real_readlink(exe)
            if target is None:
                continue
            venv = _find_venv(target)
            if venv is not None:
                venvs[venv].append(script)

        return sorted(venvs.items())


pass_repo = click.make_pass_decorator(Repo, ensure=True)


@click.group()
@click.option('--home', type=click.Path(), default=None,
              help='The folder that contains the virtualenvs.')
@click.option('--bin-dir', type=click.Path(), default=None,
              help='The path where the scripts are symlinked to.')
@click.version_option()
@pass_repo
def cli(repo, home, bin_dir):
    """pipsi is a tool that uses virtualenv and pip to install shell
    tools that are separated from each other.
    """
    if home is not None:
        repo.home = home
Esempio n. 10
0
            click.echo(
                "About to create working dir at {}".format(self.local_working_dir)
            )
            click.confirm("Do you want to continue?", abort=True)
            # Append /video to working dir path since videos are stored separately
            os.makedirs(self.local_working_dir / "video")
        else:
            click.echo(
                "Working dir already exists at {}".format(self.local_working_dir)
            )

    def __repr__(self):
        return "<BackupContext %r>" % self.local_working_dir


pass_backup_context = click.make_pass_decorator(BackupContext)


@click.group()
@click.option(
    "--bucket-name", prompt="Bucket name", help="The s3 bucket name to upload files to."
)
@click.option(
    "--year",
    prompt="Photo year",
    default="{:02}".format(datetime.today().year),
    help="The year dir to use in the working dir path (e.g. 2017).",
)
@click.option(
    "--month",
    prompt="Photo month",
Esempio n. 11
0
    """
    Helper class to store data to be passed between CLI commands.
    """

    def __init__(self):
        self.vsq = VSQFileGroup()
        self.target = TargetGroup()

    def populate_vsq(self):
        """
        Uses the cached VSQ files to populate the cached target group.
        """
        self.target.populate_vsq(self.vsq)


pass_cli_data = click.make_pass_decorator(CLIData, ensure=True)


@click.group()
@click.option('--log-level', default='CRITICAL', help='Logging level [DEBUG,INFO,WARNING,ERROR,CRITICAL]')
@click.option('-s', '--sound-file', multiple=True, type=click.File('r'), help='Input sound definition files')
@click.option('-t', '--target-file', multiple=True, type=click.File('r'), help='Output target definition files')
@pass_cli_data
def cli(cli_data, log_level, sound_file, target_file):
    """
    File converter for VOCALOID announcer voice banks.
    """
    set_logging(log_level)

    cli_data.vsq.populate(sound_file)
    cli_data.target.populate(target_file)
Esempio n. 12
0
        gandi = ctx.obj
        needs_update = False
        value, args = click.Option.handle_parse_result(self, ctx, opts, args)

        if value is not None:
            previous_value = gandi.get(global_=True, key=self.name)
            if isinstance(self.type, GandiChoice):
                if value == previous_value:
                    needs_update = True
                value = self.type.convert_deprecated_value(value)
            if not previous_value or needs_update:
                gandi.configure(global_=True, key=self.name, val=value)
        return value, args


def option(*param_decls, **attrs):
    """Attach an option to the command.

    All positional arguments are passed as parameter declarations
    to :class:`Option`, all keyword arguments are forwarded unchanged.
    This is equivalent to creating an :class:`Option` instance manually and
    attaching it to the :attr:`Command.params` list.
    """
    def decorator(f):
        _param_memo(f, GandiOption(param_decls, **attrs))
        return f
    return decorator

# create a decorator to pass the Gandi object as context to click calls
pass_gandi = click.make_pass_decorator(GandiContextHelper, ensure=True)
Esempio n. 13
0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Client utilities."""

import uuid

import click
import yaml

from renku.api import LocalClient


def _uuid_representer(dumper, data):
    """Add UUID serializer for YAML."""
    return dumper.represent_str(str(data))


yaml.add_representer(uuid.UUID, _uuid_representer)

pass_local_client = click.make_pass_decorator(LocalClient, ensure=True)
Esempio n. 14
0
import logging
import sys

import click

import miio  # noqa: E402
from miio.click_common import ExceptionHandlerGroup, validate_ip, validate_token
from miio.miioprotocol import MiIOProtocol

_LOGGER = logging.getLogger(__name__)
pass_dev = click.make_pass_decorator(miio.PhilipsEyecare)


def validate_brightness(ctx, param, value):
    value = int(value)
    if value < 1 or value > 100:
        raise click.BadParameter("Should be a positive int between 1-100.")
    return value


def validate_minutes(ctx, param, value):
    value = int(value)
    if value < 0 or value > 60:
        raise click.BadParameter("Should be a positive int between 1-60.")
    return value


def validate_scene(ctx, param, value):
    value = int(value)
    if value < 1 or value > 3:
        raise click.BadParameter("Should be a positive int between 1-3.")
Esempio n. 15
0
from workflow_executor import helpers
import click
from kubernetes.client.rest import ApiException

################################
### COMMON OPTIONS


class State(object):
    def __init__(self):
        self.verbosity = 0
        self.debug = False
        self.kubeconfig = "~/.kube/config"


pass_state = click.make_pass_decorator(State, ensure=True)


def verbosity_option(f):
    def callback(ctx, param, value):
        state = ctx.ensure_object(State)
        state.verbosity = value
        return value

    return click.option('-v',
                        '--verbose',
                        count=True,
                        expose_value=False,
                        help='Enables verbosity.',
                        callback=callback)(f)
Esempio n. 16
0
    ENCRYPTION_ENABLED = 7
    ENCRYPTION_DISABLED = 8
    LAUNCHD_ENABLED = 10
    LAUNCHD_DISABLED = 11
    WARN_MISCONFIGURED = 100
    ERROR_MISSING_KEY = 200


class Configuration(object):
    def __init__(self):
        self.confDir = POOF_CONFIG_DIR
        self.confFiles = POOF_CONFIG_FILES
        self.verbose = False


globalConf = click.make_pass_decorator(Configuration, ensure=True)
_startPoof = datetime.now()

# *** functions ***


@click.group()
@click.option('--confdir',
              default=POOF_CONFIG_DIR,
              help='poof configuration directory',
              show_default=True)
@click.option('--poofconf',
              default=POOF_CONFIG_FILES['poof.conf'],
              help='poof configuration file',
              show_default=True)
@click.option('--rcloneconf',
Esempio n. 17
0
File: cli.py Progetto: yola/pyutu
from __future__ import print_function
import sys
import json
import time
import click
import pyutu.client as pyutu

pass_pc = click.make_pass_decorator(pyutu.PricingContext, ensure=True)

CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])
regions = sorted(pyutu.regions.keys())
services = sorted(pyutu.svcs.keys())


@click.group(context_settings=CONTEXT_SETTINGS)
@click.option('--region',
              default='us-west-2',
              type=click.Choice(regions),
              show_default=True,
              help='The region from which a price is to be determined.')
@click.option('--terms',
              type=click.Choice(['ondemand', 'reserved']),
              default="ondemand",
              show_default=True,
              help='The general payment terms of the product.')
@click.option('--log',
              default='NOTSET',
              show_default=True,
              type=click.Choice(
                  ['INFO', 'DEBUG', 'WARNING', 'ERROR', 'CRITICAL', 'NOTSET']),
              help='Set a specific log level')
Esempio n. 18
0
#!/usr/bin/env python

import os
import click
import json
import time
from utility.common import launch, print_action, get_visual_studio_version, error_exit
from config import ProjectConfig

__author__ = "Ryan Sheffer"
__copyright__ = "Copyright 2018, Ryan Sheffer Open Source"
__credits__ = ["Ryan Sheffer", "VREAL"]

pass_config = click.make_pass_decorator(ProjectConfig, ensure=True)


@click.group()
@click.option(
    '--script',
    '-s',
    type=click.STRING,
    required=True,
    help=
    'The Project Script which defines the projects paths, build steps, and extra information.'
)
@pass_config
def tools(config: ProjectConfig, script):
    if not os.path.isfile(script):
        error_exit('No build script defined! Use the -s arg')

    with open(script, 'r') as fp:
Esempio n. 19
0
# SPDX-License-Identifier: Apache-2.0
"""
Main aswfdocker command line implementation using click
"""
import os
import logging
import click

from aswfdocker import builder, migrater, aswfinfo, constants, utils

logger = logging.getLogger("build-images")

pass_build_info = click.make_pass_decorator(aswfinfo.ASWFInfo)


@click.group()
@click.option(
    "--repo-root",
    "-r",
    envvar="ASWF_REPO_ROOT",
    default=".",
    help="Root of aswf-docker repository",
)
@click.option("--repo-uri", "-u", help="URL of current Git Repository")
@click.option("--source-branch", "-b", help="Current git branch name")
@click.option("--verbose", "-v", is_flag=True, help="Enables verbose mode.")
@click.version_option("1.0")
@click.pass_context
def cli(ctx, repo_root, repo_uri, source_branch, verbose):
    """aswfdocker is a command line interface to build ASWF Docker packages and ci images
    """
Esempio n. 20
0
# -*- coding: utf-8 -*-

import click
from .openligadb import OpenLigaDB
from . import helpers


pass_openligadb = click.make_pass_decorator(OpenLigaDB)


@click.group(invoke_without_command=True)
@click.pass_context
def cli(ctx):
    """
    Bundesliga results and stats for hackers.

    bundesliga-cli is a CLI tool that provides access to Bundesliga
    results and stats.

    Uses openligadb-json-api.heroku.com API which is itself a JSON wrapper
    around the OpenligaDB API (http://www.openligadb.de).
    """
    ctx.obj = OpenLigaDB()


@cli.command()
@click.option('--matchday', '-d', help='Defines the matchday')
@click.option('--league', '-l', help='Defines the league (e.g. bl1, bl2, bl3)')
@click.option('--season', '-s', help='Defines the season (e.g. 2014, 2013)')
@pass_openligadb
def matchday(openligadb, season, matchday, league):
Esempio n. 21
0
import click
import os
import sys

from morenines.index import Index
from morenines.ignores import Ignores
from morenines.repository import Repository
from morenines.util import get_files, get_hash, get_new_and_missing, abort
from morenines.output import info, success, warning, error, print_filelists
from morenines.exceptions import PathError, NoEffectWarning


pass_repository = click.make_pass_decorator(Repository, ensure=True)

def default_repo_path():
    return os.getcwd()

_common_params = {
    'ignored': click.option('-i', '--ignored/--no-ignored', 'show_ignored', default=False, help="Enable/disable showing files ignored by the ignores patterns."),
    'color': click.option('--color/--no-color', 'show_color', default=True, help="Enable/disable colorized output."),
}

def common_params(*param_names):
    def real_decorator(func):
        for param_name in param_names:
            func = _common_params[param_name](func)
        return func

    return real_decorator

"""Configuration commands."""
import click
from builtins import filter
from helium_commander import (Sensor, Element, Client, Configuration, Device,
                              DeviceConfiguration, JSONParamType,
                              ResourceParamType, device_mac_option)

pass_client = click.make_pass_decorator(Client)


@click.group()
def cli():
    """Operations on configurations."""
    pass


@cli.command()
@click.argument('config', required=False)
@pass_client
def list(client, config):
    """List configurations.

    Lists one CONFIGuration or all configurations associated with the
    authorized organization.

    """
    include = [DeviceConfiguration]
    if config:
        configs = [Configuration.lookup(client, config, include=include)]
    else:
        configs = Configuration.all(client, include=include)
Esempio n. 23
0
File: click.py Progetto: 20c/munge
 def pass_context(cls):
     return click.make_pass_decorator(cls, ensure=True)
Esempio n. 24
0
from __future__ import absolute_import, print_function, unicode_literals
import click
import sys
import elliottlib
from kerberos import GSSError
from elliottlib import logutil, Runtime
from elliottlib.cli.common import cli
from elliottlib.exceptions import ElliottFatalError
from elliottlib.util import exit_unauthenticated, major_from_branch, minor_from_branch

LOGGER = logutil.getLogger(__name__)

pass_runtime = click.make_pass_decorator(Runtime)


#
# Get advisory numbers for making puddles
#
@cli.command("puddle-advisories", short_help="Get advisory numbers for making puddles")
@click.option("--filter-id", '-f',
              default=elliottlib.constants.errata_puddle_advisory_filter,
              help="A custom filter id to list from")
@click.option('--details', '-d', is_flag=True, default=False,
              help="Print details about the found advisories to STDERR")
# @click.option("-n", default=6,
#               help="Return only N latest results (default: 6)")
@pass_runtime
def puddle_advisories_cli(runtime, filter_id, details):
    """Print a comma separated list of advisory numbers which can be used
when filling in the 'errata_whitelist' parameter in a signed puddle
config.
Esempio n. 25
0
        self._loaded_app = rv
        return rv

    @contextmanager
    def conditional_context(self, with_context=True):
        """Creates an application context or not, depending on the
        given parameter but always works as context manager.
        """
        if with_context:
            with self.load_app().app_context() as ctx:
                yield ctx
        else:
            yield None


pass_script_info = click.make_pass_decorator(ScriptInfo)


def without_appcontext(f):
    """Marks a click callback so that it does not get a app context
    created.  This only works for commands directly registered to
    the toplevel system.  This really is only useful for very
    special commands like the runserver one.
    """
    f.__flask_without_appcontext__ = True
    return f


class FlaskGroup(click.Group):
    """Special subclass of the a regular click group that supports
    loading more commands from the configured Flask app.
Esempio n. 26
0
    for setting in settings:
        cur = setting.currentValue
        print("%s* %s (%s, value: %s, type: %s)" %
              (' ' * depth, setting.title, setting.target,
               click.style(cur, bold=True), setting.type))
        for opt in setting.candidate:
            if not opt.isAvailable:
                logging.debug("Unavailable setting %s", opt)
                continue
            click.echo(
                click.style("%s  - %s (%s)" %
                            (' ' * depth, opt.title, opt.value),
                            bold=opt.value == cur))


pass_dev = click.make_pass_decorator(Device)


@click.group(invoke_without_command=False)
@click.option("--endpoint", envvar="SONGPAL_ENDPOINT", required=False)
@click.option('-d', '--debug', default=False, count=True)
@click.option('--post', is_flag=True, required=None)
@click.option('--websocket', is_flag=True, required=None)
@click.pass_context
@click.version_option()
@coro
async def cli(ctx, endpoint, debug, websocket, post):
    lvl = logging.INFO
    if debug:
        lvl = logging.DEBUG
        click.echo("Setting debug level to %s" % debug)
Esempio n. 27
0
import click
from helium_commander import Client, Sensor, Element
from helium_commander import device_mac_option, device_sort_option
from helium_commander.commands import timeseries


pass_client = click.make_pass_decorator(Client)


@click.group()
def cli():
    """Operations on physical or virtual sensors.
    """
    pass


@cli.command()
@click.argument('sensor', required=False)
@device_mac_option
@device_sort_option
@pass_client
def list(client, sensor, mac, **kwargs):
    """List sensors.

    Lists information for a given SENSOR or all sensors in the
    organization.

    """
    if sensor:
        sensors = [Sensor.lookup(client, sensor, mac=mac)]
    else:
Esempio n. 28
0
import sys
import ast
import json
import click

from collections import OrderedDict

from linchpin.cli import LinchpinCli
from linchpin.exceptions import LinchpinError
from linchpin.cli.context import LinchpinCliContext
from linchpin.shell.click_default_group import DefaultGroup
from linchpin.shell.mutually_exclusive import MutuallyExclusiveOption
import six


pass_context = click.make_pass_decorator(LinchpinCliContext, ensure=True)
CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])


def _handle_results(ctx, results, return_code):
    """
    Handle results from the RunDB output and Ansible API.
    Either as a return value (retval) when running with the
    ansible console enabled, or as a list of TaskResult
    objects, and a return value.

    If a target fails along the way, this method immediately exits with the
    appropriate return value (retval). If the ansible console is disabled, an
    error message will be printed before exiting.

    :param results:
Esempio n. 29
0
    def get_command(self, ctx, name):
        """
        Get a bound command method
        @type   ctx:    Context
        @param  name:   Command name
        @type   name:   str
        @rtype: object
        """
        try:
            mod = importlib.import_module('ips_vagrant.commands.{name}'.format(name=name))
            return mod.cli
        except (ImportError, AttributeError):
            return


pass_context = click.make_pass_decorator(Context, ensure=True)


@click.command(cls=IpsvCLI, context_settings=CONTEXT_SETTINGS)
@click.option('-v', '--verbose', count=True, default=1,
              help='-v|vv|vvv Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and '
                   '3 for debug')
@click.option('-c', '--config', type=click.Path(dir_okay=False, resolve_path=True),
              envvar='IPSV_CONFIG_PATH', default='/etc/ipsv/ipsv.conf', help='Path to the IPSV configuration file')
@click.version_option(__version__)
@pass_context
def cli(ctx, verbose, config):
    """
    IPS Vagrant Management Utility
    """
    assert isinstance(ctx, Context)
Esempio n. 30
0
import os
import sys
import ast
import json
import click

from collections import OrderedDict

from linchpin.cli import LinchpinCli
from linchpin.exceptions import LinchpinError
from linchpin.cli.context import LinchpinCliContext
from linchpin.shell.click_default_group import DefaultGroup
from linchpin.shell.mutually_exclusive import MutuallyExclusiveOption


pass_context = click.make_pass_decorator(LinchpinCliContext, ensure=True)
CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])


def _handle_results(ctx, results, return_code):
    """
    Handle results from the RunDB output and Ansible API.
    Either as a return value (retval) when running with the
    ansible console enabled, or as a list of TaskResult
    objects, and a return value.

    If a target fails along the way, this method immediately exits with the
    appropriate return value (retval). If the ansible console is disabled, an
    error message will be printed before exiting.

    :param results:
Esempio n. 31
0
        except TypeError:
            self.fail(
                "invalid json",
                param,
                ctx,
            )
        except ValueError:
            self.fail("invalid json", param, ctx)


class Config(object):
    def __init__(self):
        pass


config = click.make_pass_decorator(Config, ensure=True)


def name_has_value(name):
    if not name:
        click.echo('Tables need names')
        return False
    else:
        return True


def more_than_one(first, second, third):
    if (first and
        (second or third)) or (second and
                               (third or first)) or (third and
                                                     (first or second)):
Esempio n. 32
0
		select_sql = """SELECT projects.name as project,
								ifnull(backers.name, '') as backer,
								pledges.amount,
								projects.target_amount,
								projects.amount_raised
							FROM projects
							LEFT JOIN pledges
							ON pledges.project_id=projects.id
							LEFT JOIN backers
							ON pledges.backer_id=backers.id
							WHERE projects.name ='{project}'""".format(project=project)
		cursor.execute(select_sql)
		return cursor.fetchall()

	def pledges_by_backer(self, backer):
		conn, cursor = self.connect_to_db()
		select_sql = """SELECT projects.name as project, pledges.amount
						FROM projects
						LEFT JOIN pledges
						ON pledges.project_id=projects.id
						LEFT JOIN backers
						ON pledges.backer_id=backers.id
						WHERE backers.name='{backer}'""".format(backer=backer)
		cursor.execute(select_sql)
		return cursor.fetchall()


# A command decorator that allows you to pass your dbhandler to nested commands
pass_dbhandler = click.make_pass_decorator(DBHandler, ensure=True)

Esempio n. 33
0
import logging
import scrapers
from utils import DataLoader

subclasses = scrapers.SiteScraper._subclasses

URLS = {
    "pnp":
    "https://www.pnp.co.za/"
    "pnpstorefront/pnp/en/All-Products/Fresh-Food/Vegetables/c/vegetables703655157",
    "woolworths":
    "https://www.woolworths.co.za/"
    "cat/Food/Fruit-Vegetables-Salads/_/N-lllnam",
}

pass_state = click.make_pass_decorator(dict, ensure=True)


@click.group(chain=True)
@click.command()
@click.option(
    "--store",
    default="pnp",
    help=f"select the store to scrape: {list(subclasses.keys())}",
)
@pass_state
def scrape(state, store):
    try:
        scraper_cls = subclasses[store]
        scraper_obj = scraper_cls()
        state['docs'] = scraper_obj.scrape_site(URLS[store])
Esempio n. 34
0
import time
from pprint import pformat as pf
from typing import Any, List  # noqa: F401

import click
from appdirs import user_cache_dir
from tqdm import tqdm

import miio  # noqa: E402
from miio.click_common import (ExceptionHandlerGroup, validate_ip,
                               validate_token, LiteralParamType)
from .device import UpdateState
from .updater import OneShotServer

_LOGGER = logging.getLogger(__name__)
pass_dev = click.make_pass_decorator(miio.Device, ensure=True)


@click.group(invoke_without_command=True, cls=ExceptionHandlerGroup)
@click.option('--ip', envvar="MIROBO_IP", callback=validate_ip)
@click.option('--token', envvar="MIROBO_TOKEN", callback=validate_token)
@click.option('-d', '--debug', default=False, count=True)
@click.option('--id-file',
              type=click.Path(dir_okay=False, writable=True),
              default=user_cache_dir('python-miio') + '/python-mirobo.seq')
@click.version_option()
@click.pass_context
def cli(ctx, ip: str, token: str, debug: int, id_file: str):
    """A tool to command Xiaomi Vacuum robot."""
    if debug:
        logging.basicConfig(level=logging.DEBUG)
Esempio n. 35
0
        # The context object is a Daemon object
        daemon = ctx.obj

        def subcommand(debug=False):
            """Call a daemonocle action."""
            if daemon.detach and debug:
                daemon.detach = False

            daemon.do_action(name)

        # Override the docstring for the function so that it shows up
        # correctly in the help output
        subcommand.__doc__ = daemon.get_action(name).__doc__

        if name == 'start':
            # Add a --debug option for start
            subcommand = click.option(
                '--debug', is_flag=True,
                help='Do NOT detach and run in the background.'
            )(subcommand)

        # Make it into a click command
        subcommand = click.command(
            name, options_metavar=self.options_metavar)(subcommand)

        return subcommand


# Make a pass decorator for passing the Daemon object
pass_daemon = click.make_pass_decorator(Daemon)
Esempio n. 36
0
            msg %= args
        click.echo(msg, file=sys.stdout)

    def error(self, msg, *args):
        """Logs a message to stderr."""
        if args:
            msg %= args
        click.echo(msg, file=sys.stderr)

    def vlog(self, msg, *args):
        """Logs a message to stderr only if verbose is enabled."""
        if self.verbose:
            self.log(msg, *args)


pass_environment = click.make_pass_decorator(Environment, ensure=True)


class CommandAdapter(click.MultiCommand):
    cmd_folder = os.path.abspath(os.path.join(os.path.dirname(__file__), 'commands'))

    def list_commands(self, ctx):
        rv = []
        for filename in os.listdir(self.cmd_folder):
            if filename.endswith('.py') and filename.startswith('cmd_'):
                rv.append(filename[4:-3])
        rv.sort()
        return rv

    def get_command(self, ctx, name):
        try:
Esempio n. 37
0
    def __init__(self):
        # self.home = home
        self.config = {}
        # self.verbose = False

    def set_config(self, key, value):
        self.config[key] = value
        # cur_dir = os.path.split(os.path.realpath(__file__))[0]
        cur_dir = os.path.abspath(os.path.expanduser("~/.wio"))
        db_file_path = '%s/config.json' % cur_dir
        open("%s/config.json"%cur_dir,"w").write(json.dumps(self.config))
        # if self.verbose:
        #     click.echo('config[%s] = %s' % (key, value), file=sys.stderr)


pass_wio = click.make_pass_decorator(Wio, ensure=True)

def sigint_handler(signum, frame):
    click.echo()
    exit(0)

@click.group()
# @click.option('--wio-home', envvar='REPO_HOME', default='.wio',
#               metavar='PATH', help='Changes the wiository folder location.')
# @click.option('--config', nargs=2, multiple=True,
#               metavar='KEY VALUE', help='Overrides a config key/value pair.')
# @click.option('--verbose', '-v', is_flag=True,
#               help='Enables verbose mode.')
@click.version_option(version)
@click.pass_context
def cli(ctx):
Esempio n. 38
0
        if value is not None:
            previous_value = gandi.get(global_=True, key=self.name)
            if isinstance(self.type, GandiChoice):
                if value == previous_value:
                    needs_update = True
                value = self.type.convert_deprecated_value(value)
            if not previous_value or needs_update:
                gandi.configure(global_=True, key=self.name, val=value)
        opts[self.name] = value
        value, args = click.Option.handle_parse_result(self, ctx, opts, args)
        return value, args


def option(*param_decls, **attrs):
    """Attach an option to the command.

    All positional arguments are passed as parameter declarations
    to :class:`Option`, all keyword arguments are forwarded unchanged.
    This is equivalent to creating an :class:`Option` instance manually and
    attaching it to the :attr:`Command.params` list.
    """
    def decorator(f):
        _param_memo(f, GandiOption(param_decls, **attrs))
        return f

    return decorator


# create a decorator to pass the Gandi object as context to click calls
pass_gandi = click.make_pass_decorator(GandiContextHelper, ensure=True)
Esempio n. 39
0
import os
import click


class Repo(object):

    def __init__(self, home):
        self.home = home

    def __repr__(self):
        return '<Repo %r>' % self.home


pass_repo = click.make_pass_decorator(Repo)


@click.group()
@click.option('--repo-home', envvar='REPO_HOME', default='.repo')
@click.pass_context
def cli(ctx, repo_home):
    """Repo is a command line tool that showcases how to build complex
    command line interfaces with Click.
    """
    # Create a repo object and remember it as as the context object.
    ctx.obj = Repo(os.path.abspath(repo_home))


@cli.command()
@click.argument('src')
@click.argument('dest', required=False)
@click.option('--shallow/--deep', default=False,
Esempio n. 40
0
    def get_env(self):
        if self._env is not None:
            return self._env
        from lektor.environment import Environment
        env = Environment(self.get_project(), load_plugins=False)
        self._env = env
        return env

    def load_plugins(self, reinstall=False):
        from .packages import load_packages
        from .pluginsystem import initialize_plugins
        load_packages(self.get_env(), reinstall=reinstall)
        initialize_plugins(self.get_env())


pass_context = click.make_pass_decorator(Context, ensure=True)


def validate_language(ctx, param, value):
    if value is not None and not is_valid_language(value):
        raise click.BadParameter('Unsupported language "%s".' % value)
    return value


@click.group()
@click.option('--project',
              type=click.Path(),
              help='The path to the lektor project to work with.')
@click.option('--language',
              default=None,
              callback=validate_language,
Esempio n. 41
0
# -*- coding: utf-8 -*-
from beer.process import Brewery
import click
import os
import git

pass_beer = click.make_pass_decorator(Brewery)


@click.group()
@click.option('--config', '-c', default=os.path.expanduser('~/.config/beer-review/beer-review.conf'))
@click.option('--session', '-s', default=os.path.expanduser('~/.config/beer-review/jira-session.pickle'))
@click.pass_context
def main(brewery, config, session):
    """CLI for managing your JIRA / Gerrit / git workflow."""
    try:
        repo = git.Repo(os.path.curdir)
    except git.InvalidGitRepositoryError as e:
        click.echo('Current directory is not a git repo!')
        return -1
    brewery.obj = Brewery(config_file_path=config, session_file_path=session, repo=repo)


@main.command('brew',
              help='Work on an existing JIRA or create a new ticket. Not specifying an ISSUE_ID creates a new JIRA.')
@click.argument('issue_id', required=False, default=None)
@click.option('--issue-type', '-t', default='Bug', type=click.Choice(['Bug', 'New Feature', 'Task', 'Improvement']))
@click.option('--summary', '-s', default=None)
@click.option('--description', '-d', default=None, required=False)
@pass_beer
def init_jira(brewery, issue_id, issue_type, summary, description):
Esempio n. 42
0
import sys
import click
import logging
from click_datetime import Datetime
from pprint import pformat as pf

if sys.version_info < (3, 4):
    print("To use this script you need python 3.4 or newer! got %s" %
          sys.version_info)
    sys.exit(1)

from pyHS100 import (SmartDevice, SmartPlug, SmartBulb, SmartStrip,
                     Discover)  # noqa: E402

pass_dev = click.make_pass_decorator(SmartDevice)


@click.group(invoke_without_command=True)
@click.option('--ip',
              envvar="PYHS100_IP",
              required=False,
              help='The IP address of the device to connect to. This option '
              'is deprecated and will be removed in the future; use --host '
              'instead.')
@click.option('--host',
              envvar="PYHS100_HOST",
              required=False,
              help='The host name or IP address of the device to connect to.')
@click.option('--alias',
              envvar="PYHS100_NAME",
              required=False,
Esempio n. 43
0
    """Setup up data for the rest of the functions
    """
    def __init__(self, criteria):
        self.MAXIMUM_ITERATIONS = 30
        self.SUBPIXEL_RESOLUTION = 0.001

        self.criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER,
                         self.MAXIMUM_ITERATIONS,
                         self.SUBPIXEL_RESOLUTION)

    # prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0)
    # Set it the the maximum size array needed.
    objp = np.zeros((7 * 6, 3), np.float32)
    objp[:, :2] = np.mgrid[0:7, 0:6].T.reshape(-1, 2)

pass_configuration = click.make_pass_decorator(Configuration)


@click.group()
@click.command()
@click.argument('images', nargs=-1)
@pass_configuration()
def cli(images):

    # Arrays to store object points and image points from all the images.
    # objpoints = []  # 3d point in real world space
    # imgpoints = []  # 2d points in image plane.

    [show_image(image) for image in images]

Esempio n. 44
0
    return decorated


def object_print(fun):
    def object_print_decorator(fun, *args, **kwargs):
        obj = fun(*args, **kwargs)
        oprint(obj)

    return decorator.decorate(fun, object_print_decorator)


def add_typed_subcommands(type_):
    def add_fun(fun, attribute_name):
        @fun.command(name=attribute_name)
        @click.make_pass_decorator(type_)
        def type_cmd(obj):
            print(getattr(obj, attribute_name))

    def decorator(fun):
        for attribute_name, attribute_type in type_.openapi_types.items():
            add_fun(fun, attribute_name)

        setattr(fun, 'invoke_without_command', True)

        return fun

    return decorator


pass_state = click.make_pass_decorator(State)
Esempio n. 45
0
# stdlib imports
import sys

# third-party imports
import click


class Logger(object):

    def __init__(self):
        self.buffer = sys.stdout

    def log(self, msg, *args, **kwargs):
        """Logs a message to stdout."""
        if args:
            msg %= args
        click.echo(msg, file=self.buffer, **kwargs)

    def style(self, msg, *args, **kwargs):
        """Wrapper around click.style to allow modules to access this
        functionality via the context object without having to depend on
        click.
        """
        return click.style(msg, *args, **kwargs)


pass_logger = click.make_pass_decorator(Logger, ensure=True)
Esempio n. 46
0
    LAMBDA_BULDERS_LOGGER_NAME,
    SamCliLogger,
    SAM_CLI_FORMATTER,
    SAM_CLI_LOGGER_NAME,
)
from .options import debug_option, region_option, profile_option
from .context import Context
from .command import BaseCommand
from .global_config import GlobalConfig

LOG = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO,
                    format="%(asctime)s %(message)s",
                    datefmt="%Y-%m-%d %H:%M:%S")

pass_context = click.make_pass_decorator(Context)

global_cfg = GlobalConfig()


def common_options(f):
    """
    Common CLI options used by all commands. Ex: --debug
    :param f: Callback function passed by Click
    :return: Callback function
    """
    f = debug_option(f)
    return f


def aws_creds_options(f):
Esempio n. 47
0
import os
import sys

CONTEXT_SETTINGS = dict(auto_envvar_prefix='DIDATA')
DEFAULT_OUTPUT_TYPE = 'pretty'


class DiDataCLIClient(object):
    def __init__(self):
        self.verbose = False

    def init_client(self, user, password, region):
        self.node = DimensionDataNodeDriver(user, password, region=region)
        self.backup = DimensionDataBackupDriver(user, password, region=region)

pass_client = click.make_pass_decorator(DiDataCLIClient, ensure=True)
cmd_folder = os.path.abspath(os.path.join(os.path.dirname(__file__),
                             'commands'))


class DiDataCLI(click.MultiCommand):

    def list_commands(self, ctx):
        rv = []
        for filename in os.listdir(cmd_folder):
            if filename.endswith('.py') and \
               filename.startswith('cmd_'):
                rv.append(filename[4:-3])
        rv.sort()
        return rv
Esempio n. 48
0
log = logging.getLogger(__name__)

if __package__ is None:
    path = os.path.dirname(os.path.dirname(__file__))
    sys.path.insert(0, path)
    sys.path.insert(0, path + "/../")

from web3 import Web3, HTTPProvider
from microraiden.make_helpers import make_paywalled_proxy
from microraiden import utils, constants
from microraiden.config import NETWORK_CFG
from microraiden.exceptions import StateFileLocked, InsecureStateFile, NetworkIdMismatch
from microraiden.proxy.paywalled_proxy import PaywalledProxy

pass_app = click.make_pass_decorator(PaywalledProxy)


@click.group()
@click.option('--channel-manager-address',
              default=None,
              help='Ethereum address of the channel manager contract.')
@click.option('--state-file', default=None, help='State file of the proxy')
@click.option('--private-key',
              required=True,
              help='Path to private key file of the proxy',
              type=click.Path(exists=True, dir_okay=False, resolve_path=True))
@click.option(
    '--private-key-password-file',
    default=None,
    help='Path to file containing password for the JSON-encoded private key',
Esempio n. 49
0
import click
import xmlrpclib


class Config:

    def __init__(self, key):
        self.api_key = key


pass_config = click.make_pass_decorator(Config)


@click.group()
@click.option('--key', envvar='GANDI_API_KEY',
              help='User API key (overrides GANDI_API_KEY variable)')
@click.option('--url', envvar='GANDI_API_URL',
              help='Remote API endpoint (overrides GANDI_API_URL variable)')
@click.pass_context
def cli(context, key, url):
    """
    A command-line interface to manage Gandi domain configuration
    """
    context.obj = Config(key)
    context.obj.api = xmlrpclib.ServerProxy(url)


@cli.command()
@pass_config
def version(config):
    """Display API version info"""
Esempio n. 50
0
#  You may obtain a copy of the License at:
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
#  or implied. See the License for the specific language governing
#  permissions and limitations under the License.

import click
from dateutil import tz

from zenml.core.repo.global_config import GlobalConfig

pass_config = click.make_pass_decorator(GlobalConfig, ensure=True)


def title(text):
    """
    Args:
        text:
    """
    click.echo(click.style(text.upper(), fg='cyan', bold=True, underline=True))


def confirmation(text, *args, **kwargs):
    """
    Args:
        text:
        *args:
Esempio n. 51
0
File: cli.py Progetto: AEliu/flask
            raise NoAppException(
                'Could not locate a Flask application. You did not provide '
                'the "FLASK_APP" environment variable, and a "wsgi.py" or '
                '"app.py" module was not found in the current directory.'
            )

        if self.set_debug_flag:
            # Update the app's debug flag through the descriptor so that
            # other values repopulate as well.
            app.debug = get_debug_flag()

        self._loaded_app = app
        return app


pass_script_info = click.make_pass_decorator(ScriptInfo, ensure=True)


def with_appcontext(f):
    """Wraps a callback so that it's guaranteed to be executed with the
    script's application context.  If callbacks are registered directly
    to the ``app.cli`` object then they are wrapped with this function
    by default unless it's disabled.
    """
    @click.pass_context
    def decorator(__ctx, *args, **kwargs):
        with __ctx.ensure_object(ScriptInfo).load_app().app_context():
            return __ctx.invoke(f, *args, **kwargs)
    return update_wrapper(decorator, f)

Esempio n. 52
0
LOG = logging.getLogger()
click_log.basic_config(logger=LOG)
logging.basicConfig(format="%(levelname)s:%(message)s", level=logging.INFO)

PACKAGE_PATH = os.path.dirname(os.path.realpath(__file__))
"""path: path to install location of package
"""


class ContextCLI:
    def __init__(self):
        self.obj = {}
        self.cwd = os.getcwd()


PASS_CONTEXT = click.make_pass_decorator(ContextCLI, ensure=True)
CONTEXT_SETTINGS = dict(auto_envvar_prefix="TCG",
                        help_option_names=["-h", "--help"])


@click.group(context_settings=CONTEXT_SETTINGS)
@click_log.simple_verbosity_option(LOG, default="WARNING", metavar="LEVEL")
@click.version_option()
@click.option(
    "--es-host",
    "esHost",
    prompt=False,
    default=lambda: os.environ.get("TCG_ES_HOST", ""),
    help="Elasticsearch host to interact with",
)
@PASS_CONTEXT
Esempio n. 53
0
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.

from __future__ import unicode_literals
from __future__ import print_function

import click

from .github import GitHub


click.disable_unicode_literals_warning = True
pass_github = click.make_pass_decorator(GitHub)


class GitHubCli(object):
    """The GitHubCli, builds `click` commands and runs `GitHub` methods."""

    @click.group()
    @click.pass_context
    def cli(ctx):
        """Main entry point for GitHubCli.

        :type ctx: :class:`click.core.Context`
        :param ctx: An instance of click.core.Context that stores an instance
            of `github.GitHub`.
        """
        # Create a GitHub object and remember it as as the context object.
Esempio n. 54
0
File: cli.py Progetto: yingDD/flask
        else:
            if not self.app_import_path:
                raise NoAppException(
                    'Could not locate Flask application. You did not provide '
                    'the FLASK_APP environment variable.\n\nFor more '
                    'information see '
                    'http://flask.pocoo.org/docs/latest/quickstart/')
            rv = locate_app(self, self.app_import_path)
        debug = get_debug_flag()
        if debug is not None:
            rv.debug = debug
        self._loaded_app = rv
        return rv


pass_script_info = click.make_pass_decorator(ScriptInfo, ensure=True)


def with_appcontext(f):
    """Wraps a callback so that it's guaranteed to be executed with the
    script's application context.  If callbacks are registered directly
    to the ``app.cli`` object then they are wrapped with this function
    by default unless it's disabled.
    """
    @click.pass_context
    def decorator(__ctx, *args, **kwargs):
        with __ctx.ensure_object(ScriptInfo).load_app().app_context():
            return __ctx.invoke(f, *args, **kwargs)

    return update_wrapper(decorator, f)
Esempio n. 55
0
class State(object):
    ''' Maintain logging level.'''

    def __init__(self, log_name='mkdocs', level=logging.INFO):
        self.logger = logging.getLogger(log_name)
        self.logger.propagate = False
        stream = logging.StreamHandler()
        formatter = logging.Formatter("%(levelname)-7s -  %(message)s ")
        stream.setFormatter(formatter)
        self.logger.addHandler(stream)

        self.logger.setLevel(level)


pass_state = click.make_pass_decorator(State, ensure=True)


def verbose_option(f):
    def callback(ctx, param, value):
        state = ctx.ensure_object(State)
        if value:
            state.logger.setLevel(logging.DEBUG)
    return click.option('-v', '--verbose',
                        is_flag=True,
                        expose_value=False,
                        help='Enable verbose output',
                        callback=callback)(f)


def quiet_option(f):
Esempio n. 56
0
    3: logging.INFO,
    4: logging.DEBUG,
}  #: a mapping of `verbose` option counts to logging levels


class Info(object):
    """An information object to pass data between CLI functions."""
    def __init__(self):  # Note: This object must have an empty constructor.
        """Create a new instance."""
        self.verbose: int = 0
        self.ndays: int = 7


# pass_info is a decorator for functions that pass 'Info' objects.
#: pylint: disable=invalid-name
pass_info = click.make_pass_decorator(Info, ensure=True)


# Change the options to below to suit the actual options for your task (or
# tasks).
@click.command()
@click.option("--verbose", "-v", count=True, help="Enable verbose output.")
@click.option("--asassn", "-a", is_flag=True, help="Include ASAS-SN targets.")
@click.option("--fermi", "-f", is_flag=True, help="Include Fermi targets.")
@click.option("--swift", "-s", is_flag=True, help="Include Swift targets.")
@click.option("--ref_date",
              "-r",
              type=click.DateTime(),
              help='Reference date for search (default utcnow)')
@click.option("--ndays",
              "-n",
Esempio n. 57
0
import shutil

import click
from click.decorators import Group
import yaml

from . import clipboard, completion, config, checkers, importers
from .crypt import create_keys, encrypt, decrypt
from .database import Database, is_repo_url
from .table import Table
from .utils import genpass, ensure_dependencies
from .history import clone


__version__ = "1.1.1"
pass_db = click.make_pass_decorator(Database)


class AliasedGroup(click.Group):

    def get_command(self, ctx, cmd_name):
        rv = click.Group.get_command(self, ctx, cmd_name)
        if rv is not None:
            return rv
        matches = [x for x in self.list_commands(ctx)
                   if x.startswith(cmd_name)]
        if not matches:
            return None
        elif len(matches) == 1:
            return click.Group.get_command(self, ctx, matches[0])
        ctx.fail('Too many matches: %s' % ', '.join(sorted(matches)))
Esempio n. 58
0
    def pagure_user_token(self) -> str:
        token = os.getenv("PAGURE_USER_TOKEN", "")
        if token:
            return token
        return self._pagure_user_token

    @property
    def pagure_fork_token(self) -> str:
        """ this is needed to create pull requests """
        token = os.getenv("PAGURE_FORK_TOKEN", "")
        if token:
            return token
        return self._pagure_fork_token


pass_config = click.make_pass_decorator(Config)


def get_default_map_from_file() -> Optional[dict]:
    config_path = Path(".packit")
    if config_path.is_file():
        return json.loads(config_path.read_text())
    return None


@lru_cache()
def get_context_settings() -> dict:
    return dict(
        help_option_names=["-h", "--help"],
        auto_envvar_prefix="PACKIT",
        default_map=get_default_map_from_file(),
Esempio n. 59
0
File: app.py Progetto: Dascr32/tempy
import click
import os
from tempy.scripts import analyzer
from tempy.scripts import cleaner
from tempy.scripts.config import Config
from tempy.scripts import filemanager
from tempy.scripts import converter


app_config = click.make_pass_decorator(Config, ensure=True)


@click.group()
@click.version_option(version="0.7", prog_name="TEMPy")
def cli():
    pass


@cli.command()
@app_config
@click.option("--a", is_flag=True,
              help="Deletes all files and directories")
@click.option("--se", is_flag=True,
              help="Show all errors that were encountered during the last deletion")
def delete(config, a, se):
    """
    Deletes all the directory content (files, dirs)
    """
    if a and click.confirm("Delete all contents of " + config.dir_to_use + " ?"):
        click.echo("Attempting to delete: " + str(analyzer.get_entries_count()) + " entries...\n")
Esempio n. 60
0
    return str(repo).split()


def perform(method, files, repo, debug):
    """Perform an operation on a set of dotfiles."""
    for dotfile in repo.dotfiles(files):
        try:
            getattr(dotfile, method)(debug)
            if not debug:
                msg = '%s%s' % (method, 'd' if method[-1] == 'e' else 'ed')
                click.echo('%s %s' % (msg, dotfile.short_name(repo.homedir)))
        except DotfileException as err:
            click.echo(err)


pass_repos = click.make_pass_decorator(Repositories)
CONTEXT_SETTINGS = dict(auto_envvar_prefix='DOTFILES',
                        help_option_names=['-h', '--help'])


@click.group(context_settings=CONTEXT_SETTINGS)
@click.option('--repo', '-r', type=click.Path(), multiple=True,
              help='A repository path. Default: %s' % (DEFAULT_PATH))
@click.option('--dot/--no-dot', '-d/-D', default=None,
              help='Whether to remove the leading dot. Default: %s' % (
                  DEFAULT_REMOVE_LEADING_DOT))
@click.version_option(None, '-v', '--version')
@click.pass_context
def cli(ctx, repo, dot):
    """Dotfiles is a tool to make managing your dotfile symlinks in $HOME easy,
    allowing you to keep all your dotfiles in a single directory.