Python click.UsageError() Examples

The following are 30 code examples of click.UsageError(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module click , or try the search function .
Example #1
Source File: run_benchmarks.py    From veros with MIT License 6 votes vote down vote up
def check_arguments(fortran_library, components, float_type, burnin, timesteps, **kwargs):
    fortran_version = check_fortran_library(fortran_library)

    if 'fortran' in components or 'fortran-mpi' in components:
        if not fortran_library:
            raise click.UsageError('Path to fortran library must be given when running fortran components')
        if not fortran_version:
            raise click.UsageError('Fortran library failed to import')

    if fortran_version != 'parallel' and 'fortran-mpi' in components:
        raise click.UsageError('Fortran library must be compiled with MPI support for fortran-mpi component')

    if float_type != 'float64' and ('fortran' in components or 'fortran-mpi' in components):
        raise click.UsageError('Can run Fortran components only with "float64" float type')

    if not burnin < timesteps:
        raise click.UsageError('burnin must be smaller than number of timesteps') 
Example #2
Source File: cli.py    From chinese-support-redux with GNU General Public License v3.0 6 votes vote down vote up
def validate_lang(ctx, param, lang):
    """Validation callback for the <lang> option.
    Ensures <lang> is a supported language unless the <nocheck> flag is set
    """
    if ctx.params['nocheck']:
        return lang

    try:
        if lang not in tts_langs():
            raise click.UsageError(
                "'%s' not in list of supported languages.\n"
                "Use --all to list languages or "
                "add --nocheck to disable language check." % lang)
        else:
            # The language is valid.
            # No need to let gTTS re-validate.
            ctx.params['nocheck'] = True
    except RuntimeError as e:
        # Only case where the <nocheck> flag can be False
        # Non-fatal. gTTS will try to re-validate.
        log.debug(str(e), exc_info=True)

    return lang 
Example #3
Source File: cci.py    From CumulusCI with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def org_scratch(runtime, config_name, org_name, default, devhub, days, no_password):
    runtime.check_org_overwrite(org_name)

    scratch_configs = getattr(runtime.project_config, "orgs__scratch")
    if not scratch_configs:
        raise click.UsageError("No scratch org configs found in cumulusci.yml")
    scratch_config = scratch_configs.get(config_name)
    if not scratch_config:
        raise click.UsageError(
            f"No scratch org config named {config_name} found in the cumulusci.yml file"
        )

    if devhub:
        scratch_config["devhub"] = devhub

    runtime.keychain.create_scratch_org(
        org_name, config_name, days, set_password=not (no_password)
    )

    if default:
        runtime.keychain.set_default_org(org_name)
        click.echo(f"{org_name} is now the default org")
    else:
        click.echo(f"{org_name} is configured for use") 
Example #4
Source File: test_cci.py    From CumulusCI with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_task_run_invalid_option(self):
        runtime = mock.Mock()
        runtime.get_org.return_value = (None, None)
        runtime.project_config.get_task.return_value = TaskConfig(
            {"class_path": "cumulusci.cli.tests.test_cci.DummyTask"}
        )

        with self.assertRaises(click.UsageError):
            run_click_command(
                cci.task_run,
                runtime=runtime,
                task_name="test",
                org=None,
                o=[("bogus", "blue")],
                debug=False,
                debug_before=False,
                debug_after=False,
                no_prompt=True,
            ) 
Example #5
Source File: test_cci.py    From CumulusCI with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_flow_run_delete_non_scratch(self,):
        org_config = mock.Mock(scratch=False)
        runtime = mock.Mock()
        runtime.get_org.return_value = ("test", org_config)

        with self.assertRaises(click.UsageError):
            run_click_command(
                cci.flow_run,
                runtime=runtime,
                flow_name="test",
                org="test",
                delete_org=True,
                debug=False,
                o=None,
                skip=(),
                no_prompt=True,
            ) 
Example #6
Source File: cli.py    From flask-security with MIT License 6 votes vote down vote up
def roles_add_permissions(role, permissions):
    """Add permissions to role.

    Role is an existing role name.
    Permissions are a comma separated list.
    """
    role = _datastore._prepare_role_modify_args(role)
    if role is None:
        raise click.UsageError("Cannot find role.")
    if _datastore.add_permissions_to_role(role, permissions):
        click.secho(
            f'Permission(s) "{permissions}" added to role "{role.name}" successfully.',
            fg="green",
        )
    else:  # pragma: no cover
        raise click.UsageError("Cannot add permission(s) to role.") 
Example #7
Source File: cci.py    From CumulusCI with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def shell(runtime, script=None, python=None):
    # alias for backwards-compatibility
    variables = {
        "config": runtime,
        "runtime": runtime,
        "project_config": runtime.project_config,
    }

    if script:
        if python:
            raise click.UsageError("Cannot specify both --script and --python")
        runpy.run_path(script, init_globals=variables)
    elif python:
        exec(python, variables)
    else:
        code.interact(local=variables) 
Example #8
Source File: __init__.py    From go2mapillary with GNU General Public License v3.0 6 votes vote down vote up
def parent(ctx, input, depth):
    """Takes a [x, y, z] tile as input and writes its parent to stdout
    in the same form.

    $ echo "[486, 332, 10]" | mercantile parent

    Output:

    [243, 166, 9]
    """
    src = normalize_input(input)
    for line in iter_lines(src):
        tile = json.loads(line)[:3]
        if tile[2] - depth < 0:
            raise click.UsageError("Invalid parent level: {0}".format(tile[2] - depth))
        for i in range(depth):
            tile = mercantile.parent(tile)
        output = json.dumps(tile)
        click.echo(output) 
Example #9
Source File: bootstrap.py    From hobbit-core with MIT License 6 votes vote down vote up
def csv2model(cls, csv_path):
        with open(csv_path) as csvfile:
            spamreader = csv.reader(csvfile)

            Model = None
            for row in spamreader:
                if spamreader.line_num == 1:
                    continue
                if len(row) == 1 or row[0] == ''.join(row):
                    if Model is not None:
                        yield Model
                    Model = cls.gen_model(row[0])
                elif len(row) == 8:
                    row = cls.row_processing(row)
                    if row.type != cls.TYPE_REF:
                        Model.columns.append(row)
                    else:
                        Model.refs.append(row)
                else:
                    raise click.UsageError(
                        click.style(f'csv file err: `{row}`.', fg='red'))
            yield Model 
Example #10
Source File: __main__.py    From profiling with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def profiler_arguments(f):
    @click.argument('argv', nargs=-1)
    @click.option('-m', 'module', type=Module(),
                  help='Run library module as a script.')
    @click.option('-c', 'command', type=Command(),
                  help='Program passed in as string.')
    @wraps(f)
    def wrapped(argv, module, command, **kwargs):
        if module is not None and command is not None:
            raise click.UsageError('Option -m and -c are exclusive')
        script = module or command
        if script is None:
            # -m and -c not passed.
            try:
                script_filename, argv = argv[0], argv[1:]
            except IndexError:
                raise click.UsageError('Script not specified')
            script = Script().convert(script_filename, None, None)
        kwargs.update(script=script, argv=argv)
        return f(**kwargs)
    return wrapped 
Example #11
Source File: cli.py    From linehaul with Apache License 2.0 6 votes vote down vote up
def _configure_bigquery(credentials_file, credentials_blob, api_max_connections=None):
    if credentials_file is None and credentials_blob is None:
        raise click.UsageError(
            "Must pass either --credentials-file or --credentials-blob"
        )
    elif credentials_file is not None and credentials_blob is not None:
        raise click.UsageError(
            "Cannot pass both --credentials-file and --credentials-blob"
        )
    elif credentials_file is not None:
        logger.debug("Configuring BigQuery from %r", credentials_file.name)
        credentials = json.load(credentials_file)
    else:
        logger.debug("Configuring BigQuery from base64 blob")
        credentials = json.loads(credentials_blob)

    return BigQuery(
        credentials["client_email"],
        credentials["private_key"],
        max_connections=api_max_connections,
    ) 
Example #12
Source File: cli.py    From Watson with MIT License 6 votes vote down vote up
def convert(self, value, param, ctx):
        if value:
            date = self._parse_multiformat(value)
            if date is None:
                raise click.UsageError(
                    "Could not match value '{}' to any supported date format"
                    .format(value)
                )
            # When we parse a date, we want to parse it in the timezone
            # expected by the user, so that midnight is midnight in the local
            # timezone, not in UTC. Cf issue #16.
            date.tzinfo = tz.tzlocal()
            # Add an offset to match the week beginning specified in the
            # configuration
            if param.name == "week":
                week_start = ctx.obj.config.get(
                    "options", "week_start", "monday")
                date = apply_weekday_offset(
                    start_time=date, week_start=week_start)
            return date 
Example #13
Source File: cli.py    From datasette with Apache License 2.0 6 votes vote down vote up
def check_databases(ds):
    # Run check_connection against every connected database
    # to confirm they are all usable
    for database in list(ds.databases.values()):
        try:
            await database.execute_fn(check_connection)
        except SpatialiteConnectionProblem:
            raise click.UsageError(
                "It looks like you're trying to load a SpatiaLite"
                " database without first loading the SpatiaLite module."
                "\n\nRead more: https://datasette.readthedocs.io/en/latest/spatialite.html"
            )
        except ConnectionProblem as e:
            raise click.UsageError(
                "Connection to {} failed check: {}".format(
                    database.path, str(e.args[0])
                )
            ) 
Example #14
Source File: cfy.py    From cloudify-cli with Apache License 2.0 6 votes vote down vote up
def resolve_command(self, ctx, args):
        """Override clicks ``resolve_command`` method
        and appends *Did you mean ...* suggestions
        to the raised exception message.
        """
        try:
            return super(AliasedGroup, self).resolve_command(ctx, args)
        except click.exceptions.UsageError as error:
            error_msg = str(error)
            original_cmd_name = click.utils.make_str(args[0])
            matches = difflib.get_close_matches(
                original_cmd_name,
                self.list_commands(ctx),
                self.max_suggestions,
                self.cutoff)
            if matches:
                error_msg += '\n\nDid you mean one of these?\n    {0}'.format(
                    '\n    '.join(matches))
            raise click.exceptions.UsageError(error_msg, error.ctx) 
Example #15
Source File: cli.py    From dagster with Apache License 2.0 6 votes vote down vote up
def execute_query_against_remote(host, query, variables):
    parsed_url = urlparse(host)
    if not (parsed_url.scheme and parsed_url.netloc):
        raise click.UsageError(
            'Host {host} is not a valid URL. Host URL should include scheme ie http://localhost'.format(
                host=host
            )
        )

    sanity_check = requests.get(urljoin(host, '/dagit_info'))
    sanity_check.raise_for_status()
    if 'dagit' not in sanity_check.text:
        raise click.UsageError(
            'Host {host} failed sanity check. It is not a dagit server.'.format(host=host)
        )

    response = requests.post(
        urljoin(host, '/graphql'), params={'query': query, 'variables': variables}
    )
    response.raise_for_status()
    str_res = response.json()
    return str_res 
Example #16
Source File: cli.py    From dagster with Apache License 2.0 6 votes vote down vote up
def ui(text, file, predefined, variables, remote, output, **kwargs):
    query = None
    if text is not None and file is None and predefined is None:
        query = text.strip('\'" \n\t')
    elif file is not None and text is None and predefined is None:
        query = file.read()
    elif predefined is not None and text is None and file is None:
        query = PREDEFINED_QUERIES[predefined]
    else:
        raise click.UsageError(
            'Must select one and only one of text (-t), file (-f), or predefined (-p) '
            'to select GraphQL document to execute.'
        )

    if remote:
        res = execute_query_against_remote(remote, query, variables)
        print(res)
    else:
        workspace = get_workspace_from_kwargs(kwargs)
        execute_query_from_cli(workspace, query, variables, output) 
Example #17
Source File: cci.py    From CumulusCI with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def org_connect(runtime, org_name, sandbox, login_url, default, global_org):
    runtime.check_org_overwrite(org_name)

    if "lightning.force.com" in login_url:
        raise click.UsageError(
            "Connecting an org with a lightning.force.com URL does not work. "
            "Use the my.salesforce.com version instead"
        )

    connected_app = runtime.keychain.get_service("connected_app")
    if sandbox:
        login_url = "https://test.salesforce.com"

    oauth_capture = CaptureSalesforceOAuth(
        client_id=connected_app.client_id,
        client_secret=connected_app.client_secret,
        callback_url=connected_app.callback_url,
        auth_site=login_url,
        scope="web full refresh_token",
    )
    oauth_dict = oauth_capture()
    org_config = OrgConfig(oauth_dict, org_name)
    org_config.load_userinfo()
    org_config._load_orginfo()
    if org_config.organization_sobject["TrialExpirationDate"] is None:
        org_config.config["expires"] = "Persistent"
    else:
        org_config.config["expires"] = parse_api_datetime(
            org_config.organization_sobject["TrialExpirationDate"]
        ).date()

    global_org = global_org or runtime.project_config is None
    runtime.keychain.set_org(org_config, global_org)

    if default:
        runtime.keychain.set_default_org(org_name)
        click.echo(f"{org_name} is now the default org") 
Example #18
Source File: runtime.py    From CumulusCI with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def check_cumulusci_version(self):
        if self.project_config:
            min_cci_version = self.project_config.minimum_cumulusci_version
            if min_cci_version:
                parsed_version = pkg_resources.parse_version(min_cci_version)
                if get_installed_version() < parsed_version:
                    raise click.UsageError(
                        f"This project requires CumulusCI version {min_cci_version} or later. "
                        f"To upgrade, please run this command: {get_cci_upgrade_command()}"
                    )


# for backwards-compatibility 
Example #19
Source File: create_example.py    From dagster with Apache License 2.0 5 votes vote down vote up
def add_to_examples_json(name):
    with open(EXAMPLES_JSON_PATH, 'r') as examples_file:
        examples = json.load(examples_file)

    if name in {example['name'] for example in examples}:
        raise click.UsageError(
            'Example with name {name} already exists in {path}'.format(
                name=name, path=EXAMPLES_JSON_PATH
            )
        )

    examples.append({'name': name, 'title': '', 'description': ''})

    with open(EXAMPLES_JSON_PATH, 'w') as examples_file:
        json.dump(examples, examples_file, indent=4) 
Example #20
Source File: memory_analyzer.py    From memory-analyzer with MIT License 5 votes vote down vote up
def validate_pids(ctx, param, pids):
    for pid in pids:
        pid = int(pid)
        try:
            os.kill(pid, 0)
        except OSError as e:
            if e.errno == errno.EPERM and not is_root():
                msg = "Permission error, try running as root"
                raise click.UsageError(msg)

            msg = f"The given PID {pid} is not valid."
            raise click.BadParameter(msg)

    return pids 
Example #21
Source File: kraken.py    From kraken with Apache License 2.0 5 votes vote down vote up
def binarizer(threshold, zoom, escale, border, perc, range, low, high, input, output) -> None:
    from kraken import binarization

    ctx = click.get_current_context()
    if ctx.meta['first_process']:
        if ctx.meta['input_format_type'] != 'image':
            input = get_input_parser(ctx.meta['input_format_type'])(input)['image']
        ctx.meta['first_process'] = False
    else:
        raise click.UsageError('Binarization has to be the initial process.')

    try:
        im = Image.open(input)
    except IOError as e:
        raise click.BadParameter(str(e))
    message('Binarizing\t', nl=False)
    try:
        res = binarization.nlbin(im, threshold, zoom, escale, border, perc, range,
                                 low, high)
        form = None
        ext = os.path.splitext(output)[1]
        if ext in ['.jpg', '.jpeg', '.JPG', '.JPEG', '']:
            form = 'png'
            if ext:
                logger.warning('jpeg does not support 1bpp images. Forcing to png.')
        res.save(output, format=form)
        ctx.meta['base_image'] = output
    except Exception:
        message('\u2717', fg='red')
        raise
    message('\u2713', fg='green') 
Example #22
Source File: test_main_lib.py    From memory-analyzer with MIT License 5 votes vote down vote up
def test_validate_pids_with_an_invalid_pid_and_no_root(
        self, mock_kill, mock_geteuid
    ):
        mock_geteuid.return_value = 42
        ctx = param = mock.MagicMock()
        mock_kill.side_effect = partial(fake_kill, errno=errno.EPERM)

        with self.assertRaises(click.UsageError):
            memory_analyzer.validate_pids(ctx, param, [42, 314]) 
Example #23
Source File: cci.py    From CumulusCI with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def flow_run(runtime, flow_name, org, delete_org, debug, o, skip, no_prompt):

    # Get necessary configs
    org, org_config = runtime.get_org(org)
    if delete_org and not org_config.scratch:
        raise click.UsageError("--delete-org can only be used with a scratch org")

    # Parse command line options
    options = defaultdict(dict)
    if o:
        for key, value in o:
            task_name, option_name = key.split("__")
            options[task_name][option_name] = value

    # Create the flow and handle initialization exceptions
    try:
        coordinator = runtime.get_flow(flow_name, options=options)
        coordinator.run(org_config)
    finally:
        runtime.alert(f"Flow Complete: {flow_name}")

    # Delete the scratch org if --delete-org was set
    if delete_org:
        try:
            org_config.delete_org()
        except Exception as e:
            click.echo(
                "Scratch org deletion failed.  Ignoring the error below to complete the flow:"
            )
            click.echo(str(e)) 
Example #24
Source File: cci.py    From CumulusCI with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def flow_info(runtime, flow_name):
    try:
        coordinator = runtime.get_flow(flow_name)
        output = coordinator.get_summary()
        click.echo(output)
    except FlowNotFoundError as e:
        raise click.UsageError(str(e)) 
Example #25
Source File: test_cci.py    From CumulusCI with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_service_connect_invalid_service(self):
        multi_cmd = cci.ConnectServiceCommand()
        ctx = mock.Mock()
        runtime = mock.MagicMock()
        runtime.project_config.services = {}

        with mock.patch("cumulusci.cli.cci.RUNTIME", runtime):
            with self.assertRaises(click.UsageError):
                multi_cmd.get_command(ctx, "test") 
Example #26
Source File: cci.py    From CumulusCI with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def org_shell(runtime, org_name, script=None, python=None):
    org_name, org_config = runtime.get_org(org_name)
    org_config.refresh_oauth_token(runtime.keychain)

    sf = get_simple_salesforce_connection(runtime.project_config, org_config)

    sf_helpers = SimpleSalesforceUIHelpers(sf)

    globals = {
        "sf": sf,
        "org_config": org_config,
        "project_config": runtime.project_config,
        "help": CCIHelp(),
        "query": sf_helpers.query,
        "describe": sf_helpers.describe,
    }

    if script:
        if python:
            raise click.UsageError("Cannot specify both --script and --python")
        runpy.run_path(script, init_globals=globals)
    elif python:
        exec(python, globals)
    else:
        code.interact(
            banner=f"Use `sf` to access org `{org_name}` via simple_salesforce\n"
            + "Type `help` for more information about the cci shell.",
            local=globals,
        )

    # Save the org config in case it was modified
    runtime.keychain.set_org(org_config)


# Commands for group: task 
Example #27
Source File: script.py    From yolo with Apache License 2.0 5 votes vote down vote up
def run(yolo_file=None, **kwargs):
    """Run a script with AWS account credentials."""
    account = kwargs['account']
    stage = kwargs['stage']
    if (
        (account is None and stage is None) or
        (account is not None and stage is not None)
    ):
        raise click.UsageError(
            "One (and only one) of --account or --stage should be specified."
        )
    client.YoloClient(yolo_file=yolo_file).run(**kwargs) 
Example #28
Source File: cci.py    From CumulusCI with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_command(self, ctx, name):
        runtime = RUNTIME
        runtime._load_keychain()
        services = self._get_services_config(RUNTIME)
        try:
            service_config = services[name]
        except KeyError:
            raise click.UsageError(f"Sorry, I don't know about the '{name}' service.")
        attributes = service_config["attributes"].items()

        params = [self._build_param(attr, cnfg) for attr, cnfg in attributes]
        if runtime.project_config is not None:
            params.append(click.Option(("--project",), is_flag=True))

        def callback(*args, **kwargs):
            if runtime.project_config is None:
                project = False
            else:
                project = kwargs.pop("project", False)
            serv_conf = dict(
                (k, v) for k, v in list(kwargs.items()) if v is not None
            )  # remove None values

            # A service can define a callable to validate the service config
            validator_path = service_config.get("validator")
            if validator_path:
                validator = import_global(validator_path)
                validator(serv_conf)

            runtime.keychain.set_service(name, ServiceConfig(serv_conf), project)
            if project:
                click.echo(f"{name} is now configured for this project.")
            else:
                click.echo(f"{name} is now configured for all CumulusCI projects.")

        ret = click.Command(name, params=params, callback=callback)
        return ret 
Example #29
Source File: cci.py    From CumulusCI with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def validate_project_name(value):
    if not re.match(r"^[a-zA-Z0-9_-]+$", value):
        raise click.UsageError(
            "Invalid project name. Allowed characters: "
            "letters, numbers, dash, and underscore"
        )
    return value 
Example #30
Source File: cli.py    From whatportis with MIT License 5 votes vote down vote up
def run(port, like, use_json, server):
    """Search port names and numbers."""
    if not port and not server[0]:
        raise click.UsageError("Please specify a port")

    # Check if database exists
    if not database_exists():
        click.echo("Database not found, doing first import...")
        populate_db()

    if server[0]:
        try:
            from whatportis.server import app

            app.run(host=server[0], port=server[1])
        except ImportError:
            click.echo(
                "Dependencies are missing, please use `pip install whatportis[server]`."
            )
        return

    ports = get_ports(port, like)
    if not ports:
        click.echo("No ports found for '{0}'".format(port))
        return

    if use_json:
        print(json.dumps(ports, indent=4))
    else:
        table = as_table(ports)
        print(table)