Exemple #1
0
    def construct_options(f):
        """
        Common CLI Options that are shared for service related commands ('start-api' and 'start_lambda')

        Parameters
        ----------
        f function
            Callback passed by Click
        port int
            port number to use

        Returns
        -------
        function
            The callback function
        """
        service_options = [
            click.option('--host',
                         default="127.0.0.1",
                         help="Local hostname or IP address to bind to (default: '127.0.0.1')"),
            click.option("--port", "-p",
                         default=port,
                         help="Local port number to listen on (default: '{}')".format(str(port)))
        ]

        # Reverse the list to maintain ordering of options in help text printed with --help
        for option in reversed(service_options):
            option(f)

        return f
Exemple #2
0
    def _produce_method(self, disassociate=False):

        method = self._produce_raw_method()

        # Apply options for user to specify the 2 resources to associate
        method = click.option(
            '--{}'.format(self.other_name.replace('_', '-')),
            type=types.Related(self.other_name),
            required=True
        )(method)
        method = click.option(
            '--{}'.format(self.res_name.replace('_', '-')),
            type=types.Related(self.res_name),
            required=True
        )(method)

        # This does the same thing as @resources.command, but without importing
        method._cli_command = True
        method._cli_command_attrs = dict(use_fields_as_options=False)

        # Define field-specific parameters that control functionality
        method._relationship = self.relationship
        method._res_name = self.res_name
        method._other_name = self.other_name
        if disassociate:
            method._internal_name = '_disassoc'
            method.__doc__ = self._produce_doc(action='disassociate')
        else:
            method._internal_name = '_assoc'
            method.__doc__ = self._produce_doc()
        return method
Exemple #3
0
 def decorate_command(command):
     command = click.option('--archive-dir', required=True, multiple=True,
                            help="The base path where materials are stored (ArchiveDir in indico.conf). "
                                 "When used multiple times, the dirs are checked in order until a file is "
                                 "found.")(command)
     command = click.option('--janitor-user-id', type=int, required=True, help="The ID of the Janitor user")(command)
     return command
Exemple #4
0
def global_options(f):
    def config_callback(ctx, option, config):
        prepare_context(ctx, config)

    def verbosity_callback(ctx, option, verbose):
        if verbose:
            logger.setLevel(logging.DEBUG)
        else:
            logger.setLevel(logging.INFO)

    config = click.option(
        '--config', '-c',
        is_eager=True,  # make sure other options can access config
        help='The config file to use.',
        default=None, metavar='PATH', expose_value=False,
        callback=config_callback
    )
    verbose = click.option(
        '--verbose', '-v',
        is_eager=True,  # make sure to log config when debugging
        help='Output debugging information.',
        is_flag=True, expose_value=False, callback=verbosity_callback
    )

    version = click.version_option(version=__version__)

    return config(verbose(version(f)))
Exemple #5
0
Fichier : cli.py Projet : 20c/ngage
def connect_options(f):
    f = click.argument('host', nargs=1)(f)
    f = click.option('--port', help='port to connect to, default per platform')(f)
    f = click.option('--type', help='type of connection')(f)
    f = click.option('--user', help='username', envvar='NGAGE_USER')(f)
    f = click.option('--password', help='password to use if not using key auth')(f)
    return f
Exemple #6
0
def debug_option(func):
    @wraps(func)
    def debug_wrapper(debug, debug_perform, **kwargs):
        if debug:
            DebugSettings.settings = DebugSettings(dict(debug))
            logging_config(DebugSettings.settings.loglevel)

        if debug_perform:
            DebugSettings.perform_settings = DebugSettings(dict(debug_perform))

        return func(**kwargs)

    f = click.option(
        '--debug-perform',
        type=click.Tuple([str, str]),
        multiple=True,
        metavar='<variable> <value>',
        help='Debug perform options.'
    )

    return f(
        click.option(
            '--debug',
            type=click.Tuple([str, str]),
            multiple=True,
            metavar='<variable> <value>',
            help='Debug options.'
        )(debug_wrapper)
    )
Exemple #7
0
def save_metadata(f):
    from mcvine import version, git_revision
    mcvine_vers = dict(version=version, git_revision=git_revision)
    def _(*args, **kwds):
        c = click.get_current_context()
        cmdpath = c.command_path
        # clean parameter dictionary
        import copy
        params = copy.deepcopy(c.params)
        for popt in provenance_opts: del params[popt]
        # deal with option --use-cache
        use_cache = kwds.pop('use_cache', None)
        save_metadata_only = kwds.pop('save_metadata_only', None)
        if use_cache and not save_metadata_only:
            path = cache_path(cmdpath, params, c.args)
            if os.path.exists(path):
                # if requested to use cache and the cache exists,
                # use it.
                logger.info("%s already exists. reuse results there" % path)
                # XXX assume the current working directory is the output directory
                out = "."
                copy_withhardlinks(path,out)
                return
        # deal with --save-metadata-only
        # construct metadata
        metadata = dict(
            cmd=cmdpath, params=params, args=c.args,
            mcvine=mcvine_vers)
        # output path
        fn = cmdpath.replace(' ', '-') + ".params"
        # save
        json.dump(metadata, open(fn, 'wt'))
        # run the cmd only if we are not just saving meta data
        # no need to continue if the only request is to save metadata
        if save_metadata_only: return
        # deal with option --keep-in-cache
        keep_in_cache = kwds.pop('keep_in_cache', None)
        if not keep_in_cache:
            return f(*args, **kwds)
        # run the command in the subprocess so that we
        # can make sure it is finished before moving on to
        # the next step
        cmd = "%s %s" % (cmdpath, arg_str(params, c.args))
        ret = sp.call(cmd, shell=True)
        if ret:
            raise RuntimeError("%s failed" % cmd)
        # add output to cache
        path = cache_path(cmdpath, params, c.args)
        if not os.path.exists(path):
            os.makedirs(path)
        # XXX assume the current working directory is the output directory
        out = "."
        copy_withhardlinks(out, path)
        return
    _.__name__ = f.__name__
    _.__doc__ = f.__doc__
    d1 = click.option("--save-metadata-only", is_flag=True)
    d2 = click.option("--keep-in-cache", is_flag=True)
    d3 = click.option("--use-cache", is_flag=True)
    return d1(d2(d3(_)))
