def product_completer(prefix: str, parsed_args: argparse.Namespace, **kwargs: Any) -> Iterable[str]: """Returns a list of all the products available in the current repo source tree.""" products = [] product_globpat = os.path.join(repo_root_path(), "products", "*") try: for product_path in glob.glob(product_globpat): if not os.path.isdir(product_path): continue _product_path_split = os.path.normpath(product_path).split("/") product_name = _product_path_split[-1] try: product_obj = Product(product_name) except Exception as exc: exctype = exc.__class__.__name__ argcomplete.warn( line(""" An exception {!r} occured when evaluating product {!r}.""").format(exctype, product_name)) continue products.append(product_name) except Exception as exc: exctype = exc.__class__.__name__ argcomplete.warn( line(""" An exception {!r} occured when enumerating all the available products.""").format(exctype)) return products
def complete2(self, args, prefix): super(DocumentsUploadAndSharingCommand, self).__call__(args) from argcomplete import warn if len(prefix) >= 3: json_obj = self.ls.users.list() guesses = [] mails = [] cpt = 0 for user in json_obj: mail = user.get('mail') if re.match(".*" + prefix + ".*", mail): guesses.append(mail) if mail.startswith(prefix): cpt += 1 mails.append(mail) if cpt >= 5: break if mails: return mails else: cpt = 0 warning = ["Some results :"] for i in guesses: cpt += 1 warning.append(" * " + i + "\n") if cpt >= 4: break warn("".join(warning)) return guesses else: warn("Completion need at least 3 characters.")
def _PerformCloudListing(self, wildcard_url, timeout): """Perform a remote listing request for the given wildcard URL. Args: wildcard_url: The wildcard URL to list. timeout: Time limit for the request. Returns: Cloud resources matching the given wildcard URL. Raises: TimeoutError: If the listing does not finish within the timeout. """ request_thread = CloudListingRequestThread(wildcard_url, self._gsutil_api) request_thread.start() request_thread.join(timeout) if request_thread.is_alive(): # This is only safe to import if argcomplete is present in the install # (which happens for Cloud SDK installs), so import on usage, not on load. # pylint: disable=g-import-not-at-top import argcomplete argcomplete.warn(_TIMEOUT_WARNING % timeout) raise TimeoutError() results = request_thread.results return results
def variable_set_completer(prefix, **kwargs): # Use dummy template and dest directory # TODO: make this less janky DUMMY = '/tmp/' try: var_sets = Zenbu( DUMMY, DUMMY, ZENBU_VAR_SETS, ignores_path=ZENBU_IGNORES, ).var_sets except NotFoundError as e: # Try again with no ignores file try: var_sets = Zenbu( DUMMY, DUMMY, ZENBU_VAR_SETS, ).var_sets except NotFoundError as e: argcomplete.warn(e) except Exception as e: argcomplete.warn(e) else: return (v for v in var_sets if v.startswith(prefix))
def wrapper(parsed_args, **kwds): import argcomplete try: with cd(parsed_args.C) if getattr(parsed_args, 'C', None) else DummyContextManager() as _: return f(parsed_args=parsed_args, **kwds) except Exception as e: argcomplete.warn('An error occurred during argument completion: {}'.format(e))
def variable_set_completer(prefix, **kwargs): # Use dummy template and dest directory # TODO: make this less janky DUMMY = '/tmp/' try: var_sets = Whizker( DUMMY, DUMMY, WHIZKERS_VAR_SETS, ignores=WHIZKERS_IGNORES, ).var_sets except FileNotFoundError as e: # Try again with no ignores file try: var_sets = Whizker( DUMMY, DUMMY, WHIZKERS_VAR_SETS, ).var_sets except FileNotFoundError as e: argcomplete.warn(e) except FileParseError as e: argcomplete.warn(e) else: return (v for v in var_sets if v.startswith(prefix))
def __call__(self, prefix, **kwargs): from argcomplete import debug try: debug("\n------------ DefaultCompleter -----------------") debug("Kwargs content :") for i, j in kwargs.items(): debug("key : " + str(i)) debug("\t - " + str(j)) debug("\n------------ DefaultCompleter -----------------\n") args = kwargs.get('parsed_args') # pylint: disable-msg=W0612 parser = kwargs.get('parser') #a = parser.parse_known_args() # getting form args the current Command and looking for a method # called by default 'complete'. See __init__ method. The method # name is store in the class member called self.func_name fn = getattr(args.__func__, self.func_name, None) if fn: return fn(args, prefix) # pylint: disable-msg=W0703 except Exception as e: from argcomplete import warn warn("\nERROR::COMPLETE:An exception was caught :" + str(e) + "\n") import traceback traceback.print_exc() debug("\n------\n") return ["comlete-error"]
def endpoint_autocomplete(prefix, parsed_args, **kwargs): interfaces = UserCacheFile('webapi_interfaces.json').read_json() if not interfaces: warn("To enable endpoint tab completion run: steamctl webapi list") return [] return ('{}.{}'.format(a['name'], b['name']) for a in interfaces for b in a['methods'])
def complete(self, args, prefix): super(DocumentsUploadAndSharingCommand, self).__call__(args) from argcomplete import warn if len(prefix) >= 3: json_obj = self.ls.users.list() return (v.get('mail') for v in json_obj if v.get('mail').startswith(prefix)) else: warn("Completion need at least 3 characters.")
def wrapper(parsed_args, **kwds): import argcomplete try: with cd(parsed_args.C) if getattr( parsed_args, 'C', None) else DummyContextManager() as _: return f(parsed_args=parsed_args, **kwds) except Exception as e: argcomplete.warn( 'An error occurred during argument completion: {}'.format(e))
def __call__(self, parsed_args, **kwargs): argcomplete.warn("going through call") # p = Path(parser_args.rpkgmngroot+'/') # argcomplete.warn(p) # self.choices=['test','test2'] # for child in p.iterdir(): # self.choices.append(child) # argcomplete.warn(child) return self.choices
def _completer_warn(message): """ Show warning when autocompleting. Args: message (str): message """ from argcomplete import warn from accelpy._common import warn as warn_color warn(warn_color(message))
def wrapped(**kwargs): completions = [] try: completions = fn(**kwargs) except RepositoryException: warn("No repository at/below CWD") except: t,v,_ = sys.exc_info() warn("Unhandled exception: %s(%s)" % (t.__name__, v)) return completions
def __call__(self, prefix, action=None, parsed_args=None): if prefix == "": prefix = "codalab" first_slash = prefix.find('/') trimmed_prefix = prefix[0:first_slash] if first_slash >= 0 else prefix try: client = docker.from_env() return (img['name'] for img in client.images.search(trimmed_prefix)) except docker.errors.APIError as ex: warn('Error: {}'.format(ex))
def __call__(self, prefix, action=None, parser=None, parsed_args=None): if prefix == "": prefix = "codalab" first_slash = prefix.find('/') trimmed_prefix = prefix[0:first_slash] if first_slash >= 0 else prefix try: client = docker.from_env() return (img['name'] for img in client.images.search(trimmed_prefix)) except docker.errors.APIError as ex: warn('Error: {}'.format(ex))
def argcomplete_warn_redraw_prompt(prefix, message): argcomplete = import_argcomplete('argcomplete_warn_redraw_prompt') if prefix != '': argcomplete.warn(message) try: shell_pid = int(os.popen('ps -p %d -oppid=' % os.getppid()).read().strip()) os.kill(shell_pid, 28) except ValueError: pass _ = '_' if locale.getlocale()[1] != 'UTF-8' else '\xa0' return [_+message.replace(' ', _), '']
def _get_location_from_resource_group(cli_ctx, resource_group_name): from ._client_factory import cf_resource_groups from msrestazure.azure_exceptions import CloudError try: rg = cf_resource_groups(cli_ctx).get(resource_group_name) return rg.location except CloudError as err: # Print a warning if the user hit [TAB] but the `--resource-group` argument was incorrect. # For example: "Warning: Resource group 'bogus' could not be found." from argcomplete import warn warn('Warning: {}'.format(err.message))
def __call__(self, prefix, parsed_args, **kwargs): foreman = ForemanClient(host="judy.cern.ch", port=8443, timeout=15, dryrun=True) if prefix == '': query = '' else: query = "%s~%s" % (self.item, prefix) try: response = foreman.search_query(self.model,query) except AiToolsForemanError: warn("Tab completion could not connect to Foreman") return return [item[self.item] for item in response if item[self.item].startswith(prefix) ]
def ios_devices(prefix, parsed_args, **kwargs): """ Returns all connected iOS devices. :param prefix: The prefix text of the last word before the cursor on the command line. :param parsed_args: The result of argument parsing so far. :param kwargs: keyword arguments. :returns list: list of all connected iOS devices. """ devices = ios.list_devices() if not devices: warn("No connected iOS devices") return devices
def __call__(self, prefix, action=None, parser=None, parsed_args=None): import docker from codalab.worker.docker_utils import DEFAULT_DOCKER_TIMEOUT if prefix == "": prefix = "codalab" first_slash = prefix.find('/') trimmed_prefix = prefix[0:first_slash] if first_slash >= 0 else prefix try: client = docker.from_env(timeout=DEFAULT_DOCKER_TIMEOUT) return (img['name'] for img in client.images.search(trimmed_prefix)) except docker.errors.APIError as ex: warn('Error: {}'.format(ex))
def keymap_completer(prefix, action, parser, parsed_args): """Returns a list of keymaps for tab completion. """ try: if parsed_args.keyboard: return list_keymaps(parsed_args.keyboard) keyboard = find_keyboard_from_dir() if keyboard: return list_keymaps(keyboard) except Exception as e: argcomplete.warn(f'Error: {e.__class__.__name__}: {str(e)}') return [] return []
def recipe_completer(prefix: str, parsed_args: argparse.Namespace, **kwargs: Any) -> Iterable[str]: """Returns a list of all the recipes available in the current repo source tree that would be appropriate regarding the current parsed arguments from the :py:func:`main()` function of ``cosmk``.""" current_subcommand = parsed_args.subcommand try: # get the eligible features for the current action: eligible_features = features_for_action(current_subcommand) except Exception as exc: exctype = exc.__class__.__name__ argcomplete.warn( line(""" An exception {!r} occured when identifying the recipes features providing action {!r}""").format(exctype, current_subcommand)) if not eligible_features: argcomplete.warn("No recipe feature provide action {!r}.".format( current_subcommand)) return [] recipes = [] recipe_globpat = os.path.join(repo_root_path(), "products", "*", "*") try: for recipe_path in glob.glob(recipe_globpat): if not os.path.isdir(recipe_path): continue _recipe_path_split = os.path.normpath(recipe_path).split("/") recipe = _recipe_path_split[-1] product = _recipe_path_split[-2] recipe_toml = os.path.join(recipe_path, "recipe.toml") if not os.path.exists(recipe_toml): continue try: recipe_identifier = "{}/{}".format(product, recipe) recipe_obj = Recipe(recipe_identifier) except Exception as exc: exctype = exc.__class__.__name__ argcomplete.warn( line(""" An exception {!r} occured when evaluating recipe {!r}.""").format(exctype, recipe_identifier)) continue if set(eligible_features) & set(recipe_obj.features.keys()): recipes.append(recipe_identifier) except Exception as exc: exctype = exc.__class__.__name__ argcomplete.warn( line(""" An exception {!r} occured when enumerating all the available recipes.""").format(exctype)) return recipes
def bucket_name_completer(prefix, parsed_args, **kwargs): parse_argument(args=parsed_args) if not (access_key is None) and not (secret_key is None) and not (region is None): argcomplete.warn(str(enable_https) + ' ' + str(enable_cdn) + ' ' + str(region)) fds_config = FDSClientConfiguration(region_name=region, enable_https=enable_https, enable_cdn_for_download=enable_cdn, enable_cdn_for_upload=enable_cdn) fds_client = GalaxyFDSClient(access_key=access_key, access_secret=secret_key, config=fds_config) bucket_list = get_buckets(fds_client=fds_client) rtn = [] for i in bucket_list: if i.startswith(prefix): rtn.append(i) return rtn return ['a', 'b', 'c']
def _get_location(cli_ctx, namespace): """ Return an Azure location by using an explicit `--location` argument, then by `--resource-group`, and finally by the subscription if neither argument was provided. """ from azure.core.exceptions import HttpResponseError from azure.cli.core.commands.parameters import get_one_of_subscription_locations location = None if getattr(namespace, 'location', None): location = namespace.location elif getattr(namespace, 'resource_group_name', None): try: location = _get_location_from_resource_group(cli_ctx, namespace.resource_group_name) except HttpResponseError as err: from argcomplete import warn warn('Warning: {}'.format(err.message)) if not location: location = get_one_of_subscription_locations(cli_ctx) return location
def parameter_autocomplete(prefix, parsed_args, **kwargs): interfaces = UserCacheFile('webapi_interfaces.json').read_json() if not interfaces: warn("To enable endpoint tab completion run: steamctl webapi list") return [] parameters = [] ainterface, amethod = parsed_args.endpoint.split('.', 1) for interface in filter(lambda a: a['name'] == ainterface, interfaces): for method in filter(lambda b: b['name'] == amethod, interface['methods']): for param in method['parameters']: if param['name'][-3:] == '[0]': param['name'] = param['name'][:-3] parameters.append(param['name'] + '=') break return parameters
def complete_command_name(prefix: str, parsed_args: argparse.Namespace, **kwargs) -> List[str]: """ Returns a list of all command names that could possibly complete the given prefix """ # Kwargs arguments required for argcomplete, so suppress warning # pylint: disable=unused-argument dict_path = "" try: dict_path = get_dictionary_path(parsed_args) except ValueError: argcomplete.warn("No dictionary found to get command names from") return [] from fprime_gds.common.pipeline.dictionaries import Dictionaries dictionary = Dictionaries() dictionary.load_dictionaries(dict_path, None) command_names = dictionary.command_name.keys() return [name for name in command_names if name.startswith(prefix)]
def _get_completions(self, comp_words, cword_prefix, cword_prequote, last_wordbreak_pos): ''' Intercept argcomplete and allow attaching our own completers (which can be attached to functions in addition to arguments). This allows us to do command delegation without knowing their relationship ahead of time. ''' try: _container['completion'] = (comp_words, cword_prefix) completions = commandobj.complete( args if args is not None else comp_words[1:]) completions = self.filter_completions(completions) completions = self.quote_completions( completions, cword_prequote, last_wordbreak_pos) del _container['completion'] return completions except BaseException as e: argcomplete.warn(e, traceback.print_exc())
def runner_input_completer(prefix, parsed_args, **kwargs): # argcomplete completer for `miniwdl run` and `miniwdl cromwell` if "uri" in parsed_args: # load document. in the completer setting, we need to substitute the home directory # and environment variables uri = os.path.expandvars(os.path.expanduser(parsed_args.uri)) if not (runtime.download.able(uri) or os.path.exists(uri)): argcomplete.warn("file not found: " + uri) return [] try: doc = load( uri, path=(parsed_args.path if hasattr(parsed_args, "path") else []), check_quant=parsed_args.check_quant, read_source=read_source, ) except Exception as exn: argcomplete.warn( "unable to load {}; try 'miniwdl check' on it ({})".format( uri, str(exn))) return [] # resolve target if doc.workflow: target = doc.workflow elif len(doc.tasks) == 1: target = doc.tasks[0] elif len(doc.tasks) > 1: argcomplete.warn( "WDL document contains multiple tasks and no workflow") return [] else: argcomplete.warn("WDL document is empty") return [] assert target # figure the available input names (starting with prefix, if any) available_input_names = [ nm + "=" for nm in values_to_json(target.available_inputs) ] if prefix and prefix.find("=") == -1: available_input_names = [ nm for nm in available_input_names if nm.startswith(prefix) ] # TODO idea -- complete only required inputs until they're all present, then start # completing the non-required inputs. Tricky with arrays, because we want to keep # allowing their completion even after already supplied. # compute set of inputs already supplied return available_input_names
def complete_mail(self, args, prefix): """TODO""" # pylint: disable=unused-argument super(ThreadMembersCommand, self).__call__(args) from argcomplete import warn if len(prefix) >= 3: json_obj = self.ls.users.list() return (v.get('mail') for v in json_obj if v.get('mail').startswith(prefix)) warn("---------------------------------------") warn("Completion need at least 3 characters.") warn("---------------------------------------") return None
def __call__(self, **kwargs): try: return self._complete(**kwargs) except Exception as e: argcomplete.warn(e)
def _run_command(): """ Command line entry point """ from os import environ from argparse import ArgumentParser from argcomplete import autocomplete from argcomplete.completers import ChoicesCompleter # Mark as CLI before import accelpy environ['ACCELPY_CLI'] = 'True' from accelpy import __version__ as accelpy_version from accelpy._host import _iter_hosts_names from accelpy._common import warn # List existing hosts and eventually generate "init" warning names = tuple(_iter_hosts_names()) names_completer = ChoicesCompleter(names) if not names and not environ.get('ACCELPY_GENERATE_CLI_DOC'): epilog = warn('No host configuration found, run "accelpy init" first.') else: epilog = None # Parser: "accelpy" parser = ArgumentParser(prog='accelpy', description=f'Accelpy {accelpy_version}.', epilog=epilog) sub_parsers = parser.add_subparsers( dest='action', title='Commands', help='accelpy commands', description='accelpy must perform one of the following commands:') # Parser: "accelpy init" description = 'Create a new configuration.' action = sub_parsers.add_parser('init', help=description, description=description) action.add_argument('--name', '-n', help='Name of the configuration to create, if not ' 'specified a random name is generated. The ' 'generated name is returned as command output.') action.add_argument( '--application', '-a', help='Application in format ' '"product_id:version" (or "product_id" for latest version) or ' 'path to a local application definition file.' ).completer = _application_completer action.add_argument('--provider', '-p', help='Provider name.').completer = _provider_completer action.add_argument( '--user_config', '-c', help='Extra user configuration directory. Always also use the ' '"~./accelize" directory.') name_help = 'Configuration name to use.' # Parser: "accelpy plan" description = 'Plan the host infrastructure creation and show details.' action = sub_parsers.add_parser('plan', help=description, description=description, epilog=epilog) action.add_argument('--name', '-n', help=name_help).completer = names_completer # Parser: "accelpy apply" description = 'Create the host infrastructure.' action = sub_parsers.add_parser('apply', help=description, description=description, epilog=epilog) action.add_argument('--name', '-n', help=name_help).completer = names_completer action.add_argument('--quiet', '-q', action='store_true', help='If specified, hide outputs.') # Parser: "accelpy build" description = 'Create a virtual machine image of the configured host.' action = sub_parsers.add_parser('build', help=description, description=description, epilog=epilog) action.add_argument('--name', '-n', help=name_help).completer = names_completer action.add_argument( '--update_application', '-u', action='store_true', help='If applicable, update the application definition Yaml file to ' 'use this image as host base for the selected provider. Warning, ' 'this will reset any yaml file formatting and comments.') action.add_argument('--quiet', '-q', action='store_true', help='If specified, hide outputs.') # Parser: "accelpy destroy" description = 'Destroy the host infrastructure.' action = sub_parsers.add_parser('destroy', help=description, description=description, epilog=epilog) action.add_argument('--name', '-n', help=name_help).completer = names_completer action.add_argument('--quiet', '-q', action='store_true', help='If specified, hide outputs.') action.add_argument('--delete', '-d', action='store_true', help='Delete configuration after command completion.') # Parser: "accelpy ssh_private_key" description = 'Print the host SSH private key path.' action = sub_parsers.add_parser('ssh_private_key', help=description, description=description, epilog=epilog) action.add_argument('--name', '-n', help=name_help).completer = names_completer # Parser: "accelpy ssh_user" description = 'Print the name of the user to use to connect with SSH' action = sub_parsers.add_parser('ssh_user', help=description, description=description, epilog=epilog) action.add_argument('--name', '-n', help=name_help).completer = names_completer # Parser: "accelpy private_ip" description = 'Print the private IP address.' action = sub_parsers.add_parser('private_ip', help=description, description=description, epilog=epilog) action.add_argument('--name', '-n', help=name_help).completer = names_completer # Parser: "accelpy public_ip" description = 'Print the public IP address.' action = sub_parsers.add_parser('public_ip', help=description, description=description, epilog=epilog) action.add_argument('--name', '-n', help=name_help).completer = names_completer # Parser: "accelpy list" description = 'List available host configurations.' sub_parsers.add_parser('list', help=description, description=description) # Parser: "accelpy lint" description = 'lint an application definition file.' action = sub_parsers.add_parser('lint', help=description, description=description) action.add_argument( 'file', help='Path to YAML file to lint.').completer = _yaml_completer # Parser: "accelpy push" description = 'Push an application definition file to Accelize web service.' action = sub_parsers.add_parser('push', help=description, description=description) action.add_argument( 'file', help='Path to YAML file to push.').completer = _yaml_completer # Enable autocompletion autocomplete(parser) # Get arguments and call function args = parser.parse_args() action = args.action if not action: from accelpy._common import error parser.error(error('A command is required.')) # Disables Python warnings from warnings import filterwarnings filterwarnings("ignore") # Adds parent directory to sys.path: # Allows import of accelpy if this script is run locally from os.path import dirname, realpath import sys sys.path.insert(0, dirname(dirname(realpath(__file__)))) # Run command from accelpy.exceptions import AccelizeException try: output = globals()[f'_action_{action}'](args) if output: print(output) parser.exit() except (AccelizeException, OSError) as exception: from accelpy._common import debug, error if not debug(): message = str(exception).split('\n', 1) message[0] = error(message[0]) parser.error('\n'.join(message)) raise except KeyboardInterrupt: # pragma: no cover parser.exit(status=1, message="Interrupted by user\n")
def handle_err(exitcode, msg): warn("Error: %s (exitcode %d)" % (msg, exitcode))
def handle_err(exc): warn("Error: %s" % exc)
def warn(*args): argcomplete.warn(*args) LOGGER.warning(*args)
def print_cmd2(): argcomplete.warn('print_cmd2:') argcomplete.warn('_ARGCOMPLETE: ', os.environ['_ARGCOMPLETE']) argcomplete.warn('_ARGCOMPLETE_IFS: ', os.environ['_ARGCOMPLETE_IFS']) argcomplete.warn('COMP_LINE: ', os.environ['COMP_LINE']) argcomplete.warn('COMP_POINT: ', os.environ['COMP_POINT']) argcomplete.warn('_ARGCOMPLETE_COMP_WORDBREAKS: ', os.environ['_ARGCOMPLETE_COMP_WORDBREAKS']) argcomplete.warn('COMP_WORDBREAKS: ', os.environ['COMP_WORDBREAKS'])