Coverage for appr/commands/command_base.py: 32%

# Coverage for appr/commands/command_base.py : 32%

## 166 statements 53 run 113 missing 0 excluded

Hot-keys on this page

r m x p toggle line displays

j k next/prev highlighted chunk

0 (zero) top of page

1 (one) first highlighted chunk

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 | from __future__ import absolute_import, division, print_function import argparse import copy import json import os import re import subprocess import requests import yaml from appr.client import ApprClient from appr.utils import parse_package_name, parse_version, split_package_name from appr.render_jsonnet import RenderJsonnet def _set_package(parser, namespace, dest, package_parts): parsed_version = parse_version(package_parts['version']) setattr(namespace, "registry_host", package_parts['host']) setattr(namespace, 'version', parsed_version['value']) setattr(namespace, 'version_parts', parsed_version) package = "%s/%s" % (package_parts['namespace'], package_parts['package']) setattr(namespace, dest, package) setattr(namespace, "package_parts", package_parts) class PackageName(argparse.Action): def __call__(self, parser, namespace, value, option_string=None): try: name = value[0] package_parts = parse_package_name(name) _set_package(parser, namespace, self.dest, package_parts) except ValueError as exc: raise parser.error(str(exc)) class RegistryHost(argparse.Action): def __call__(self, parser, namespace, value, option_string=None): setattr(namespace, self.dest, value[0]) class PackageSplit(argparse.Action): def __call__(self, parser, namespace, value, option_string=None): name = value package_parts = split_package_name(name) _set_package(parser, namespace, self.dest, package_parts) class LoadVariables(argparse.Action): def _parse_cmd(self, var): r = {} try: return json.loads(var) except: for v in var.split(","): sp = re.match("(.+?)=(.+)", v) if sp is None: raise ValueError("Malformed variable: %s" % v) key, value = sp.group(1), sp.group(2) r[key] = value return r def _load_from_file(self, filename, ext): with open(filename, 'r') as f: if ext in ['.yml', '.yaml']: return yaml.load(f.read()) elif ext == '.json': return json.loads(f.read()) elif ext in [".jsonnet", "libjsonnet"]: r = RenderJsonnet() return r.render_jsonnet(f.read()) else: raise ValueError("File extension is not in [yaml, json, jsonnet]: %s" % filename) def load_variables(self, var): _, ext = os.path.splitext(var) if ext not in ['.yaml', '.yml', '.json', '.jsonnet']: return self._parse_cmd(var) else: return self._load_from_file(var, ext) def __call__(self, parser, namespace, values, option_string=None): items = copy.copy(argparse._ensure_value(namespace, self.dest, {})) try: items.update(self.load_variables(values)) except ValueError as exc: raise parser.error(option_string + ": " + str(exc)) setattr(namespace, self.dest, items) class CommandBase(object): name = 'command-base' help_message = 'describe the command' RegistryClient = ApprClient default_media_type = "-" parse_unknown = False output_default = 'text' def __init__(self, args_options, unknown=None): self.unknown = unknown self.args_options = args_options self.output = args_options.output def render(self): if self.output == 'none': return elif self.output == 'json': self._render_json() elif self.output == 'yaml': self._render_yaml() else: print(self._render_console()) def render_error(self, payload): if self.output == 'json': self._render_json(payload) elif self.output == 'yaml': self._render_yaml(payload) else: raise argparse.ArgumentTypeError("\n" + yaml.safe_dump( payload, default_flow_style=False, width=float("inf"))) @classmethod def call(cls, options, unknown=None, render=True): # @TODO(ant31): all methods should have the 'unknown' parameter if cls.parse_unknown: obj = cls(options, unknown) else: obj = cls(options) obj.exec_cmd(render=render) def exec_cmd(self, render=True): try: self._call() except requests.exceptions.RequestException as exc: payload = {"message": str(exc)} if exc.response is not None: content = None try: content = exc.response.json() except ValueError: content = exc.response.content payload["response"] = content self.render_error(payload) exit(2) except subprocess.CalledProcessError as exc: payload = {"message": str(exc.output)} self.render_error(payload) exit(exc.returncode) if render: self.render() @classmethod def add_parser(cls, subparsers, env=None): parser = subparsers.add_parser(cls.name, help=cls.help_message) cls._add_output_option(parser) cls._add_arguments(parser) parser.set_defaults(func=cls.call, env=env, which_cmd=cls.name, parse_unknown=cls.parse_unknown) def _render_json(self, value=None): if not value: value = self._render_dict() print(json.dumps(value, indent=2, separators=(',', ': '))) def _render_dict(self): raise NotImplementedError def _render_console(self): raise NotImplementedError def _render_yaml(self, value=None): if not value: value = self._render_dict() print(yaml.safe_dump(value, default_flow_style=False, width=float("inf"))) def _call(self): raise NotImplementedError @classmethod def _add_arguments(cls, parser): raise NotImplementedError @classmethod def _add_registryhost_option(cls, parser): parser.add_argument("-H", "--registry-host", default=None, help=argparse.SUPPRESS) parser.add_argument("-k", "--insecure", action="store_true", default=False, help="turn off verification of the https certificate") parser.add_argument("--cacert", default=None, help="CA certificate to verify peer against (SSL)") @classmethod def _add_output_option(cls, parser): parser.add_argument("--output", default=cls.output_default, choices=[ 'text', 'none', 'json', 'yaml'], help="output format") @classmethod def _add_mediatype_option(cls, parser, default="-", required=False): default = os.getenv("APPR_DEFAULT_MEDIA_TYPE", default) if default is not None: required = False parser.add_argument( "-t", "--media-type", default=default, required=required, help='package format: [kpm, kpm-compose, helm, docker-compose, kubernetes, appr]') @classmethod def _add_packagename_option(cls, parser): parser.add_argument('package', nargs=1, default=None, action=PackageName, help="package-name") @classmethod def _add_packagesplit_option(cls, parser): parser.add_argument('package', nargs="?", default=None, action=PackageSplit, help="registry-host.com/namespace/name") @classmethod def _add_packageversion_option(cls, parser): parser.add_argument("-v", "--version", help="package VERSION", default='default') @classmethod def _add_registryhost_arg(cls, parser): parser.add_argument("registry_host", nargs=1, action=RegistryHost, help='registry API url') parser.add_argument("-k", "--insecure", action="store_true", default=False, help="turn off verification of the https certificate") parser.add_argument("--cacert", nargs='?', default=None, help="CA certificate to verify peer against (SSL)")