Exemple #8
0
 def decorate_command(command):
     command = click.option("--janitor-user-id", type=int, required=True, help="The ID of the Janitor user")(command)
     command = click.option(
         "--default-group-provider", default="legacy-ldap", help="Name of the default group provider"
     )(command)
     command = super(AttachmentImporter, AttachmentImporter).decorate_command(command)
     return command
def codegen_options(f):
    f = click.option(
        "-c", "--categories", multiple=True, default=default_categories,
        type=click.Choice(all_categories),
        help="A list of the categories of inputs and outputs that should "
        "be enabled"
    )(f)
    f = click.option(
        "-f", "--param_file",
        type=click.File(),
        help="""YAML or JSON file describing the firmware module configuration to be flashed.
        This is the same file that is used for rosparam in the launch file."""
        "code"
    )(f)
    f = click.option(
        "-p", "--plugin", multiple=True, help="Enable a specific plugin"
    )(f)
    f = click.option(
        "-t", "--target", help="PlatformIO target (e.g.  upload)"
    )(f)
    f = click.option(
        "--status_update_interval", default=5,
        help="Minimum interval between driver status updates (in seconds)"
    )(f)
    return f
Exemple #10
0
def ssh_command(func):
    func = click.option(
        "-i", "--identity-file",
        type=click.File(lazy=False),
        default=str(get_private_key_path()),
        help="Path to the private key file",
        show_default=True
    )(func)
    func = click.option(
        "-b", "--batch-size",
        type=int,
        default=20,
        help="By default, command won't connect to all servers "
             "simultaneously, it is trying to process servers in batches. "
             "Negative number or 0 means connect to all hosts",
        show_default=True,
    )(func)

    @functools.wraps(func)
    @click.pass_context
    def decorator(ctx, identity_file, batch_size, *args, **kwargs):
        private_key = asyncssh.import_private_key(identity_file.read())
        batch_size = batch_size if batch_size > 0 else None
        identity_file.close()

        ctx.obj["private_key"] = private_key
        ctx.obj["batch_size"] = batch_size
        ctx.obj["event_loop"] = asyncio.get_event_loop()

        return func(*args, **kwargs)

    return decorator
Exemple #11
0
def ssh_file_operations(func):
    func = click.option(
        "--no-preserve",
        is_flag=True,
        help="The access and modification times and permissions of the "
             "original file are not set on the processed file."
    )(func)
    func = click.option(
        "--no-recursive",
        is_flag=True,
        help="The remote path points at a directory, the entire subtree "
             "under that directory is not processed"
    )(func)
    func = click.option(
        "--no-follow-symlinks",
        is_flag=True,
        help="Do not process symbolic links"
    )(func)

    @functools.wraps(func)
    @click.pass_context
    def decorator(ctx, no_preserve, no_recursive, no_follow_symlinks, *args,
                  **kwargs):
        ctx.obj["preserve"] = not no_preserve
        ctx.obj["recursive"] = not no_recursive
        ctx.obj["follow_symlinks"] = not no_follow_symlinks

        return func(*args, **kwargs)

    return decorator
Exemple #12
0
 def decorate_command(command):
     command = click.option('--rb-zodb-uri', required=True, help="ZODB URI for the room booking database")(command)
     command = click.option('--photo-path', type=click.Path(exists=True, file_okay=False),
                            help="path to the folder containing room photos")(command)
     command = click.option('--no-merged-avatars', default=False, is_flag=True,
                            help="speed up migration by not checking for merged avatars")(command)
     return command
def unified_job_template_options(method):
    """
    Adds the decorators for all types of unified job templates,
    and if the non-unified type is specified, converts it into the
    unified_job_template kwarg.
    """
    jt_dec = click.option(
        '--job-template', type=types.Related('job_template'),
        help='Use this job template as unified_job_template field')
    prj_dec = click.option(
        '--project', type=types.Related('project'),
        help='Use this project as unified_job_template field')
    inv_src_dec = click.option(
        '--inventory-source', type=types.Related('inventory_source'),
        help='Use this inventory source as unified_job_template field')

    def ujt_translation(_method):
        def _ujt_translation(*args, **kwargs):
            for fd in ['job_template', 'project', 'inventory_source']:
                if fd in kwargs and kwargs[fd] is not None:
                    kwargs['unified_job_template'] = kwargs.pop(fd)
            return _method(*args, **kwargs)
        return functools.wraps(_method)(_ujt_translation)

    return ujt_translation(
        inv_src_dec(
            prj_dec(
                jt_dec(
                    method
                )
            )
        )
    )
Exemple #14
0
Fichier : cli.py Projet : pdav/khal
def global_options(f):
    def color_callback(ctx, option, value):
        ctx.color = value

    def logfile_callback(ctx, option, path):
        ctx.logfilepath = path

    config = click.option(
        '--config', '-c',
        help='The config file to use.',
        default=None, metavar='PATH'
    )
    color = click.option(
        '--color/--no-color',
        help=('Use colored/uncolored output. Default is to only enable colors '
              'when not part of a pipe.'),
        expose_value=False, default=None,
        callback=color_callback
    )

    logfile = click.option(
        '--logfile', '-l',
        help='The logfile to use [defaults to stdout]',
        type=click.Path(),
        callback=logfile_callback,
        default=None,
        expose_value=False,
        metavar='LOGFILE',
    )

    version = click.version_option(version=__version__)

    return logfile(config(color(version(f))))
