| {"repo": "kxr/o-must-gather", "pull_number": 29, "instance_id": "kxr__o-must-gather-29", "issue_numbers": "", "base_commit": "3b80e3bd4ee67bce2a24b19c1341d8db5e1337e8", "patch": "diff --git a/omg/cli.py b/omg/cli.py\n--- a/omg/cli.py\n+++ b/omg/cli.py\n@@ -1,94 +1,153 @@\n-import sys, argparse\n+import click\n+\n+import subprocess\n+import os\n \n from omg import version\n from omg.cmd.use import use\n-from omg.cmd.project import project, projects\n-from omg.cmd.get_main import get_main\n+from omg.cmd.project import project, projects, list_projects\n+from omg.cmd.get_main import get_main, complete_get\n from omg.cmd.describe import describe\n-from omg.cmd.log import log\n+from omg.cmd.log import log, list_pods, list_containers\n from omg.cmd.whoami import whoami\n from omg.cmd.machine_config import machine_config\n \n-# Process the Arguments and call the respective functions\n-def main():\n- # Common parser, with shared arguments for all subcommands:\n- common = argparse.ArgumentParser(add_help=False)\n- common.add_argument(\"-n\", \"--namespace\", dest=\"namespace\")\n- common.add_argument(\"-A\", \"--all-namespaces\", dest=\"all_namespaces\",action='store_true')\n-\n- # Main Parser for sub commands\n- parser = argparse.ArgumentParser()\n- subparsers = parser.add_subparsers()\n-\n- # omg use </path/to/must-gather>\n- p_use = subparsers.add_parser('use',\n- help='Select the must-gather to use')\n- p_use.add_argument('mg_path', metavar='</must/gather/location>', type=str, nargs='?')\n- p_use.add_argument('--cwd', dest=\"cwd\", action='store_true')\n- p_use.set_defaults(func=use)\n-\n- # omg project\n- p_project = subparsers.add_parser('project', parents=[common],\n- help='Display information about the current active project and existing projects')\n- p_project.add_argument('project', nargs='?', type=str)\n- p_project.set_defaults(func=project)\n-\n- # omg projects\n- p_projects = subparsers.add_parser('projects', parents=[common],\n- help='Display information about the current active project and existing projects')\n- p_projects.set_defaults(func=projects)\n-\n- # omg get <object(s)>\n- p_get = subparsers.add_parser('get', parents=[common],\n- help='Display one or many resources')\n- p_get.add_argument('objects', nargs='*', type=str)\n- p_get.add_argument(\"-o\", \"--output\", dest=\"output\",\n- choices=['yaml', 'json', 'wide'] )\n- p_get.set_defaults(func=get_main)\n-\n- # omg describe <object(s)>\n- p_describe = subparsers.add_parser('describe', parents=[common],\n- help='This command joins many API calls together to form a detailed description of a given resource.')\n- p_describe.add_argument('object', nargs='*', type=str)\n- p_describe.set_defaults(func=describe)\n-\n- # omg log <pod>\n- p_log = subparsers.add_parser('log', aliases=['logs'], parents=[common],\n- help='Display logs')\n- p_log.add_argument('resource', type=str)\n- p_log.add_argument(\"-c\", \"--container\", dest=\"container\")\n- p_log.add_argument(\"-p\", \"--previous\", dest=\"previous\", action='store_true')\n- p_log.set_defaults(func=log)\n-\n- # omg whoami\n- p_whoami = subparsers.add_parser('whoami', parents=[common],\n- help='Display who you are')\n- p_whoami.set_defaults(func=whoami)\n-\n- # omg version\n- p_version = subparsers.add_parser('version', parents=[common],\n- help='Display omg version')\n- p_version.set_defaults(func=lambda x: print('omg version '+version+' (https://github.com/kxr/o-must-gather)'))\n-\n- # omg machine-config\n- p_mc = subparsers.add_parser('machine-config',\n- help='Explore Machine Configs')\n- p_mc.add_argument('mc_op', metavar='operation', type=str,choices=['extract', 'show', 'compare'],\n- help='Operation to be performed on the machine-config (extract/show/compare)')\n- p_mc.add_argument('mc_names', metavar='name', type=str, nargs='*',\n- help='Machine Config name (skip this to process all machine-configs')\n- p_mc.add_argument(\"--show-contents\", dest=\"show_contents\", action='store_true')\n- p_mc.set_defaults(func=machine_config)\n-\n- # process args and call the corresponding function\n- args = parser.parse_args()\n- try:\n- func = args.func\n- except AttributeError:\n- parser.error(\"too few arguments\")\n- try:\n- func(args)\n- except BrokenPipeError:\n- sys.stdout.close()\n- except KeyboardInterrupt:\n- pass\n+CONTEXT_SETTINGS = dict(help_option_names=[\"-h\", \"--help\"])\n+\n+# Namespace related options shared by a few commands\n+_global_namespace_options = [\n+ click.option(\"--namespace\", \"-n\", required=False, autocompletion=list_projects),\n+ click.option(\"--all-namespaces\", \"-A\", required=False, is_flag=True),\n+]\n+\n+\n+# Decorator lets us use namespace related options above\n+def global_namespace_options(func):\n+ for option in reversed(_global_namespace_options):\n+ func = option(func)\n+ return func\n+\n+\n+@click.group(context_settings=CONTEXT_SETTINGS)\n+def cli():\n+ pass\n+\n+\n+@cli.command(\"use\")\n+@click.argument(\"mg_path\", required=False,\n+ type=click.Path(exists=True, file_okay=False, resolve_path=True, allow_dash=False))\n+@click.option(\"--cwd\", is_flag=True)\n+def use_cmd(mg_path, cwd):\n+ \"\"\"\n+ Select the must-gather to use\n+ \"\"\"\n+ use(mg_path, cwd)\n+\n+\n+@cli.command(\"project\")\n+@click.argument(\"name\", required=False, autocompletion=list_projects)\n+def project_cmd(name):\n+ \"\"\"\n+ Display information about the current active project and existing projects\n+ \"\"\"\n+ project(name)\n+\n+\n+@cli.command(\"projects\")\n+def projects_cmd():\n+ \"\"\"\n+ Display information about the current active project and existing projects\n+ \"\"\"\n+ projects()\n+\n+\n+@cli.command(\"get\")\n+@click.argument(\"objects\", nargs=-1, autocompletion=complete_get)\n+@click.option(\"--output\", \"-o\", type=click.Choice([\"yaml\", \"json\", \"wide\"]))\n+@global_namespace_options\n+def get_cmd(objects, output, namespace, all_namespaces):\n+ \"\"\"\n+ Display one or many resources\n+ \"\"\"\n+ get_main(objects, output, namespace, all_namespaces)\n+\n+\n+@cli.command(\"describe\")\n+@click.argument(\"object\", nargs=-1)\n+@global_namespace_options\n+def describe_cmd(objects, namespace, all_namespaces):\n+ \"\"\"\n+ This command joins many API calls together to form a detailed description of a given resource.\n+ \"\"\"\n+ describe(None)\n+\n+\n+@cli.command(\"logs\")\n+@click.argument(\"resource\", autocompletion=list_pods)\n+@click.option(\"--container\", \"-c\", autocompletion=list_containers)\n+@click.option(\"--previous\", \"-p\", is_flag=True)\n+@global_namespace_options # TODO: Only support -n\n+def logs_cmd(resource, container, previous, namespace, all_namespaces):\n+ \"\"\"\n+ Display logs\n+ \"\"\"\n+ log(resource, container, previous, namespace, False)\n+\n+\n+@cli.command(\"whoami\")\n+def whoami_cmd():\n+ \"\"\"\n+ Display who you are\n+ \"\"\"\n+ whoami(None)\n+\n+\n+@cli.command\n+def version():\n+ \"\"\"\n+ Display omg version\n+ \"\"\"\n+ print('omg version ' + version + ' (https://github.com/kxr/o-must-gather)')\n+\n+\n+@cli.command(\"completion\")\n+@click.argument(\"shell\", nargs=1, type=click.Choice([\"bash\", \"zsh\", \"fish\"]))\n+def completion(shell):\n+ \"\"\"\n+ Output shell completion code for bash, zsh, or fish.\n+\n+ \\b\n+ For example:\n+ # omg completion bash > omg-completion.sh\n+ # source omg-completion.sh\n+ \"\"\"\n+ newenv = os.environ.copy()\n+ newenv[\"_OMG_COMPLETE\"] = \"source_%s\" % shell\n+ subprocess.run(\"omg\", env=newenv)\n+\n+\n+@cli.group(\"machine-config\")\n+def mc_cmd():\n+ \"\"\"\n+ Explore Machine Configs\n+ \"\"\"\n+ pass\n+\n+\n+@mc_cmd.command(\"extract\")\n+@click.argument(\"mc_names\", nargs=-1)\n+def extract_mc_cmd(mc_names):\n+ \"\"\"\n+ Extract a Machine Config\n+ \"\"\"\n+ machine_config(\"extract\", mc_names, False)\n+\n+\n+@mc_cmd.command(\"compare\")\n+@click.argument(\"mc_names\", nargs=-1)\n+@click.option(\"--show-contents\", is_flag=True)\n+def compare_mc_cmd(mc_names, show_contents):\n+ \"\"\"\n+ Compare Machine Configs\n+ \"\"\"\n+ machine_config(\"show\", mc_names, show_contents)\ndiff --git a/omg/cmd/get/parse.py b/omg/cmd/get/parse.py\nnew file mode 100644\n--- /dev/null\n+++ b/omg/cmd/get/parse.py\n@@ -0,0 +1,241 @@\n+import enum\n+\n+from omg.common.resource_map import map_res, map\n+\n+\n+ALL_RESOURCES = \"_all\"\n+ALL_TYPES = ['pod', 'rc', 'svc', 'ds', 'deployment', 'rs', 'statefulset', 'hpa', 'job', 'cronjob', 'dc', 'bc', 'build',\n+ 'is']\n+\n+\n+class ResourceMap:\n+ \"\"\"\n+ Wrapper around a dictionary that contains type->set<Resource>.\n+ \"\"\"\n+ def __init__(self):\n+ self.dict = {}\n+ self.__res_generator = None\n+\n+ def add_type(self, resource_type):\n+ \"\"\"\n+ Add a resource type (e.g. pod, service, route) to inner dict.\n+ \"\"\"\n+ if resource_type not in self.dict:\n+ self.dict[resource_type] = set()\n+\n+ def add_resource(self, resource_type, resource_name):\n+ \"\"\"\n+ Add resource name of given type to inner dict.\n+ \"\"\"\n+ self.add_type(resource_type)\n+ self.dict[resource_type].add(resource_name)\n+\n+ def has_type(self, resource_type):\n+ \"\"\"\n+ Check if inner dict knows about given type.\n+ \"\"\"\n+ return resource_type in self.dict\n+\n+ def get_types(self):\n+ \"\"\"\n+ Get a list of resource types.\n+ \"\"\"\n+ return self.dict.keys()\n+\n+ def get_resources(self, resource_type):\n+ \"\"\"\n+ Get a set of resource names for given type or empty set if type is not known.\n+ \"\"\"\n+ return self.dict.get(resource_type) or set()\n+\n+ def generator(self):\n+ \"\"\"\n+ Yields all resources types -> set<Resource>.\n+ \"\"\"\n+ for r_type in self.get_types():\n+ yield r_type, self.get_resources(r_type)\n+\n+ def __contains__(self, item):\n+ \"\"\"\n+ Check if given resource type exists.\n+ \"\"\"\n+ res = map_res(item)\n+ if res is not None:\n+ return self.has_type(res['type'])\n+\n+ def __iter__(self):\n+ \"\"\"\n+ Initialize iterator from ResourceMap generator\n+ \"\"\"\n+ self.__res_generator = self.generator()\n+ return self\n+\n+ def __next__(self):\n+ \"\"\"\n+ Pull next item from ResourceMap generator.\n+ \"\"\"\n+ if self.__res_generator is None:\n+ self.__iter__()\n+ r_type, r_name = next(self.__res_generator)\n+ return r_type, r_name\n+\n+ def __len__(self):\n+ \"\"\"\n+ Length of ResourceMap.\n+ \"\"\"\n+ return len(self.dict)\n+\n+\n+class Method(enum.Enum):\n+ \"\"\"\n+ Enumeration of various methods `omg get` can be called.\n+ \"\"\"\n+ UNKNOWN = 0 # \u00af\\_(\u30c4)_/\u00af\n+ SINGLE_TYPE = 1 # e.g. omg get pod/mypod\n+ MULTI_TYPE_SINGLE_RESOURCE = 2 # e.g. omg get svc,ep,ds dns-default\n+ MULTI_TYPE_MULTI_RESOURCE = 3 # e.g. omg get pod mypod myotherpod\n+ ALL = 4 # e.g. oc get all\n+\n+\n+class ResourceParseError(Exception):\n+ \"\"\"\n+ Error raised during parsing of `oc get` args.\n+ \"\"\"\n+ pass\n+\n+\n+def _parse_slash(arg):\n+ \"\"\"\n+ Parses out a single word containing a slash, validates the type is known and returns: type name, resource name\n+ \"\"\"\n+ try:\n+ o_split = arg.split('/')\n+ r_type = o_split[0]\n+ r_name = o_split[1]\n+ checked_type = map_res(r_type)\n+ if r_type is None:\n+ raise ResourceParseError(\"[ERROR] Invalid object type: \" + r_type)\n+ return checked_type['type'], r_name\n+ except Exception:\n+ raise ResourceParseError(\"[ERROR] Invalid object type: \" + arg)\n+\n+\n+def parse_get_resources(objects: tuple) -> (Method, ResourceMap):\n+ \"\"\"\n+ Takes a tuple (examples below) of arguments passed to `omg get ...` and parses it into\n+ manageable class. Returns a tuple containing the Method enum and resource mapping.\n+\n+ Raises ResourceParseError if it runs into any issues.\n+\n+ Example object contents:\n+ ('pod', 'httpd')\n+ ('pods', 'httpd1', 'httpd2')\n+ ('dc/httpd', 'pod/httpd1')\n+ ('routes')\n+ ('pod,svc')\n+ \"\"\"\n+ method = Method.UNKNOWN\n+ resources = ResourceMap()\n+\n+ if len(objects) == 0:\n+ # We've nothing to parse right now.\n+ return method, resources\n+\n+ last_object = []\n+\n+ # Check first arg to see if we're doing multiple or single resources\n+ first = objects[0]\n+ if '/' in first:\n+ method = Method.MULTI_TYPE_MULTI_RESOURCE\n+ elif ',' in first:\n+ method = Method.MULTI_TYPE_SINGLE_RESOURCE\n+ else:\n+ method = Method.SINGLE_TYPE\n+\n+ for o in objects:\n+ if '/' in o:\n+ r_type, r_name = _parse_slash(o)\n+ resources.add_resource(r_type, r_name)\n+ elif ',' in o:\n+ pass\n+ else:\n+ pass\n+\n+ for o in objects:\n+ # Case where we have a '/'\n+ # e.g omg get pod/httpd\n+ if '/' in o:\n+ method = Method.MULTI_TYPE_MULTI_RESOURCE\n+ if not last_object:\n+ pre = o.split('/')[0]\n+ r_type = map_res(pre)['type']\n+ r_name = o.split('/')[1]\n+ # If its a valid resource type, append it to objects\n+ if r_type is not None:\n+ resources.add_resource(r_type, r_name)\n+ else:\n+ raise ResourceParseError(\"[ERROR] Invalid object type: \" + pre)\n+\n+ # Convert 'all' to list of resource types in a specific order\n+ elif o == 'all':\n+ for rt in ALL_TYPES:\n+ # TODO Simplify to just: last_object.append(rt)?\n+ check_rt = map_res(rt)\n+ if check_rt is None:\n+ raise ResourceParseError(\"[ERROR] Invalid object type: \" + rt)\n+ else:\n+ last_object.append(check_rt['type'])\n+\n+ # Case where we have a ',' e.g `get dc,svc,pod httpd`\n+ # These all will be resource_types, not names,\n+ # resource_name will come it next iteration (if any)\n+ elif ',' in o:\n+ method = Method.MULTI_TYPE_SINGLE_RESOURCE\n+ if not last_object:\n+ r_types = o.split(',')\n+ # if all is present, we will replace it with all_types\n+ if 'all' in r_types:\n+ ai = r_types.index('all')\n+ r_types.remove('all')\n+ r_types[ai:ai] = ALL_TYPES\n+ for rt in r_types:\n+ check_rt = map_res(rt)\n+ if check_rt is None:\n+ raise ResourceParseError(\"[ERROR] Invalid object type: \" + rt)\n+ else:\n+ last_object.append(check_rt['type'])\n+ else:\n+ # last_object was set, meaning this should be object name\n+ raise ResourceParseError(\"[ERROR] Invalid resources to get: \" + objects)\n+\n+ # Simple word (without , or /)\n+ # If last_object was not set, means this is a resource_type\n+ elif not last_object:\n+ method = Method.SINGLE_TYPE\n+ check_rt = map_res(o)\n+ if check_rt is not None:\n+ last_object = [check_rt['type']]\n+ else:\n+ raise ResourceParseError(\"[ERROR] Invalid resource type to get: \" + o)\n+ # Simple word (without , or /)\n+ # If the last_object was set, means we got resource_type last time,\n+ # and this should be a resource_name.\n+ elif last_object:\n+ method = Method.SINGLE_TYPE\n+ for rt in last_object:\n+ resources.add_resource(rt, o)\n+ else:\n+ # Should never happen\n+ raise ResourceParseError(\"[ERROR] Invalid resources to get: \" + o)\n+\n+ if last_object:\n+ for rt in last_object:\n+ check_rt = map_res(rt)\n+ if check_rt is None:\n+ continue\n+ r_type = check_rt['type']\n+ if not resources.has_type(r_type) or len(resources.get_resources(r_type)) == 0:\n+ method = Method.ALL\n+ resources.add_resource(r_type, ALL_RESOURCES)\n+\n+ return method, resources\ndiff --git a/omg/cmd/get_main.py b/omg/cmd/get_main.py\n--- a/omg/cmd/get_main.py\n+++ b/omg/cmd/get_main.py\n@@ -1,6 +1,61 @@\n-import sys, yaml, json\n+import yaml\n+import json\n+\n+from click import Context\n+\n from omg.common.config import Config\n-from omg.common.resource_map import map_res\n+from omg.common.resource_map import map_res, map\n+from omg.cmd.get import parse\n+\n+\n+def complete_get(ctx: Context, args, incomplete):\n+ \"\"\"\n+ Pull out objects args from Click context and return completions.\n+ \"\"\"\n+ c = Config()\n+ objects = ctx.params.get(\"objects\")\n+ return generate_completions(c, objects, incomplete)\n+\n+\n+def generate_completions(config, objects, incomplete):\n+ \"\"\"\n+ Given a config, tuple of args, and incomplete input from user, generate a list of completions.\n+\n+ This function should not print stack traces or do any error logging (without turning it on explicitly)\n+ since shell completion should be transparent to user.\n+ \"\"\"\n+ try:\n+ get_method, resource_list = parse.parse_get_resources(objects)\n+ except Exception as e:\n+ # Swallow any error since we don't want to spam terminal during autcompletion.\n+ print(e)\n+ return []\n+\n+ # We're completing something like `oc get pod/name`.\n+ if \"/\" in incomplete:\n+ restypein = incomplete.split(\"/\")[0]\n+ resname = incomplete.split(\"/\")[1]\n+ restype = map_res(restypein)\n+ resources = restype['get_func']('items', config.project, '_all', restype['yaml_loc'], restype['need_ns'])\n+ return [restypein + \"/\" + r['res']['metadata']['name'] for r in resources if r['res']['metadata']['name'].startswith(resname)]\n+\n+ if len(resource_list) == 0 and \",\" in incomplete:\n+ # This is a NOP like oc\n+ return []\n+ elif get_method == parse.Method.SINGLE_TYPE or \\\n+ get_method == parse.Method.ALL:\n+ # Autocomplete resource names based on the type: oc get pod mypod1 mypod2\n+ restypein, _ = next(resource_list)\n+ restype = map_res(restypein)\n+ resources = restype['get_func']('items', config.project, '_all', restype['yaml_loc'], restype['need_ns'])\n+ return [r['res']['metadata']['name'] for r in resources if\n+ r['res']['metadata']['name'].startswith(incomplete)]\n+ else:\n+ # Return completions for resource types\n+ # TODO: Include aliases\n+ fullset = set(parse.ALL_TYPES + [t['type'] for t in map])\n+ return [t for t in fullset if t.startswith(incomplete)]\n+\n \n # The high level function that gets called for any \"get\" command\n # This function processes/identifies the objects, they can be in various formats e.g:\n@@ -9,124 +64,31 @@\n # get dc/httpd pod/httpd1\n # get routes\n # get pod,svc\n-# We get all these args (space separated) in the array a.objects\n+# We get all these args (space separated) in the array objects\n # We'll process them and normalize them in a python dict (objects)\n # Once we have one of more object to get,\n # and call the respective get function\n # (this function is looked up from common/resource_map)\n-def get_main(a):\n+def get_main(objects, output, namespace, all_namespaces):\n # a = args passed from cli\n # Check if -A/--all-namespaces is set\n # else, Set the namespace\n # -n/--namespace takes precedence over current project \n- if a.all_namespaces is True:\n+ if all_namespaces is True:\n ns = '_all'\n else:\n- if a.namespace is not None:\n- ns = a.namespace\n+ if namespace is not None:\n+ ns = namespace\n elif Config().project is not None:\n ns = Config().project\n else:\n ns = None\n \n- # We collect the resources types/names in this dict\n- # e.g for `get pod httpd1 httpd2` this will look like:\n- # objects = { 'pod': ['httpd1', 'httpd2'] }\n- # e.g, for `get pod,svc` this will look like:\n- # objects = { 'pod': ['_all'], 'service': ['_all'] }\n- objects = {}\n-\n- last_object = []\n- all_types = ['pod', 'rc', 'svc', 'ds', 'deployment', 'rs', 'statefulset', 'hpa', 'job', 'cronjob', 'dc', 'bc', 'build', 'is']\n- for o in a.objects:\n- # Case where we have a '/'\n- # e.g omg get pod/httpd\n- if '/' in o:\n- if not last_object:\n- pre = o.split('/')[0]\n- r_type = map_res(pre)['type']\n- r_name = o.split('/')[1]\n- # If its a valid resource type, apppend it to objects\n- if r_type is not None:\n- if r_type in objects:\n- objects[r_type].append(r_name)\n- else:\n- objects[r_type] = [r_name]\n- else:\n- print(\"[ERROR] Invalid object type: \",pre)\n- sys.exit(1)\n- else:\n- # last_object was set, meaning this should be object name\n- print(\"[ERROR] There is no need to specify a resource type as a separate argument when passing arguments in resource/name form\")\n- sys.exit(1)\n- \n- # Convert 'all' to list of resource types in a specific order\n- elif o == 'all':\n- for rt in all_types:\n- check_rt = map_res(rt)\n- if check_rt is None:\n- print(\"[ERROR] Invalid object type: \",rt)\n- sys.exit(1)\n- else:\n- last_object.append(check_rt['type'])\n-\n- # Case where we have a ',' e.g `get dc,svc,pod httpd`\n- # These all will be resource_types, not names,\n- # resource_name will come it next iteration (if any)\n- elif ',' in o:\n- if not last_object:\n- r_types = o.split(',')\n- # if all is present, we will replace it with all_types\n- if 'all' in r_types:\n- ai = r_types.index('all')\n- r_types.remove('all')\n- r_types[ai:ai] = all_types\n- for rt in r_types:\n- check_rt = map_res(rt)\n- if check_rt is None:\n- print(\"[ERROR] Invalid object type: \",rt)\n- sys.exit(1)\n- else:\n- last_object.append(check_rt['type'])\n- else:\n- # last_object was set, meaning this should be object name\n- print(\"[ERROR] Invalid resources to get: \", a.objects)\n- sys.exit(1)\n-\n- # Simple word (without , or /)\n- # If last_object was not set, means this is a resource_type\n- elif not last_object:\n- check_rt = map_res(o)\n- if check_rt is not None:\n- last_object = [ check_rt['type'] ]\n- else:\n- print(\"[ERROR] Invalid resource type to get: \", o)\n- # Simple word (without , or /)\n- # If the last_object was set, means we got resource_type last time,\n- # and this should be a resource_name. \n- elif last_object:\n- for rt in last_object:\n- if rt in objects:\n- objects[rt].append(o)\n- else:\n- objects[rt] = [o]\n- #last_object = []\n- else:\n- # Should never happen\n- print(\"[ERROR] Invalid resources to get: \", o)\n- sys.exit(1)\n- # If after going through all the args, we have last_object set\n- # and there was no entry in objects[] for this, it\n- # means we didn't get a resource_name for this resource_type.\n- # i.e, we need to get all names\n- if last_object:\n- for rt in last_object:\n- check_rt = map_res(rt)\n- if check_rt['type'] not in objects or len(objects[check_rt['type']]) == 0:\n- objects[check_rt['type']] = ['_all']\n-\n- # Debug\n- # print(objects)\n+ try:\n+ get_method, resource_list = parse.parse_get_resources(objects)\n+ except parse.ResourceParseError as e:\n+ print(e)\n+ return\n \n # Object based routing\n # i.e, call the get function for all the requested types\n@@ -134,47 +96,50 @@ def get_main(a):\n \n # If printing multiple objects, add a blank line between each\n mult_objs_blank_line = False\n- for rt in objects.keys():\n- rt_info = map_res(rt)\n+\n+ for r_type, res_set in resource_list:\n+ rt_info = map_res(r_type)\n get_func = rt_info['get_func']\n getout_func = rt_info['getout_func']\n yaml_loc = rt_info['yaml_loc']\n need_ns = rt_info['need_ns']\n \n # Call the get function to get the resoruces\n- res = get_func(rt, ns, objects[rt], yaml_loc, need_ns)\n+ res = get_func(r_type, ns, res_set, yaml_loc, need_ns)\n \n # Error out if no objects/resources were collected\n- if len(res) == 0 and len(objects) == 1:\n- print('No resources found for type \"%s\" in %s namespace'%(rt,ns))\n+ if len(res) == 0 and get_method is not parse.Method.ALL:\n+ print('No resources found for type \"%s\" in %s namespace' % (r_type, ns))\n elif len(res) > 0:\n # If printing multiple objects, add a blank line between each\n- if mult_objs_blank_line == True:\n+ if mult_objs_blank_line:\n print('')\n # Yaml dump if -o yaml\n- if a.output == 'yaml':\n+ if output == 'yaml':\n if len(res) == 1:\n print(yaml.dump(res[0]['res']))\n elif len(res) > 1:\n print(yaml.dump({'apiVersion':'v1','items':[cp['res']for cp in res]}))\n # Json dump if -o json\n- elif a.output == 'json':\n+ elif output == 'json':\n if len(res) == 1:\n print(json.dumps(res[0]['res'],indent=4))\n elif len(res) > 1:\n print(json.dumps({'apiVersion':'v1','items':[cp['res']for cp in res]},indent=4))\n # Call the respective output function if -o is not set or -o wide\n- elif a.output in [None, 'wide']:\n+ elif output in [None, 'wide']:\n # If we displaying more than one resource_type,\n # we need to display resource_type with the name (type/name)\n- if len(objects) > 1:\n+\n+ if len(resource_list) > 1:\n show_type = True\n else:\n show_type = False\n- getout_func(rt, ns, res, a.output, show_type)\n+ getout_func(r_type, ns, res, output, show_type)\n # Flag to print multiple objects\n- if mult_objs_blank_line == False:\n+ if not mult_objs_blank_line:\n mult_objs_blank_line = True\n+\n # Error out once if multiple objects/resources requested and none collected\n- if mult_objs_blank_line == False and len(objects) > 1:\n- print('No resources found in %s namespace'%(ns))\n+ if not mult_objs_blank_line and get_method == parse.Method.ALL:\n+ print('No resources found in %s namespace' % ns)\ndiff --git a/omg/cmd/log.py b/omg/cmd/log.py\n--- a/omg/cmd/log.py\n+++ b/omg/cmd/log.py\n@@ -1,14 +1,45 @@\n import os, sys\n \n+from click import Context\n+\n from omg.common.config import Config\n \n-def log(a):\n- if a.all_namespaces is True:\n+\n+def list_pods(ctx: Context, args, incomplete):\n+ \"\"\"\n+ Callback for pod name (within an ns) autocompletion\n+ :return: List of matching pod names or empty list.\n+ \"\"\"\n+ # Get current project and filter Pods\n+ c = Config()\n+ ns = ctx.params.get(\"namespace\") or c.project\n+ pod_listing = os.listdir(os.path.join(c.path, \"namespaces\", ns, \"pods\"))\n+ suggestions = [pod for pod in pod_listing if incomplete in pod]\n+ return suggestions\n+\n+\n+def list_containers(ctx: Context, args, incomplete):\n+ \"\"\"\n+ Callback for container name (within a pod and ns) autocompletion\n+ :return: List of matching container names or empty list\n+ \"\"\"\n+ c = Config()\n+ if len(ctx.args) != 1: # If there's no pod specified yet, can't autocomplete a container name\n+ return []\n+ ns = ctx.params.get(\"namespace\") or c.project\n+ pod = ctx.args[0]\n+ container_listing = os.listdir(os.path.join(c.path, \"namespaces\", ns, \"pods\", pod))\n+ suggestions = [c for c in container_listing if incomplete in c and not c.endswith(\".yaml\")] # skip .yaml files\n+ return suggestions\n+\n+\n+def log(resource, container, previous, namespace, all_namespaces):\n+ if all_namespaces is True:\n print('[ERROR] All Namespaces is not supported with log')\n sys.exit(1)\n else:\n- if a.namespace is not None:\n- ns = a.namespace\n+ if namespace is not None:\n+ ns = namespace\n elif Config().project is not None:\n ns = Config().project\n else:\n@@ -24,14 +55,14 @@ def log(a):\n sys.exit(1)\n \n # pod\n- if '/' in a.resource:\n- r_type = a.resource.split('/')[0]\n- pod = a.resource.split('/')[1]\n+ if '/' in resource:\n+ r_type = resource.split('/')[0]\n+ pod = resource.split('/')[1]\n if r_type not in ['pod','pods']:\n print('[ERROR] Can not print logs of type:',r_type)\n sys.exit(1)\n else:\n- pod = a.resource\n+ pod = resource\n \n # check if top pod directory exits\n pod_dir = os.path.join(ns_dir, 'pods', pod)\n@@ -42,22 +73,22 @@ def log(a):\n # Containers are dirs in pod_dir\n containers = [ c for c in os.listdir(pod_dir) \n if os.path.isdir(os.path.join(pod_dir,c))]\n- # If we have > 1 containers and -c/--container is not speficied, error out\n+ # If we have > 1 containers and -c/--container is not specified, error out\n if len(containers) == 0:\n- print('[ERROR] No container directory not found in pod direcotry:', pod_dir)\n+ print('[ERROR] No container directory not found in pod directory:', pod_dir)\n sys.exit(1)\n elif len(containers) > 1:\n- if a.container is None:\n+ if container is None:\n print('[ERROR] This pod has more than one containers:')\n print(' ', str(containers))\n print(' Use -c/--container to specify the container')\n sys.exit(1)\n else:\n- con_to_log = a.container\n+ con_to_log = container\n else: # len(containers) == 1\n con_to_log = containers[0]\n \n- if a.previous:\n+ if previous:\n log_f = 'previous.log'\n else:\n log_f = 'current.log'\ndiff --git a/omg/cmd/machine_config.py b/omg/cmd/machine_config.py\n--- a/omg/cmd/machine_config.py\n+++ b/omg/cmd/machine_config.py\n@@ -278,14 +278,14 @@ def mc_diff(d1, d2, path=[]):\n \n mc_diff(mc1,mc2)\n \n-def machine_config(a):\n- if a.mc_op == 'extract':\n- if len(a.mc_names) <= 0:\n+def machine_config(mc_op, mc_names, show_contents):\n+ if mc_op == 'extract':\n+ if len(mc_names) <= 0:\n extract('_all')\n else:\n- extract(a.mc_names)\n- elif a.mc_op == 'compare':\n- if len(a.mc_names) == 2:\n- compare(a.mc_names, show_contents=a.show_contents)\n+ extract(mc_names)\n+ elif mc_op == 'compare':\n+ if len(mc_names) == 2:\n+ compare(mc_names, show_contents=show_contents)\n else:\n print('[ERROR] Provide two machine-configs to compare')\ndiff --git a/omg/cmd/project.py b/omg/cmd/project.py\n--- a/omg/cmd/project.py\n+++ b/omg/cmd/project.py\n@@ -2,10 +2,23 @@\n from omg.common.config import Config\n \n \n-def project(a):\n+def list_projects(ctx, args, incomplete):\n+ \"\"\"\n+ Callback for project name autocompletion\n+ :return: List of matching namespace names or empty list.\n+ \"\"\"\n+ c = Config()\n+ if incomplete is not None:\n+ ns_listing = os.listdir(os.path.join(c.path, \"namespaces\"))\n+ suggestions = [ns for ns in ns_listing if incomplete in ns]\n+ return suggestions\n+ return []\n+\n+\n+def project(name):\n c = Config()\n ns_dir = os.path.join(c.path,'namespaces')\n- if a is None or a.project is None:\n+ if name is None:\n # print current project\n if c.project is None:\n print('No project selected')\n@@ -13,17 +26,17 @@ def project(a):\n print('Using project \"%s\" on must-gather \"%s\"' % (c.project,c.path))\n else:\n # Set current project\n- if os.path.isdir(os.path.join(ns_dir, a.project)):\n- if a.project == c.project:\n+ if os.path.isdir(os.path.join(ns_dir, name)):\n+ if name == c.project:\n print('Already on project \"%s\" on server \"%s\"' % (c.project,c.path))\n else:\n- c.save(project=a.project)\n+ c.save(project=name)\n print('Now using project \"%s\" on must-gather \"%s\"' % (c.project,c.path))\n else:\n- print('[ERROR] Project %s not found in %s'%(a.project,ns_dir))\n+ print('[ERROR] Project %s not found in %s'%(name,ns_dir))\n \n \n-def projects(a):\n+def projects():\n c = Config()\n ns_dir = os.path.join(c.path,'namespaces')\n projects = [ p for p in os.listdir(ns_dir) \ndiff --git a/omg/cmd/use.py b/omg/cmd/use.py\n--- a/omg/cmd/use.py\n+++ b/omg/cmd/use.py\n@@ -1,9 +1,10 @@\n-import sys, os\n+import os\n from omg.common.config import Config\n \n-def use(a):\n- if a.mg_path is None:\n- if a.cwd == True:\n+\n+def use(mg_path, cwd):\n+ if mg_path is None:\n+ if cwd == True:\n # If --cwd is set we will blidly assume current working directory\n # to be the must-gather to use\n c = Config(fail_if_no_path=False)\n@@ -32,7 +33,7 @@ def use(a):\n print('[ERROR] Unable to determine cluster API URL and Platform.')\n else:\n c = Config(fail_if_no_path=False)\n- p = a.mg_path\n+ p = mg_path\n # We traverse up to 3 levels to find the must-gather\n # At each leve if it has only one dir and we check inside it\n # When we see see the dir /namespaces and /cluster-scoped-resources, we assume it\n@@ -52,4 +53,3 @@ def use(a):\n else:\n print('[ERROR] Invalid path. Please give path to the extracted must-gather')\n break\n- \ndiff --git a/setup.py b/setup.py\nold mode 100644\nnew mode 100755\n--- a/setup.py\n+++ b/setup.py\n@@ -4,7 +4,7 @@\n from setuptools import find_packages, setup\n import omg\n \n-dependencies = ['tabulate', 'pyyaml', 'python-dateutil', 'cryptography>=2.5' ]\n+dependencies = ['tabulate', 'pyyaml', 'python-dateutil', 'cryptography>=2.5', 'click==7.1.2']\n \n setup(\n name='o-must-gather',\n@@ -15,14 +15,14 @@\n author_email='khizernaeem@gmail.com',\n description='oc like tool that works with must-gather rather than OpenShift API',\n long_description=__doc__,\n- packages=find_packages(exclude=['tests']),\n+ packages=find_packages(),\n include_package_data=True,\n zip_safe=False,\n platforms='any',\n install_requires=dependencies,\n entry_points={\n 'console_scripts': [\n- 'omg = omg.cli:main',\n+ 'omg = omg.cli:cli',\n ],\n },\n classifiers=[\n", "test_patch": "diff --git a/omg/test/test_get_completion.py b/omg/test/test_get_completion.py\nnew file mode 100644\n--- /dev/null\n+++ b/omg/test/test_get_completion.py\n@@ -0,0 +1,34 @@\n+from omg.cmd.get_main import generate_completions\n+\n+import unittest\n+\n+\n+class TestGetCompletion(unittest.TestCase):\n+ def setUp(self):\n+ pass\n+\n+ def tearDown(self):\n+ pass\n+\n+ def testTypeCompletion(self):\n+ expected = [\"service\"]\n+ results = generate_completions(None, (), \"servi\")\n+ self.assertEqual(expected, results)\n+\n+ def testNoTypeCompletion(self):\n+ expected = []\n+ results = generate_completions(None, (), \"asdf\")\n+ self.assertEqual(expected, results)\n+\n+ def testMultiTypeComma(self):\n+ expected = []\n+ results = generate_completions(None, (), \"pods,services,endpoi\")\n+ self.assertEqual(expected, results)\n+\n+ def testNoRaise(self):\n+ expected = []\n+ results = generate_completions(None, None, None)\n+ self.assertEqual(expected, results)\n+\n+ results = generate_completions(None, (\"12312323\",), \"1231231231231\") # Bogus input\n+ self.assertEqual(expected, results)\ndiff --git a/omg/test/test_get_parse.py b/omg/test/test_get_parse.py\nnew file mode 100644\n--- /dev/null\n+++ b/omg/test/test_get_parse.py\n@@ -0,0 +1,103 @@\n+import unittest\n+\n+from omg.cmd.get import parse\n+\n+\n+class TestGetParse(unittest.TestCase):\n+ def setUp(self):\n+ pass\n+\n+ def tearDown(self):\n+ pass\n+\n+ def testAllTypes(self):\n+ args = (\"all\",)\n+ _, rl = parse.parse_get_resources(args)\n+\n+ for expected_type in parse.ALL_TYPES:\n+ self.assertIn(expected_type, rl)\n+\n+ for _, n in rl:\n+ self.assertEqual({parse.ALL_RESOURCES}, n)\n+\n+ def testAllResource(self):\n+ args = (\"pods\",)\n+ _, rl = parse.parse_get_resources(args)\n+ r_type, r_name = next(rl)\n+ self.assertEqual(1, len(rl))\n+ self.assertEqual(\"pod\", r_type)\n+ self.assertEqual({parse.ALL_RESOURCES}, r_name)\n+\n+ def testSingleResource(self):\n+ args = (\"pod\", \"mypod\")\n+ _, rl = parse.parse_get_resources(args)\n+ r_type, r_name = next(rl)\n+ self.assertEqual(1, len(rl))\n+ self.assertEqual(\"pod\", r_type)\n+ self.assertEqual({\"mypod\"}, r_name)\n+\n+ def testSingleTypeMultiResource(self):\n+ args = (\"pod\", \"mypod\", \"myotherpod\")\n+ _, rl = parse.parse_get_resources(args)\n+ r_type, r_name = next(rl)\n+ self.assertEqual(1, len(rl))\n+ self.assertEqual(\"pod\", r_type)\n+ self.assertEqual({\"mypod\", \"myotherpod\"}, r_name)\n+\n+ def testMultipleResources(self):\n+ expected_args = [\"endpoint\", \"service\", \"pod\"]\n+ args = (\"pods,svc,endpoints\",)\n+ _, rl = parse.parse_get_resources(args)\n+ for r_type, r_name in rl:\n+ expected = expected_args.pop()\n+ self.assertEqual(expected, r_type)\n+ self.assertEqual({parse.ALL_RESOURCES}, r_name)\n+\n+ def testMultipleResourcesOneName(self):\n+ expected_args = [\"endpoint\", \"service\"]\n+ args = (\"svc,endpoints\", \"dns-default\")\n+ _, rl = parse.parse_get_resources(args)\n+ for r_type, r_name in rl:\n+ expected = expected_args.pop()\n+ self.assertEqual(expected, r_type)\n+ self.assertEqual({\"dns-default\"}, r_name)\n+\n+ def testSingleSlash(self):\n+ args = (\"pods/mypod\",)\n+ _, rl = parse.parse_get_resources(args)\n+ r_type, r_name = next(rl)\n+ self.assertEqual(1, len(rl))\n+ self.assertEqual(\"pod\", r_type)\n+ self.assertEqual({\"mypod\"}, r_name)\n+\n+ def testMultiSlash(self):\n+ args = (\"pods/mypod\", \"svc/default\")\n+ _, rl = parse.parse_get_resources(args)\n+ self.assertEqual(2, len(rl))\n+\n+ r_type, r_name = next(rl)\n+ self.assertEqual(\"pod\", r_type)\n+ self.assertEqual({\"mypod\"}, r_name)\n+\n+ r_type, r_name = next(rl)\n+ self.assertEqual(\"service\", r_type)\n+ self.assertEqual({\"default\"}, r_name)\n+\n+ def testInvalidType(self):\n+ args = (\"podzzzz\",)\n+ with self.assertRaises(parse.ResourceParseError):\n+ parse.parse_get_resources(args)\n+\n+ def testInvalidMultiTypeComma(self):\n+ args = (\"pods,svc,asdf\",)\n+ with self.assertRaises(parse.ResourceParseError):\n+ parse.parse_get_resources(args)\n+\n+ def testInvalidMultiTypeMultiResource(self):\n+ args = (\"pods/mypod\", \"svc/myservice\", \"blarg/bad\")\n+ with self.assertRaises(parse.ResourceParseError):\n+ parse.parse_get_resources(args)\n+\n+\n+if __name__ == \"__main__\":\n+ unittest.main()\n", "problem_statement": "", "hints_text": "", "created_at": "2020-12-18T23:09:32Z"} | |