def web(ctx: Context, config_file: str): """Software Heritage web client""" import logging from swh.core import config from swh.web.client.client import WebAPIClient if not config_file: config_file = DEFAULT_CONFIG_PATH try: conf = config.read_raw_config(config.config_basepath(config_file)) if not conf: raise ValueError(f"Cannot parse configuration file: {config_file}") # TODO: Determine what the following conditional is for if config_file == DEFAULT_CONFIG_PATH: try: conf = conf["swh"]["web"]["client"] except KeyError: pass # recursive merge not done by config.read conf = config.merge_configs(DEFAULT_CONFIG, conf) except Exception: logging.warning("Using default configuration (cannot load custom one)", exc_info=True) conf = DEFAULT_CONFIG ctx.ensure_object(dict) ctx.obj["client"] = WebAPIClient(conf["api_url"], conf["bearer_token"])
def get_command(self, ctx: Context, name: str) -> Optional[Union[Command, 'PluginCLI']]: # Dashes aren't valid in Python identifiers, so let's just replace them here. name = name.replace('-', '_') command_map: Dict[str, str] = self.command_to_canonical_map if name in command_map: return self._get_command(command_map[name]) matches = match_prefix(command_map.keys(), name, return_unique=False) if matches is None: matches = [] if len(matches) == 1: match = command_map[matches[0]] return self._get_command(match) if ' ' not in name: cmd = self._try_suffix_match(ctx, name) if cmd: return cmd if len(matches) > 1: ctx.fail('"{name}" matches {matches}; be more specific?'.format( name=name, matches=', '.join( click.style(match, bold=True) for match in sorted(matches)))) return None
def global_callback(ctx: Context, global_args: PropertyDict, tasks: List) -> None: def move_to_front(task_name: str) -> None: for index, task in enumerate(tasks): if task.name == task_name: tasks.insert(0, tasks.pop(index)) break debug_targets = any( [task.name in ('openocd', 'gdbgui') for task in tasks]) if debug_targets: # Register the meta cleanup callback -> called on FatalError ctx.meta['cleanup'] = debug_cleanup move_to_front('gdbgui') # possibly 2nd move_to_front('openocd') # always 1st # followed by "monitor", "gdb" or "gdbtui" in any order post_action = ctx.invoke(ctx.command.get_command( ctx, 'post_debug')) if any( [task.name in ('monitor', 'gdb', 'gdbtui') for task in tasks]): post_action.action_args['block'] = 0 else: post_action.action_args['block'] = 1 tasks.append(post_action) # always last if any([task.name == 'openocd' for task in tasks]): for task in tasks: if task.name in ('gdb', 'gdbgui', 'gdbtui'): task.action_args['require_openocd'] = True
def cli(ctx: Context, config_path: str, verbose: bool) -> None: """Command line interface main click entrypoint.""" ctx.ensure_object(dict) ctx.obj["config"] = load_config(config_path) ctx.obj["repo"] = get_repo(ctx.obj["config"]) load_logger(verbose)
def stakkr(ctx: Context, config=None, debug=False, verbose=True): """Click group, set context and main object.""" from stakkr.actions import StakkrActions ctx.obj['CONFIG'] = config ctx.obj['DEBUG'] = debug ctx.obj['VERBOSE'] = verbose ctx.obj['STAKKR'] = StakkrActions(ctx.obj)
def genfolder(ctx: Context, folder: str, template: str, extension: str = None, output: str = None, search: str = None, exclprefix: list = None, root: str = None, recurse: bool = False, exit: bool = False, overwrite: bool = False): """ Command used for, generating the documentation for an entire folder of YAML files. """ # Set the default values. if not output: output = folder if not root: root = folder # Validate the paths. os.path.isdir(folder) os.path.isdir(output) os.path.isdir(root) os.path.isfile(template) print(search) # Do we want to recursively search? files = FileHelper.get_files(folder, search, recurse) print(f'Found {len(files)} YAML files to generate the docs for...\n') # If there are no files to process throw an error. if len(files) == 0: raise Exception( 'No files were found to generate docs for. Double check your search pattern.' ) # Loop through each of the files and generate the docs. for idx, file in enumerate(files): print(f'[{idx + 1}/{len(files)}] - {file}\n') ctx.invoke(genfile, file=file, template=template, output=FileHelper.exchange_file_extension(file, extension), exclprefix=exclprefix, root=folder, exit=exit, overwrite=overwrite)
def print_version(ctx: Context, param: Option, value: bool) -> None: """ Print version information of cli :param ctx: click context :param param: current parameter's metadata :param value: value of current parameter """ if not value or ctx.resilient_parsing: return click.echo('{title}, version {version}.'.format(title=__TITLE__.capitalize(), version=__VERSION__)) click.echo('Developed by {author}, {email}.'.format(author=__AUTHOR__, email=__AUTHOR_EMAIL__)) ctx.exit()
def wrapper(ctx: Context, *args, **kwargs) -> None: """Work with given function""" msg = function(*args, **kwargs) if msg.get("always_print", True) or ctx.obj.get( "invoked_internally_by") not in ctx.obj.get( "do_not_print_when_invoked_by", []): echo_wr(msg) if msg.get("err"): ctx.abort()
def get_command(self, ctx: Context, cmd_name: str) -> Optional[Command]: rv = click.Group.get_command(self, ctx, cmd_name) if rv is not None: return rv matches = [ x for x in self.list_commands(ctx) if x.startswith(cmd_name) ] if not matches: return None elif len(matches) == 1: return click.Group.get_command(self, ctx, matches[0]) ctx.fail("Too many matches: %s" % ", ".join(sorted(matches)))
def parse_args(self: Command, ctx: Context, args: List[str], supportsLiterals: Callable[[click.Parameter], bool]): if not args and self.no_args_is_help and not ctx.resilient_parsing: click.echo(ctx.get_help(), color=ctx.color) ctx.exit() args = PrettyHelper.parse_line(args) ctx.original_params = args.copy() parser = self.make_parser(ctx) opts, args, param_order = parser.parse_args(args=args) ctx.original_args = args.copy() i = 0 for param in iter_params_for_processing(param_order, self.get_params(ctx)): if supportsLiterals(param): value, args, i = param.handle_parse_result(ctx, opts, args, i) else: value, args = param.handle_parse_result(ctx, opts, args) if args and not ctx.allow_extra_args and not ctx.resilient_parsing: ctx.fail("Got unexpected extra argument{} ({})".format( "s" if len(args) != 1 else "", " ".join(map(make_str, args)))) ctx.args = args return args
def restart(ctx: Context, container: str, pull: bool, recreate: bool, proxy: bool): """See command Help.""" print(click.style('[RESTARTING]', fg='green') + ' your stakkr services') try: ctx.invoke(stop, container=container, proxy=proxy) except Exception: pass ctx.invoke(start, container=container, pull=pull, recreate=recreate, proxy=proxy)
def run_commands(ctx: Context, extra_args: tuple, tty: bool): """Run commands for a specific alias""" commands = ctx.obj['STAKKR'].get_config()['aliases'][ ctx.command.name]['exec'] for command in commands: user = command['user'] if 'user' in command else 'root' container = command['container'] args = command['args'] + list( extra_args) if extra_args is not None else [] ctx.invoke(exec_cmd, user=user, container=container, command=args, tty=tty)
def get_help(self: Command, ctx: Context): """Formats the help into a string and returns it. """ print() formatter = ctx.make_formatter() self.format_help(ctx, formatter) txt = formatter.getvalue().rstrip("\n") return '\t' + '\t'.join(txt.splitlines(True))
def cli(ctx: Context, previous_version: str, current_version: str) -> None: """Welcome to change log generator""" previous_logs = GitLogs(previous_version) current_logs = GitLogs(current_version) previous_logs.fetch() current_logs.fetch() base_parameters = BaseParameters(previous_logs, current_logs) ctx.obj = base_parameters
def cli(ctx: Context, config_path: str, verbose: bool) -> None: """Command line interface main click entrypoint.""" ctx.ensure_object(dict) ctx.obj["config"] = load_config(config_path) try: ctx.obj["drone"] except KeyError: ctx.obj["drone"] = load_drone() try: ctx.obj["aws"] except KeyError: ctx.obj["aws"] = load_aws() load_logger(verbose)
def test_context_aware_command_valid(_): """Check command succeeds when context exists.""" def test_callback(): return 10 command = ContextAwareCommand(name='test-command', callback=test_callback) context = Context(command) assert command.invoke(context) == 10
def invoke_brick_command(monkeypatch, command: str, folder: str, recursive=False) -> Result: # pylint: disable import-outside-toplevel if recursive: assert folder == EXAMPLES_FOLDER monkeypatch.chdir(folder) # The funky import order and module reloading is due to the monkey patching # and the nature of the code running when the modules are imported. from brick import lib importlib.reload(lib) from brick import __main__ importlib.reload(__main__) commands = { "build": __main__.build, "deploy": __main__.deploy, "prepare": __main__.prepare, "test": __main__.test, } command_fn = commands[command] parent = Context(command=command_fn) if recursive: parent.params = {"recursive": True} runner = CliRunner() result = runner.invoke(command_fn, args=None, parent=parent) if result.exception: raise result.exception assert result.exit_code == 0 return result
def console(ctx: Context, container: str, user: str, tty: bool): """See command Help.""" ctx.obj['STAKKR'].init_project() ctx.obj['CTS'] = get_running_containers_names( ctx.obj['STAKKR'].project_name) if ctx.obj['CTS']: ct_choice = click.Choice(ctx.obj['CTS']) ct_choice.convert(container, None, ctx) ctx.obj['STAKKR'].console(container, _get_cmd_user(user, container), tty)
def exec_cmd(ctx: Context, user: str, container: str, command: tuple, tty: bool): """See command Help.""" ctx.obj['STAKKR'].init_project() ctx.obj['CTS'] = get_running_containers_names( ctx.obj['STAKKR'].project_name) if ctx.obj['CTS']: click.Choice(ctx.obj['CTS']).convert(container, None, ctx) ctx.obj['STAKKR'].exec_cmd(container, _get_cmd_user(user, container), command, tty)
def main(ctx: Context): """A simple program to make flatpak build and test easier""" obj = AttrDict() ctx.obj = obj obj.repo_dir = os.environ.get( "FLATPAK_REPO", os.path.expandvars(os.path.expanduser("~/.local/share/flatpak-repo")), ) obj.build_dir = os.environ.get("FLATPAK_BUILD_DIR", "./.build")
def recursive_help(cmd, parent=None): ctx = Context(cmd, info_name=cmd.name, parent=parent) print("```") print(cmd.get_help(ctx)) print("```") commands = getattr(cmd, "commands", {}) for sub in commands.values(): if isinstance(sub, Group): print("## " + sub.name) elif isinstance(sub, Command): print("### " + sub.name) recursive_help(sub, ctx)
def restart( ctx: Context, force: bool, apply: bool, service_names: tuple[str, ...] ): """Restarts service(s) Args: ctx (Context): Click Context for current CLI. force (bool, optional): If True, pass force to all subcommands. Defaults to False. apply (bool, optional): If True, configure apply after service(s) are stopped. Defaults to False. service_names (tuple[str, ...], optional): The name of the service(s) to restart. If not provided, will restart all services. """ cli_context: CliContext = ctx.obj configure_cli = cli_context.commands["configure"] # At completion, the invoked commands try to exit the script, so we have to catch # the SystemExit exception. try: ctx.invoke(stop, service_names=service_names) except SystemExit: pass if apply: try: ctx.invoke( configure_cli.commands["apply"], message="[autocommit] due to `configure apply` triggered by `service restart --apply`", force=force, ) except SystemExit: pass ctx.invoke(start, force=force, service_names=service_names)
def main(ctx: Context, user: str, device: str): if not user and not device: print(ctx.get_help()) sys.exit(1) client_args = axonapi.get_env_connect() client = CustomConnect(**client_args) client.start() if user: client.run(user_search_criteria=user) elif device: client.run(device_search_criteria=device)
def cli(context: Context, check_signatures: bool, verbosity: int = LOGGING_DEFAULT): """Verifies embedded signatures, and the integrity of docker image layers and metadata.""" if verbosity is None: verbosity = LOGGING_DEFAULT set_log_levels(verbosity) context.obj = { "check_signatures": check_signatures, "verbosity": verbosity }
def cli(ctx: ClickContext): if 'debian' not in Sys.id_like(): ctx.fail("Sorry, sutler only supports Debian based systems") app = ctx.ensure_object(App) if app.is_root(): ctx.fail("You're not allowed to run sutler as root") if ctx.invoked_subcommand is None: click.echo(ctx.get_help())
def resolve_command(self: MultiCommand, ctx: Context, args): cmd_name = make_str(args[0]) original_cmd_name = cmd_name # Get the command cmd = self.get_command(ctx, cmd_name) # If we can't find the command but there is a normalization # function available, we try with that one. if cmd is None and ctx.token_normalize_func is not None: cmd_name = ctx.token_normalize_func(cmd_name) cmd = self.get_command(ctx, cmd_name) # Command not found if cmd is None and not ctx.resilient_parsing: PrettyHelper.VerifyCommand(self, ctx) ctx.abort() # if split_opt(cmd_name)[0]: # self.parse_args(ctx, ctx.args) # ctx.fail("No such command '{}'.".format(original_cmd_name)) return cmd_name, cmd, args[1:]
async def cli(ctx: ClickContext, files: Path, outdir: Path) -> None: """Convert files from a digiarch generated file database. OUTDIR specifies the directory in which to output converted files. It must be an existing directory.""" try: file_db: FileDB = FileDB(f"sqlite:///{files}") except Exception: raise click.ClickException(f"Failed to load {files} as a database.") else: click.secho("Collecting files...", bold=True) files_: List[ArchiveFile] = await file_db.get_files() if not files_: raise click.ClickException("Database is empty. Aborting.") ctx.obj = FileConv(files=files_, db=file_db, out_dir=outdir)
def cli( ctx: Context, version: str, version_rc: str, ) -> None: """Welcome to releasing send email CLI interface!""" base_parameters = BaseParameters(version, version_rc) base_parameters.template_arguments["receiver_email"] = RECEIVER_EMAIL base_parameters.template_arguments["project_name"] = PROJECT_NAME base_parameters.template_arguments["project_module"] = PROJECT_MODULE base_parameters.template_arguments[ "project_description"] = PROJECT_DESCRIPTION base_parameters.template_arguments["version"] = base_parameters.version base_parameters.template_arguments[ "version_rc"] = base_parameters.version_rc ctx.obj = base_parameters
def cli( context: Context, dry_run: False, signature_type: "sign", verbosity: int = LOGGING_DEFAULT, ): """Creates and embeds signatures into docker images.""" if verbosity is None: verbosity = LOGGING_DEFAULT set_log_levels(verbosity) context.obj = { "dry_run": dry_run, "signature_type": signature_type, "verbosity": verbosity, }
def cli( context: Context, check_signatures: bool, dry_run: False, verbosity: int = LOGGING_DEFAULT, ): """Replicates docker images while verifying embedded signatures, and the integrity of docker image layers and metadata.""" if verbosity is None: verbosity = LOGGING_DEFAULT set_log_levels(verbosity) context.obj = { "check_signatures": check_signatures, "dry_run": dry_run, "verbosity": verbosity, }