Exemple #15
0
def test_report_options():
    return _compose(
        click.option(
            "--test_output",
            type=click.Path(file_okay=True, resolve_path=True),
            callback=get_default_callback("tool_test_output.html",
                                          resolve_path=True),
            help=("Output test report (HTML - for humans) defaults to "
                  "tool_test_output.html."),
            default=None,
        ),
        click.option(
            "--test_output_text",
            type=click.Path(file_okay=True, resolve_path=True),
            callback=get_default_callback(None, resolve_path=True),
            help=("Output test report (Basic text - for display in CI)"),
            default=None,
        ),
        click.option(
            "--test_output_markdown",
            type=click.Path(file_okay=True, resolve_path=True),
            callback=get_default_callback(None, resolve_path=True),
            help=("Output test report (Markdown style - for humans & "
                  "computers)"),
            default=None,
        ),
    )
Exemple #16
0
def attrib_parser(__f: Callable) -> Callable:
    __f = click.option('-o', '--order', default='number',
                       type=click.Choice(['number', 'updated']),
                       help='Sort order for listing bugs.')(__f)
    __f = click.option('-s', '--state', default='open',
                       type=click.Choice(['open', 'closed', 'all']),
                       help='State of bugs to operate on.')(__f)
    return __f
Exemple #17
0
def global_options(f):
    config = click.option('--config', '-c', default=None, metavar='PATH',
                          help='The config file to use.')
    verbose = click.option('--verbose', '-v', is_flag=True,
                           help='Output debugging information.')
    version = click.version_option(version=__version__)

    return config(verbose(version(f)))
Exemple #18
0
def addInitFlag(app):
    """ 
  Add init flag to given clickObj: 
  calls create_example 
  """
    click.option("--init", is_flag=True, callback=create_example, expose_value=False, is_eager=True)(
        app.baseGroup.clickObj
    )
Exemple #19
0
 def decorate_command(command):
     command = click.option('--archive-dir', required=True, multiple=True,
                            help="The base path where resources are stored (ArchiveDir in indico.conf). "
                                 "When used multiple times, the dirs are checked in order until a file is "
                                 "found.")(command)
     command = click.option('--default-group-provider', required=True,
                            help="Name of the default group provider")(command)
     return command
Exemple #20
0
def print_completer_option(f):
    bash_shell_completer = textwrap.dedent(
        """\
    _globus_completion () {
      local IFS=$'\\t'
      if type globus > /dev/null; then
        COMPREPLY=( $( env COMP_LINE="$COMP_LINE" COMP_POINT="$COMP_POINT" \\
                       globus --shell-complete BASH ) )
      else
        COMPREPLY=( )
      fi
      return 0
    }
    complete -F _globus_completion -o default globus;
    """
    )
    zsh_shell_completer = textwrap.dedent(
        """\
    #compdef globus
    _globus () {
        if type globus > /dev/null; then
          eval "$(env COMMANDLINE="${words[1,$CURRENT]}" \\
                  globus --shell-complete ZSH)"
        fi
    }
    compdef _globus globus
    """
    )

    def callback(ctx, param, value):
        if not value or ctx.resilient_parsing:
            return
        if value == "BASH":
            safeprint(bash_shell_completer)
        elif value == "ZSH":
            safeprint(zsh_shell_completer)
        else:
            raise ValueError("Unsupported shell completion")
        click.get_current_context().exit(0)

    f = click.option(
        "--completer",
        "--bash-completer",
        cls=HiddenOption,
        is_eager=True,
        expose_value=False,
        flag_value="BASH",
        callback=callback,
    )(f)
    f = click.option(
        "--zsh-completer",
        cls=HiddenOption,
        is_eager=True,
        expose_value=False,
        flag_value="ZSH",
        callback=callback,
    )(f)
    return f
Exemple #21
0
    def inner_decorator(
        f, allow_anonymous=False, allow_all_authenticated=False, allow_provision=False
    ):

        # order matters here -- the preprocessor must run after option
        # application, so it has to be applied first
        if isinstance(f, click.Command):
            # if we're decorating a command, put the preprocessor on its
            # callback, not on `f` itself
            f.callback = preprocess_security_principals(f.callback)
        else:
            # otherwise, we're applying to a function, but other decorators may
            # have been applied to give it params
            # so, copy __click_params__ to preserve those parameters
            oldfun = f
            f = preprocess_security_principals(f)
            f.__click_params__ = getattr(oldfun, "__click_params__", [])

        f = click.option(
            "--identity",
            metavar="IDENTITY_ID_OR_NAME",
            help="Identity to use as a security principal",
        )(f)
        f = click.option(
            "--group", metavar="GROUP_ID", help="Group to use as a security principal"
        )(f)

        if allow_anonymous:
            f = click.option(
                "--anonymous",
                "principal",
                flag_value=("anonymous", ""),
                help=(
                    "Allow anyone access, even without logging in "
                    "(treated as a security principal)"
                ),
            )(f)
        if allow_all_authenticated:
            f = click.option(
                "--all-authenticated",
                "principal",
                flag_value=("all_authenticated_users", ""),
                help=(
                    "Allow anyone access, as long as they login"
                    "(treated as a security principal)"
                ),
            )(f)

        if allow_provision:
            f = click.option(
                "--provision-identity",
                metavar="IDENTITY_USERNAME",
                help="Identity username to use as a security principal. "
                "Identity will be provisioned if it does not exist.",
            )(f)

        return f
Exemple #22
0
Fichier : cli.py Projet : pdav/khal
def multi_calendar_option(f):
    a = click.option('--include-calendar', '-a', multiple=True, metavar='CAL',
                     help=('Include the given calendar. Can be specified '
                           'multiple times.'))
    d = click.option('--exclude-calendar', '-d', multiple=True, metavar='CAL',
                     help=('Exclude the given calendar. Can be specified '
                           'multiple times.'))

    return d(a(f))
