def test_plot(plot, expected): try: import click except ImportError: click = None if click: ctx = click.Context(plot) ctx.invoke(plot) else: plot() assert os.path.exists(expected) os.remove(expected)
def _generate_nodes(self, name, command, parent, nested, commands=None): """Generate the relevant Sphinx nodes. Format a `click.Group` or `click.Command`. :param name: Name of command, as used on the command line :param command: Instance of `click.Group` or `click.Command` :param parent: Instance of `click.Context`, or None :param nested: The granularity of subcommand details. :param commands: Display only listed commands or skip the section if empty :returns: A list of nested docutil nodes """ ctx = click.Context( command, info_name=name, parent=parent, auto_envvar_prefix="DOCTR_VERSIONS_MENU", ) if CLICK_VERSION >= (7, 0) and command.hidden: return [] # Title section = nodes.section( '', nodes.title(name, '', nodes.literal(text=name)), ids=[nodes.make_id(ctx.command_path)], names=[nodes.fully_normalize_name(ctx.command_path)], ) # Summary source_name = ctx.command_path result = statemachine.ViewList() lines = _format_command(ctx, nested, commands) for line in lines: LOG.debug(line) result.append(line, source_name) sphinx_nodes.nested_parse_with_titles(self.state, result, section) # Subcommands if nested == NESTED_FULL: commands = _filter_commands(ctx, commands) for command in commands: section.extend( self._generate_nodes(command.name, command, ctx, nested)) return [section]
def test_args_to_config_arg_not_given() -> None: ctx = click.Context(click.Command('test'), obj=None) config_options = cli._get_configuration_options(MyConfig) cfg = cli._args_to_config(ctx, MyConfig, config_options, opt1=None, opt2='hello') assert cfg.opt2 == 'hello' with pytest.raises(click.BadParameter): assert cfg.opt1
def validate_taxdump(value, method): if (os.path.isfile("%s/%s" % (value, "names.dmp")) and os.path.isfile("%s/%s" % (value, "nodes.dmp")) and os.path.isfile("%s/%s" % (value, "merged.dmp")) and os.path.isfile("%s/%s" % (value, "delnodes.dmp"))): return value else: with click.Context(method) as ctx: click.echo(ctx.get_help()) raise click.BadParameter( "Could not find names.dmp in taxdump, specify a value or make sure the files are present" )
def main(): if len(sys.argv) == 1: with click.Context(spellbook) as ctx: click.echo(spellbook.get_help(ctx)) return 1 try: spellbook() except Exception as e: # LOG.debug(traceback.format_exc()) print(traceback.format_exc()) LOG.error(str(e)) return 1
def test_basic_parameters(self): """Validate a combination of parameters. This exercises the code paths for a command with arguments, options and environment variables. """ @click.command() @click.option('--param', envvar='PARAM', help='A sample option') @click.argument('ARG', envvar='ARG') def foobar(bar): """A sample command.""" pass ctx = click.Context(foobar, info_name='foobar') output = list(ext._format_command(ctx, show_nested=False)) self.assertEqual( textwrap.dedent(""" A sample command. .. program:: foobar .. code-block:: shell foobar [OPTIONS] ARG .. rubric:: Options .. option:: --param <param> A sample option .. rubric:: Arguments .. option:: ARG Required argument .. rubric:: Environment variables .. _foobar-param-PARAM: .. envvar:: PARAM :noindex: Provide a default for :option:`--param` .. _foobar-arg-ARG: .. envvar:: ARG :noindex: Provide a default for :option:`ARG` """).lstrip(), '\n'.join(output))
def test_hidden(self): """Ensure 'hidden' subcommands are not shown.""" @click.command() def hello(): """A sample command.""" @click.command() def world(): """A world command.""" @click.command(hidden=True) def hidden(): """A hidden command.""" class MyCLI(click.MultiCommand): _command_mapping = { 'hello': hello, 'world': world, 'hidden': hidden, } def list_commands(self, ctx): return ['hello', 'world', 'hidden'] def get_command(self, ctx, name): return self._command_mapping[name] cli = MyCLI(help='A sample custom multicommand.') ctx = click.Context(cli, info_name='cli') output = list(ext._format_command(ctx, nested='short')) # Note that we do NOT expect this to show the 'hidden' command self.assertEqual( textwrap.dedent(""" A sample custom multicommand. .. program:: cli .. code-block:: shell cli [OPTIONS] COMMAND [ARGS]... .. rubric:: Commands .. object:: hello A sample command. .. object:: world A world command. """).lstrip(), '\n'.join(output), )
def test_eodag_search_without_args(self): """Calling eodag search subcommand without arguments should print help message and return error code""" # noqa result = self.runner.invoke(eodag, ["search"]) with click.Context(search_crunch) as ctx: self.assertEqual( no_blanks(result.output), no_blanks("".join(( "Give me some work to do. See below for how to do that:", ctx.get_help(), ))), ) self.assertNotEqual(result.exit_code, 0)
def helptext(command=None): if command is None: ctx = click.Context(cli, info_name='cooler') text = indent(ctx.get_help(), 4) else: ctx = click.Context(cli.commands.get(command), info_name='cooler ' + command) text = indent(ctx.get_help(), 4) if command in SUBCOMMANDS: for subcommand in SUBCOMMANDS[command]: info_name = 'cooler {} {}'.format(command, subcommand) ctx = click.Context( cli.commands.get(command).commands.get(subcommand), info_name=info_name) subtext = '\n\n' + info_name + '\n' subtext += '~' * len(info_name) + '\n' subtext += ctx.get_help() + '\n' text += indent(subtext, 8) return text
def _get_ctx(): @click.group() def cli(): """A sample command group.""" pass @cli.command() def hello(): """A sample command.""" pass return click.Context(cli, info_name='cli')
def _generate_nodes(self, name, command, parent=None, show_nested=False, commands=None): """Generate the relevant Sphinx nodes. Format a `click.Group` or `click.Command`. :param name: Name of command, as used on the command line :param command: Instance of `click.Group` or `click.Command` :param parent: Instance of `click.Context`, or None :param show_nested: Whether subcommands should be included in output :param commands: Display only listed commands or skip the section if empty :returns: A list of nested docutil nodes """ ctx = click.Context(command, info_name=name, parent=parent) if CLICK_VERSION >= (7, 0) and command.hidden: return [] # Title section = nodes.section( '', nodes.title(text=name), ids=[nodes.make_id(ctx.command_path)], names=[nodes.fully_normalize_name(ctx.command_path)]) # Summary source_name = ctx.command_path result = statemachine.ViewList() lines = _format_command(ctx, show_nested, commands) for line in lines: LOG.debug(line) result.append(line, source_name) self.state.nested_parse(result, 0, section) # Subcommands if show_nested: commands = _filter_commands(ctx, commands) for command in commands: section.extend( self._generate_nodes(command.name, command, ctx, show_nested)) return [section]
def get_help_msg(command): """ Print full help message of click def <function> Ex: print_help_msg(testcmd) :param command: function that has the click command decorator and help option :return: a string containting the @click.command() <function> help message """ with click.Context(command) as ctx: # click.echo(command.get_help(ctx)) return command.get_help(ctx)
def test_eodag_download_no_search_results_arg(self): """Calling eodag download without a path to a search result should fail""" result = self.runner.invoke(eodag, ["download"]) with click.Context(download) as ctx: self.assertEqual( no_blanks(result.output), no_blanks("".join(( "Nothing to do (no search results file provided)", ctx.get_help(), ))), ) self.assertEqual(result.exit_code, 1)
def test_register_email_from_env(monkeypatch: MonkeyPatch, tmp_path: Path) -> None: monkeypatch.setenv("BENTO_EMAIL", "*****@*****.**") ctx = click.Context(cli) context = Context(base_path=INTEGRATION / "simple") context.is_init = True ctx.obj = context registrar = Registrar(click_context=ctx, agree=False) assert registrar.email == "*****@*****.**"
def help_(self): # pylint: disable=unused-argument extra = {} for key, value in command.context_settings.items(): if key not in extra: extra[key] = value # Print click's help message with click.Context(command, info_name=command.name, parent=self.ctx, **extra) as ctx: click.echo(ctx.get_help(), color=ctx.color)
def test_hidden(self): """Validate a `click.Command` with the `hidden` flag.""" @click.command(hidden=True) def foobar(): """A sample command.""" pass ctx = click.Context(foobar, info_name='foobar') output = list(ext._format_command(ctx, show_nested=False)) self.assertEqual('', '\n'.join(output))
def test_empty_pyproject_is_detected_and_injects_nothing( self, cli_runner, testdir): """ctx.params 'src' is set, simulating looking for pyproject.toml in CLI passed formatted file's directory""" pyproject = Path("pyproject.toml") pyproject.touch() ctx = click.Context(click.Command("snakefmt")) ctx.params = dict(src=(str(Path().resolve()), )) param = mock.MagicMock() actual_config_path = inject_snakefmt_config(ctx, param, None) assert actual_config_path == str(pyproject.resolve()) assert ctx.default_map == dict()
def test_ignores_missing_file_if_config_was_not_given_explicitly( self, tmp_path: pathlib.Path) -> None: callback = phile.todo.cli.create_config_option_callback( submap_keys=["package", "name"]) config_path = tmp_path / "config.json" context = click.Context(click.Command("default-missing-okay")) context.set_parameter_source("config", click.core.ParameterSource.DEFAULT) return_value = callback(context, click.Option(("--config", )), config_path) assert return_value == config_path assert context.default_map is None
def cli(pulsar_si, nebula_si, emin, e0, ofname, irf): #check if both pulsar_si nebula_si and Emin are at least one value if (len(pulsar_si) == 0 or len(nebula_si) == 0 or len(emin) == 0): click.echo(cli.get_help(click.Context(cli))) raise click.Abort() if (len(irf) == 0): click.echo(cli.get_help(click.Context(cli))) raise click.Abort() if (ofname is None): click.echo(cli.get_help(click.Context(cli))) raise click.Abort() if (len(e0) == 0): click.echo(cli.get_help(click.Context(cli))) raise click.Abort() # As loading ROOT takes time, I move import here. import PyGammaRateCalculator.scripts.getExpRateDF as c emin_TeV = [e / 1000 for e in emin] df_l = [] for ze, nsb, irfname in irf: for k in e0: norm_P2 = 7.1e-14 * 10000 * np.power(k / 1000, -3.0) # MAGIC A&A @150GeV norm_nebula = 3.10e-11 * 10000 * np.power( k / 1000, -2.5) #TeV^-1 m^-2 s^-1 @ 1TeV df = c.getExpRateDF(irfname, ze, emin_TeV, pulsar_si, nebula_si, norm_P2, norm_nebula, E0=k / 1000, nsb=nsb) df_l.append(df) df = pd.concat(df_l) df['E0'] = df['E0'] * 1000 df['EPrimeMin'] = df['EPrimeMin'] * 1000 df.to_csv(ofname, index=False)
def main(**kwargs): """ Search-That-Hash - The fastest way to crack any hash. \n GitHub:\n https://github.com/HashPals/Search-That-Hash\n Discord:\n https://discord.gg/CswayhQ8Ru \n Usage: \n sth --text "5f4dcc3b5aa765d61d8327deb882cf99" """ if kwargs == { # pragma: no cover "text": None, "file": None, "wordlist": None, "timeout": 3, "greppable": False, "hashcat_binary": None, "offline": False, "verbose": 0, "accessible": False, "no_banner": False, }: with click.Context(main) as ctx: click.echo(ctx.get_help()) ctx.exit() levels = {1: logging.WARNING, 2: logging.INFO, 3: logging.DEBUG} if kwargs["verbose"] and kwargs["verbose"] <= 3: coloredlogs.install(level=levels[kwargs["verbose"]]) else: # Verobosity was not given so it removes logging coloredlogs.install(level=logging.CRITICAL) logging.debug("Updated logging level") logging.info("Called config updater") config = config_object.cli_config(kwargs) if not kwargs["greppable"] and not kwargs["accessible"] and not kwargs[ "no_banner"]: logging.info("Printing banner") printing.Prettifier.banner() cracking_handler = handler.Handler(config) cracking_handler.start() exit(0)
def send_column_keys(user_id, device_id, policy): table = get_tinydb_table(path, 'device_keys') doc = table.get(Query().device_id == device_id) if not doc: with click.Context(send_key_to_device) as ctx: click.echo( f"Keys for device {device_id} not present, please use: {ctx.command.name}" ) click.echo(get_attr_auth_keys.get_help(ctx)) return fernet_key = hex_to_fernet(doc["shared_key"]) keys = { "action:name": None, "device_data:added": None, "device_data:num_data": None, "device_data:tid": None } payload_keys = {} for k in keys: random_bytes = os.urandom(32) keys[k] = key_to_hex( random_bytes) # NOTE: retrieve key as `key_to_hex(key)` payload_keys[k] = fernet_key.encrypt(random_bytes).decode() # payload_keys["device_data:data"] = fernet_key.encrypt(get_aa_public_key().encode()).decode() abe_key_and_policy = json.dumps({ "public_key": get_aa_public_key(), "policy": policy }).encode() payload_keys["device_data:data"] = fernet_key.encrypt( abe_key_and_policy).decode() payload_keys["device:name"] = fernet_key.encrypt( hex_to_key(doc["device:name"])).decode() payload_keys["device:status"] = fernet_key.encrypt( hex_to_key(doc["device:status"])).decode() payload_keys["bi_key"] = fernet_key.encrypt(hex_to_key( doc["bi_key"])).decode() payload_keys["scene_key"] = fernet_key.encrypt( get_global_scene_key()).decode() doc = {**doc, **keys} table.upsert(doc, Query().device_id == device_id) client = _setup_client(user_id) payload = f'"{json.dumps(_create_payload(payload_keys, user_id))}"' ret = client.publish(f"u:{user_id}/d:{device_id}/", payload) click.echo(f"RC and MID = {ret}")
def cli(): global from_command_line from_command_line = True command = " ".join(sys.argv) change_working_directory() logger = setup_logging() logger.info(command) if len(sys.argv) > 1 and sys.argv[1] not in ("src", ): check_uid() change_uid() change_dir() if is_dist_editable(bench.PROJECT_NAME) and len( sys.argv) > 1 and sys.argv[1] != "src" and not get_config(".").get( "developer_mode"): log("bench is installed in editable mode!\n\nThis is not the recommended mode of installation for production. Instead, install the package from PyPI with: `pip install frappe-bench`\n", level=3) if not is_bench_directory() and not cmd_requires_root() and len( sys.argv) > 1 and sys.argv[1] not in ("init", "find", "src"): log("Command not being executed in bench directory", level=3) if len(sys.argv) > 2 and sys.argv[1] == "frappe": return old_frappe_cli() elif len(sys.argv) > 1: if sys.argv[1] in get_frappe_commands() + [ "--site", "--verbose", "--force", "--profile" ]: return frappe_cmd() elif sys.argv[1] == "--help": print(click.Context(bench_command).get_help()) print(get_frappe_help()) return elif sys.argv[1] in get_apps(): return app_cmd() if not (len(sys.argv) > 1 and sys.argv[1] == "src"): atexit.register(check_latest_version) try: bench_command() except BaseException as e: return_code = getattr(e, "code", 0) if return_code: logger.warning("{0} executed with exit code {1}".format( command, return_code)) sys.exit(return_code)
def generate_cli_docs(): """Generate Markdown friendly CLI API documentation.""" print("# reana-client CLI API\n") print("The complete `reana-client` CLI API reference guide is available here:\n") print(f"- [{CLI_API_URL}]({CLI_API_URL})\n") with click.Context(cli) as ctx: _print_code_block(cli.get_help(ctx), lang="console") for cmd_group in cli.cmd_groups: print("\n## {}".format(cmd_group.help)) for cmd_obj in cmd_group.commands.values(): print("\n### {}\n".format(cmd_obj.name)) print(cmd_obj.help)
def info(patch): """Get info for a given patch""" patches = troi.utils.discover_patches() if patch not in patches: print( "Cannot load patch '%s'. Use the list command to get a list of available patches." % patch, file=sys.stderr) sys.exit(1) apatch = patches[patch] context = click.Context(apatch.parse_args, info_name=patch) click.echo(apatch.parse_args.get_help(context))
def recursive_subcommand_loader(root, path=''): """Recursively load and list every command.""" if getattr(root, 'list_commands', None) is None: return ctx = click.Context(root) for command in root.list_commands(ctx): new_path = '%s:%s' % (path, command) logging.info("loading %s", new_path) new_root = root.get_command(ctx, command) recursive_subcommand_loader(new_root, path=new_path)
def _emit_command_options(command): help_records = [ p.get_help_record(click.Context(command)) for p in command.params if isinstance(p, click.Option) ] if help_records: result = "\n\n" + _emit_header("Options", level=3) + "\n\n" result += "\n".join(" * **`%s`**: %s" % (option, option_help) for option, option_help in help_records) return result else: return ""
def test_unknown_options_in_pyproject_get_parsed(self, testdir): pyproject = Path("pyproject.toml") pyproject.write_text("[tool.snakefmt]\nfoo = true") ctx = click.Context(click.Command("snakefmt"), default_map=dict()) ctx.params = dict(src=(str(Path().resolve()), )) param = mock.MagicMock() parsed_config_file = inject_snakefmt_config(ctx, param, config_file=None) assert parsed_config_file == str(pyproject.resolve()) expected_parameters = dict(foo=True) assert ctx.default_map == expected_parameters
def test_show_default_boolean_flag_value(runner): """When a boolean flag only has one opt, it will show the default value, not the opt name. """ opt = click.Option( ("--cache", ), is_flag=True, show_default=True, help="Enable the cache.", ) ctx = click.Context(click.Command("test")) message = opt.get_help_record(ctx)[1] assert "[default: False]" in message
def test_args_to_config_normal() -> None: # Always recreate context since it is modified destructively and the tests # will be flaky ctx = click.Context(click.Command('test'), obj=None) config_options = cli._get_configuration_options(MyConfig) cfg = cli._args_to_config(ctx, MyConfig, config_options, opt1=True, opt2='hello') assert cfg.opt1 assert cfg.opt2 == 'hello'
def cli(ctx, subcommand): """Display help for a given command or popper default help """ if subcommand: target_command = popper_cli.get_command(ctx, subcommand) log.info(target_command.get_help(click.Context(popper_cli))) # log.info("") # popper is not happy with this line else: log.info(popper_cli.get_help(click.Context(popper_cli))) log.info("") log.info("""If you enjoy using popper, please leave us a star at https://github.com/getpopper/popper!""") log.info("") log.info("""If you have encountered any bugs or issues, please start a discussion at the github repository""") log.info( "or discuss Popper with us in our slack at the following link:") log.info("https://bit.ly/join-popper-slack") log.info("") log.info("""Finally, please give us your feedback using this survey! https://bit.ly/popper-survey""")