Exemple #23
0
def submit_options(func):
    func = click.option("--commit", type=int, help="deprecated/ignored option",
                        expose_value=False)(func)
    func = click.option("--select-machine", default='match',
                        type=click.Choice(['match', 'update', 'split']),
                        help="How to select and create missing machine")(func)
    func = click.option("--merge", default="replace", show_default=True,
                        type=click.Choice(['reject', 'replace', 'append']),
                        help="Merge strategy when run already exists")(func)
    return func
Exemple #24
0
 def decorator(fn):
     fn = click.option('--dev', is_flag=True, default=False, help="Build in dev mode")(fn)
     fn = click.option('--clean/--no-clean', default=None,
                       help="Delete everything in dist. This is disabled by default for `--dev` builds.")(fn)
     fn = click.option('--url-root', default='/', metavar='PATH',
                       help='URL root from which the assets are loaded. '
                            'Defaults to / and should usually not be changed')(fn)
     if allow_watch:
         fn = click.option('--watch', is_flag=True, default=False, help="Run the watcher to rebuild on changes")(fn)
     return fn
Exemple #25
0
def lib_options(f):
    f = click.option('--sample-data-dir', expose_value=False, required=True, type=click.Path(exists=True), callback=callback,
            help=("LIBRARY: Path to directory (usually INBOX) containing the project "
            "(one dir per sample, scilife structure project/sample/flowcell/)"))(f)
    f = click.option('--insert', expose_value=False, required=True, callback=callback,
            help="LIBRARY: insert size", type=int)(f) 
    f = click.option('--std', expose_value=False, required=True, callback=callback,
            help="LIBRARY: Insert size standard deviation", type=int)(f)
    f = click.option('--orientation', type=click.Choice(['innie', 'outtie']), expose_value=False, required=True, callback=callback,
            help="LIBRARY: orientation, ie. 'innie' for paired-end and 'outtie' for mate-pairs")(f)
    return f
Exemple #26
0
def telegram_options(function):
    options = [
        click.option('-o', '--offset', default=0),
        click.option('-t', '--timeout', help="poll timeout"),
        click.option('-c', '--config', type=click.Path(dir_okay=False, exists=True))
    ]

    for option in options:
        function = option(function)

    return function
Exemple #27
0
def mode_option(f):
    o1 = click.option('-f', '--force', 'mode',
                      flag_value=Scaffold.EXISTING_OVERWRITE,
                      help='Force overwriting of existing files')
    o2 = click.option('-p', '--prompt', 'mode', default=True,
                      flag_value=Scaffold.EXISTING_PROMPT,
                      help='Prompt to overwrite existing files (default)')
    o3 = click.option('-s', '--skip', 'mode',
                      flag_value=Scaffold.EXISTING_SKIP,
                      help='Skip existing files')
    return o1(o2(o3(f)))
Exemple #28
0
def calendar_selector(f):
    a = click.option('--include-calendar', '-a', multiple=True, metavar='CAL',
                     expose_value=False, callback=_calendar_select_callback,
                     help=('Include the given calendar. Can be specified '
                           'multiple times.'))
    d = click.option('--exclude-calendar', '-d', multiple=True, metavar='CAL',
                     expose_value=False, callback=_calendar_select_callback,
                     help=('Exclude the given calendar. Can be specified '
                           'multiple times.'))

    return d(a(f))
Exemple #29
0
def apic_options(f):
    """Aggregate multiple common options into one.

    This decorator should be used by CLI commands that need an APIC client."""

    f = click.option('--apic-ip', help='APIC ip address', required=True)(f)
    f = click.option('--apic-username', help='APIC username', default=None)(f)
    f = click.option('--apic-password', help='APIC password', default=None)(f)
    f = click.option('--ssl/--no-ssl', default=True,
                     help='Whether to use SSL or not')(f)
    f = click.option('--secure/--no-secure', default=True,
                     help='Verify server certificate')(f)
    return f
Exemple #30
0
def signature_analysis(cmd):
    cmd = click.option('--model', '-m', default=None, type=click.Path(exists=True, dir_okay=False),
                       help='Path to model file.')(cmd)
    cmd = click.option('--parameter', '-p',
                       default=None,
                       type=click.Path(exists=True, dir_okay=False),
                       help='(optional) Path to parameter file.'
                       )(cmd)
    cmd = click.argument("scheme",
                         type=click.Path(exists=True, dir_okay=False),
                         required=False
                         )(cmd)
    return cmd
Exemple #31
0
        formatter.write("\n")

        formatter.write_dl(attr_tuples)
        help_text += formatter.getvalue()
        return help_text


# All the command line options defined here
FILES_ARGUMENT = click.argument(
    "files", metavar="FILE", nargs=-1, type=click.Path(exists=True)
)
HELP_OPTION = click.option(
    # add this only so I can show help text via echo_via_pager
    "--help",
    "-h",
    "help_",
    help="Show this message and exit.",
    is_flag=True,
    default=False,
    required=False,
)
WALK_OPTION = click.option(
    "--walk",
    "-w",
    is_flag=True,
    help="Walk directory tree, processing each file in the tree.",
    default=False,
)
JSON_OPTION = click.option(
    "--json",
    "-j",
    "json_",
Exemple #32
0
 def decorator(f):
     return click.option('--id',
                         help='Workspace identifier.',
                         **extra_kwargs)(f)
Exemple #33
0
from ravenml.utils.question import cli_spinner, user_confirms
from ravenml.data.interfaces import CreateInput
from ravenml.data.options import pass_create
from ravenml.data.interfaces import CreateInput, CreateOutput
from ravenml.utils.config import get_config, load_yaml_config
from ravenml.utils.aws import upload_directory

# metedata fields to exclude when printing metadata to the user
# these are specific to datasets at the moment
EXCLUDED_METADATA = ['filters', 'transforms', 'image_ids']

### OPTIONS ###
explore_details_opt = click.option(
    '-e',
    '--explore_details',
    'explore_details',
    is_flag=True,
    help=
    'Explore detailed metadata about all imagesets/datasets currently on S3 via a pager view.'
)

print_details_opt = click.option(
    '-p',
    '--print-details',
    'print_details',
    is_flag=True,
    help=
    'Print detailed metadata about all imagesets/datasets currently on S3 to the console.'
)

filter_details_opt = click.option(
    '-f',
Exemple #34
0
# -*- coding: utf-8 -*-
import click
import os
from asyncpg import utils, connect
from logging import debug, info
from .helpers import drier, timeit

DEFAULT_HOST = 'localhost'
DEFAULT_PORT = 5432
DEFAULT_DATABASE = 'musicbot_prod'
DEFAULT_USER = '******'
DEFAULT_PASSWORD = '******'

options = [
    click.option('--db-host', envvar='MB_DB_HOST', help='DB host', default=DEFAULT_HOST),
    click.option('--db-port', envvar='MB_DB_PORT', help='DB port', default=DEFAULT_PORT),
    click.option('--db-database', envvar='MB_DATABASE', help='DB name', default=DEFAULT_DATABASE),
    click.option('--db-user', envvar='MB_DB_USER', help='DB user', default=DEFAULT_USER),
    click.option('--db-password', envvar='MB_DB_PASSWORD', help='DB password', default=DEFAULT_PASSWORD)
]


class Database(object):
    def __init__(self, max_conn=100, **kwargs):
        self.set(**kwargs)
        self.max_conn = max_conn

    def set(self, db_host=None, db_port=None, db_database=None, db_user=None, db_password=None, **kwargs):
        self.host = db_host if db_host is not None else os.getenv('MB_DB_HOST', DEFAULT_HOST)
        self.port = db_port if db_port is not None else os.getenv('MB_DB_PORT', DEFAULT_PORT)
        self.database = db_database if db_database is not None else os.getenv('MB_DATABASE', DEFAULT_DATABASE)
Exemple #35
0
 def service_id(required=False):
     return click.option('-s',
                         '--service-id',
                         required=required,
                         help=helptexts.SERVICE_ID)
Exemple #36
0
        else:
            out_red("deleting account directory: {}".format(account.dir))
            account.remove()
    if not os.path.exists(account.dir):
        os.mkdir(account.dir)
    account.init()
    click.echo("account directory initialized: {}".format(account.dir))
    if not no_identity:
        account.add_identity("default")
    _status(account)


option_use_key = click.option(
    "--use-key",
    default=None,
    type=str,
    metavar="KEYHANDLE",
    help=  # NOQA
    "use specified secret key which must be findable "
    "through the specified keyhandle (e.g. email, keyid, fingerprint)")

option_use_system_keyring = click.option(
    "--use-system-keyring",
    default=False,
    is_flag=True,
    help=  # NOQA
    "use system keyring for all secret/public keys instead of storing "
    "keyring state inside our account identity directory.")

option_gpgbin = click.option(
    "--gpgbin",
    default="gpg",
Exemple #37
0
 def service_template_name(required=False):
     return click.option('-t',
                         '--service-template-name',
                         required=required,
                         help=helptexts.SERVICE_ID)
Exemple #38
0
                                  option_parameters)
from nucypher.cli.painting.deployment import (
    paint_contract_deployment, paint_deployer_contract_inspection,
    paint_deployment_delay, paint_staged_deployment)
from nucypher.cli.painting.help import echo_solidity_version
from nucypher.cli.painting.multisig import paint_multisig_proposed_transaction
from nucypher.cli.painting.transactions import paint_receipt_summary
from nucypher.cli.types import EIP55_CHECKSUM_ADDRESS, EXISTING_READABLE_FILE, WEI
from nucypher.cli.utils import (deployer_pre_launch_warnings,
                                ensure_config_root,
                                establish_deployer_registry,
                                initialize_deployer_interface)
from nucypher.types import NuNits

option_deployer_address = click.option('--deployer-address',
                                       help="Deployer's checksum address",
                                       type=EIP55_CHECKSUM_ADDRESS)
option_registry_infile = click.option(
    '--registry-infile',
    help="Input path for contract registry file",
    type=EXISTING_READABLE_FILE)
option_registry_outfile = click.option(
    '--registry-outfile',
    help="Output path for contract registry file",
    type=click.Path(file_okay=True))
option_target_address = click.option('--target-address',
                                     help="Address of the target contract",
                                     type=EIP55_CHECKSUM_ADDRESS)
option_gas = click.option(
    '--gas',
    help="Operate with a specified gas per-transaction limit",
def to_string(function):
    function = click.option('--to-string',
                            help='stringify output',
                            default=False,
                            type=bool)(function)
    return function
class NaturalOrderGroup(click.Group):
    """Click group that lists commmands in the order added"""

    def list_commands(self, ctx):
        return self.commands.keys()


@click.group(cls=NaturalOrderGroup)
def main():
    """Release helper scripts"""
    pass


# Extracted common options
version_cmd_options = [
    click.option("--version-cmd", envvar="VERSION_CMD", help="The version command")
]

branch_options = [
    click.option("--branch", envvar="BRANCH", help="The target branch"),
    click.option(
        "--remote", envvar="REMOTE", default="upstream", help="The git remote name"
    ),
    click.option("--repo", envvar="REPOSITORY", help="The git repo"),
]

auth_options = [
    click.option("--auth", envvar="GITHUB_ACCESS_TOKEN", help="The GitHub auth token"),
]

changelog_path_options = [
Exemple #41
0
def config_option(config_function):
    """Helper decorator that turns an option function into a cli option"""
    return lambda function: \
        click.option('--' + config_function.__name__,
                     help=f'{config_function.__doc__}. Default: "{config_function()}"')(function)
Exemple #42
0
installed_targets = [target for target in interface.plugin_store.registry]
if len(installed_targets) > 0:
    supported_targets_msg = "Support is currently installed for deployment to: " \
                        "{targets}".format(targets=", ".join(installed_targets))
else:
    supported_targets_msg = "NOTE: you currently do not have support for installed for any " \
                            "deployment targets."

target_details = click.option("--target",
                              "-t",
                              required=True,
                              help="""
                                   Deployment target URI. Run
                                   `mlflow deployments help --target-name <target-name>` for
                                   more details on the supported URI format and config options
                                   for a given target.
                                   {supported_targets_msg}

                                   See all supported deployment targets and installation
                                   instructions at
                                   https://mlflow.org/docs/latest/plugins.html#community-plugins
                                   """.format(
                                  supported_targets_msg=supported_targets_msg))
deployment_name = click.option("--name",
                               "name",
                               required=True,
                               help="Name of the deployment")
parse_custom_arguments = click.option(
    "--config",
    "-C",
    metavar="NAME=VALUE",
Exemple #43
0
import functools
import json

import click
from click_didyoumean import DYMMixin
from click_help_colors import HelpColorsGroup

api_key_option = click.option(
    "--apiKey",
    "api_key",
    help="API key to use this time only",
)


def del_if_value_is_none(dict_):
    """Remove all elements with value == None"""
    for key, val in list(dict_.items()):
        if val is None:
            del dict_[key]


def jsonify_dicts(dict_):
    json_fields = ["envVars", "nodeAttrs"]
    for field in json_fields:
        if field in dict_:
            dict_[field] = json.dumps(dict_[field])


class ClickGroup(DYMMixin, HelpColorsGroup):
    pass
Exemple #44
0
def option_performance(f):
    """Defines options for all aspects of performance tuning"""

    _preset = {
        # Fixed
        'O1': {
            'opt': 'noop'
        },
        'O2': {
            'opt': 'advanced'
        },
    }

    def from_preset(ctx, param, value):
        """Set all performance options according to bench-mode preset"""
        ctx.params.update(_preset[value])
        return value

    def from_value(ctx, param, value):
        """Prefer preset values and warn for competing values."""
        return ctx.params[param.name] or value

    def config_blockshape(ctx, param, value):
        if value:
            # Block innermost loops if a full block shape is provided
            # Note: see https://github.com/devitocodes/devito/issues/320 for why
            # we use blockinner=True only if the backend compiler is Intel
            flag = isinstance(configuration['compiler'], IntelCompiler)
            configuration['opt-options']['blockinner'] = flag
            # Normalize value:
            # 1. integers, not strings
            # 2. sanity check the (hierarchical) blocking shape
            normalized_value = []
            for i, block_shape in enumerate(value):
                # If hierarchical blocking is activated, say with N levels, here in
                # `bs` we expect to see 3*N entries
                bs = [int(x) for x in block_shape.split()]
                levels = [bs[x:x + 3] for x in range(0, len(bs), 3)]
                if any(len(level) != 3 for level in levels):
                    raise ValueError(
                        "Expected 3 entries per block shape level, but got "
                        "one level with less than 3 entries (`%s`)" % levels)
                normalized_value.append(levels)
            if not all_equal(len(i) for i in normalized_value):
                raise ValueError(
                    "Found different block shapes with incompatible "
                    "number of levels (`%s`)" % normalized_value)
            configuration['opt-options']['blocklevels'] = len(
                normalized_value[0])
        else:
            normalized_value = []
        return tuple(normalized_value)

    def config_autotuning(ctx, param, value):
        """Setup auto-tuning to run in ``{basic,aggressive,...}+preemptive`` mode."""
        if value != 'off':
            # Sneak-peek at the `block-shape` -- if provided, keep auto-tuning off
            if ctx.params['block_shape']:
                warning(
                    "Skipping autotuning (using explicit block-shape `%s`)" %
                    str(ctx.params['block_shape']))
                level = False
            else:
                # Make sure to always run in preemptive mode
                configuration['autotuning'] = [value, 'preemptive']
                # We apply blocking to all parallel loops, including the innermost ones
                # Note: see https://github.com/devitocodes/devito/issues/320 for why
                # we use blockinner=True only if the backend compiler is Intel
                flag = isinstance(configuration['compiler'], IntelCompiler)
                configuration['opt-options']['blockinner'] = flag
                level = value
        else:
            level = False
        return level

    options = [
        click.option('-bm',
                     '--bench-mode',
                     is_eager=True,
                     callback=from_preset,
                     expose_value=False,
                     default='O2',
                     type=click.Choice(['O1', 'O2']),
                     help='Choose what to benchmark; ignored if execmode=run'),
        click.option('--arch',
                     default='unknown',
                     help='Architecture on which the simulation is/was run'),
        click.option('--opt',
                     callback=from_value,
                     type=click.Choice([
                         str(i) if type(i) is tuple else i
                         for i in configuration._accepted['opt']
                     ]),
                     help='Performance optimization level'),
        click.option('-bs',
                     '--block-shape',
                     callback=config_blockshape,
                     multiple=True,
                     is_eager=True,
                     help='Loop-blocking shape, bypass autotuning'),
        click.option('-a',
                     '--autotune',
                     default='aggressive',
                     callback=config_autotuning,
                     type=click.Choice([
                         str(tuple(i)) if type(i) is list else i
                         for i in configuration._accepted['autotuning']
                     ]),
                     help='Select autotuning mode')
    ]
    for option in reversed(options):
        f = option(f)
    return f
Exemple #45
0
 def mark_pattern():
     return click.option('-m',
                         '--mark-pattern',
                         help=helptexts.MARK_PATTERN,
                         type=str,
                         required=False)
Exemple #46
0
 def service_template_id(required=False):
     return click.option('-t',
                         '--service-template-id',
                         required=required,
                         help=helptexts.SERVICE_TEMPLATE_ID)
Exemple #47
0
import logging
import os
import contextlib

import click
from itertools import groupby

import ckan.migration as migration_repo
import ckan.plugins as p
import ckan.model as model
from ckan.common import config
from . import error_shout

log = logging.getLogger(__name__)

applies_to_plugin = click.option(u"-p", u"--plugin", help=u"Affected plugin.")


@click.group(short_help=u"Database management commands.")
def db():
    """Database management commands.
    """
    pass


@db.command()
def init():
    """Initialize the database.
    """
    log.info(u"Initialize the Database")
    try:
Exemple #48
0
for cmd_name in cmd_list:
    cmd_class = getattr(frontend, re.sub(r'_js$', '', cmd_name))

    cmd = click.command(cmd_name)(wrap_distutils_command(cmd_class))
    for opt, short_opt, description in cmd_class.user_options:
        long_opt_name = opt.rstrip('=')
        var_name = long_opt_name.replace('-', '_')
        opts = ['--' + long_opt_name]

        if short_opt:
            opts.append('-' + short_opt)

        default = DEFAULT_OPTIONS.get(cmd_name, {}).get(var_name)
        is_flag = not opt.endswith('=')
        cmd = click.option(*(opts + [var_name]), is_flag=is_flag, default=default, help=description)(cmd)

    cli.add_command(cmd)


@cli.command()
def check_format_strings():
    """Check whether format strings match.

    This helps finding cases where e.g. the original string uses
    ``{error}`` but the translation uses ``{erro}``, resulting
    in errors when using the translated string.
    """
    root_path = os.path.join(current_app.root_path, 'translations')
    paths = set()
    for root, dirs, files in os.walk(root_path):
Exemple #49
0
 def service_template_path(required=False):
     return click.option('-p',
                         '--service-template-path',
                         required=required,
                         type=click.Path(exists=True))
Exemple #50
0
            def get_command(self, ctx, name):
                """Retrieve the appropriate method from the Resource,
                decorate it as a click command, and return that method.
                """
                # Sanity check: Does a method exist corresponding to this
                # command? If not, None is returned for click to raise
                # exception.
                if not hasattr(self.resource, name):
                    return None

                # Get the method.
                method = getattr(self.resource, name)

                # Get any attributes that were given at command-declaration
                # time.
                attrs = getattr(method, '_cli_command_attrs', {})

                # If the help message comes from the docstring, then
                # convert it into a message specifically for this resource.
                help_text = inspect.getdoc(method)
                attrs['help'] = self._auto_help_text(help_text or '')

                # On some methods, we ignore the defaults, which are intended
                # for writing and not reading; process this.
                ignore_defaults = attrs.pop('ignore_defaults', False)

                # Wrap the method, such that it outputs its final return
                # value rather than returning it.
                new_method = self._echo_method(method)

                # Soft copy the "__click_params__", if any exist.
                # This is the internal holding method that the click library
                # uses to store @click.option and @click.argument directives
                # before the method is converted into a command.
                #
                # Because self._echo_method uses @functools.wraps, this is
                # actually preserved; the purpose of copying it over is
                # so we can get our resource fields at the top of the help;
                # the easiest way to do this is to load them in before the
                # conversion takes place. (This is a happy result of Armin's
                # work to get around Python's processing decorators
                # bottom-to-top.)
                click_params = getattr(method, '__click_params__', [])
                new_method.__click_params__ = copy(click_params)

                # Write options based on the fields available on this resource.
                fao = attrs.pop('use_fields_as_options', True)
                if fao:
                    for field in reversed(self.resource.fields):
                        if not field.is_option:
                            continue

                        # If we got an iterable rather than a boolean,
                        # then it is a list of fields to use; check for
                        # presence in that list.
                        if not isinstance(fao, bool) and field.name not in fao:
                            continue

                        # Create the initial arguments based on the
                        # option value. If we have a different key to use
                        # (which is what gets routed to the Tower API),
                        # ensure that is the first argument.
                        args = [field.option]
                        if field.key:
                            args.insert(0, field.key)

                        # short name aliases for common flags
                        short_fields = {
                            'name': 'n',
                            'description': 'd',
                            'inventory': 'i',
                            'extra_vars': 'e'
                        }
                        if field.name in short_fields:
                            args.append('-' + short_fields[field.name])

                        # Apply the option to the method.
                        option_help = field.help
                        if field.required:
                            option_help = '[REQUIRED] ' + option_help
                        click.option(*args,
                                     default=field.default
                                     if not ignore_defaults else None,
                                     help=option_help,
                                     type=field.type,
                                     show_default=field.show_default,
                                     multiple=field.multiple)(new_method)

                # Make a click Command instance using this method
                # as the callback, and return it.
                cmd = command(name=name, cls=Command, **attrs)(new_method)

                # If this method has a `pk` positional argument,
                # then add a click argument for it.
                code = six.get_function_code(method)
                if 'pk' in code.co_varnames:
                    click.argument('pk',
                                   nargs=1,
                                   required=False,
                                   type=int,
                                   metavar='[ID]')(cmd)

                # Done; return the command.
                return cmd
Exemple #51
0
 def execution_id(required=False):
     return click.option('-e',
                         '--execution-id',
                         required=required,
                         help=helptexts.EXECUTION_ID)
Exemple #52
0
def verbose_option():
    return click.option('-v', '--verbose', count=True)
Exemple #53
0
from rq.serializers import DefaultSerializer
from rq.suspension import (suspend as connection_suspend, resume as
                           connection_resume, is_suspended)
from rq.worker_registration import clean_worker_registry
from rq.job import JobStatus

blue = make_colorizer('darkblue')

# Disable the warning that Click displays (as of Click version 5.0) when users
# use unicode_literals in Python 2.
# See http://click.pocoo.org/dev/python3/#unicode-literals for more details.
click.disable_unicode_literals_warning = True

shared_options = [
    click.option('--url',
                 '-u',
                 envvar='RQ_REDIS_URL',
                 help='URL describing Redis connection details.'),
    click.option('--config',
                 '-c',
                 envvar='RQ_CONFIG',
                 help='Module containing RQ settings.'),
    click.option('--worker-class',
                 '-w',
                 envvar='RQ_WORKER_CLASS',
                 default=DEFAULT_WORKER_CLASS,
                 help='RQ Worker class to use'),
    click.option('--job-class',
                 '-j',
                 envvar='RQ_JOB_CLASS',
                 default=DEFAULT_JOB_CLASS,
                 help='RQ Job class to use'),
Exemple #54
0
            before=sys.path,
            after=[''],
        ))


def print_environment_variables(env, *variables):
    for name in variables:
        value = env.get(name)
        if value is None:
            print('{} is not set'.format(name))
        else:
            print('{}: {}'.format(name, value))


qt_debug_plugins_option = click.option(
    '--qt-debug-plugins/--no-qt-debug-plugins',
    help='Set QT_DEBUG_PLUGINS=1',
)


@click.command(
    context_settings={
        'ignore_unknown_options': True,
        'allow_extra_args': True,
    }, )
@click.pass_context
@click.option(
    '--widget-path',
    '-p',
    'widget_paths',
    help='Paths to be combined with PYQTDESIGNERPATH',
    type=click.Path(exists=True, file_okay=False, resolve_path=True),
Exemple #55
0
 def task_retry_interval(default=defaults.TASK_RETRY_INTERVAL):
     return click.option('--task-retry-interval',
                         type=int,
                         default=default,
                         help=helptexts.TASK_RETRY_INTERVAL.format(default))
Exemple #56
0
def pruneflag(cli):
    return click.option(
        "--prune/--no-prune",
        default=True,
        help="Controls if old " 'artifacts should be pruned.  "prune" is the default.',
    )(cli)
Exemple #57
0
import click
from py42.clients.trustedactivities import TrustedActivityType

from code42cli.bulk import generate_template_cmd_factory
from code42cli.bulk import run_bulk_process
from code42cli.click_ext.groups import OrderedGroup
from code42cli.errors import Code42CLIError
from code42cli.file_readers import read_csv_arg
from code42cli.options import format_option
from code42cli.options import sdk_options
from code42cli.output_formats import OutputFormatter

resource_id_arg = click.argument("resource-id", type=int)
type_option = click.option(
    "--type",
    help=
    f"Type of trusted activity. Valid types include {', '.join(TrustedActivityType.choices())}.",
    type=click.Choice(TrustedActivityType.choices()),
)
value_option = click.option(
    "--value",
    help=
    "The value of the trusted activity, such as the domain or Slack workspace name.",
)
description_option = click.option(
    "--description", help="The description of the trusted activity.")


def _get_trust_header():
    return {
        "resourceId": "Resource Id",
        "type": "Type",
from code42cli.file_readers import read_csv_arg
from code42cli.file_readers import read_flat_file_arg
from code42cli.options import format_option
from code42cli.options import sdk_options


def _get_filter_choices():
    filters = DepartingEmployeeFilters.choices()
    return get_choices(filters)


DATE_FORMAT = "%Y-%m-%d"
filter_option = click.option(
    "--filter",
    help="Departing employee filter options. Defaults to {}.".format(
        ALL_FILTER),
    type=click.Choice(_get_filter_choices()),
    default=ALL_FILTER,
    callback=lambda ctx, param, arg: handle_filter_choice(arg),
)


@click.group(cls=OrderedGroup)
@sdk_options(hidden=True)
def departing_employee(state):
    """Add and remove employees from the Departing Employees detection list."""
    pass


@departing_employee.command("list")
@sdk_options()
@format_option
Exemple #59
0
        )

    @cached_property
    def formatter(self):
        return self.formatter_class(
            self.config['main']['date_format'],
            self.config['main']['time_format'],
            self.config['main']['dt_separator']
        )


pass_ctx = click.make_pass_decorator(AppContext)


_interactive_option = click.option(
    '--interactive', '-i', is_flag=True, default=None,
    help='Go into interactive mode before saving the task.')


@click.group(invoke_without_command=True)
@click_log.init('todoman')
@click_log.simple_verbosity_option()
@click.option('--colour', '--color', default=None,
              type=click.Choice(['always', 'auto', 'never']),
              help=('By default todoman will disable colored output if stdout '
                    'is not a TTY (value `auto`). Set to `never` to disable '
                    'colored output entirely, or `always` to enable it '
                    'regardless.'))
@click.option('--porcelain', is_flag=True, help='Use a JSON format that will '
              'remain stable regardless of configuration or version.')
@click.option('--humanize', '-h', default=None, is_flag=True,
Exemple #60
0
        __AIRFLOW_SOURCES_ROOT = airflow_sources_root
    else:
        console.print(
            f"\n[yellow]Could not find Airflow sources location. Assuming {__AIRFLOW_SOURCES_ROOT}"
        )
    os.chdir(__AIRFLOW_SOURCES_ROOT)


@click.group()
def main():
    find_airflow_sources_root()


option_verbose = click.option(
    "--verbose",
    is_flag=True,
    help="Print verbose information about performed steps",
)


@main.command()
def version():
    """Prints version of breeze.py."""
    console.print(ASCIIART, style=ASCIIART_STYLE)
    console.print(f"\n[green]{NAME} version: {VERSION}[/]\n")


@option_verbose
@main.command()
def shell(verbose: bool):
    """Enters breeze.py environment. this is the default command use when no other is selected."""