|
| 1 | +""" |
| 2 | +CLI configuration decorator to use TOML configuration files for click commands. |
| 3 | +""" |
| 4 | + |
| 5 | +## This section contains code copied and modified from [click_config_file][https://github.com/phha/click_config_file/blob/master/click_config_file.py] |
| 6 | +## SPDX-License-Identifier: MIT |
| 7 | + |
| 8 | +import functools |
| 9 | +import os |
| 10 | +import logging |
| 11 | + |
| 12 | +import click |
| 13 | +import toml |
| 14 | + |
| 15 | +__all__ = ("TomlProvider", "configuration_option", "get_ctx_defaults") |
| 16 | + |
| 17 | +LOG = logging.getLogger("samcli") |
| 18 | +DEFAULT_CONFIG_FILE_NAME = "samconfig.toml" |
| 19 | +DEFAULT_IDENTIFER = "default" |
| 20 | + |
| 21 | + |
| 22 | +class TomlProvider: |
| 23 | + """ |
| 24 | + A parser for toml configuration files |
| 25 | + :param cmd: sam command name as defined by click |
| 26 | + :param section: section defined in the configuration file nested within `cmd` |
| 27 | + """ |
| 28 | + |
| 29 | + def __init__(self, section=None): |
| 30 | + self.section = section |
| 31 | + |
| 32 | + def __call__(self, file_path, config_env, cmd_name): |
| 33 | + """ |
| 34 | + Get resolved config based on the `file_path` for the configuration file, |
| 35 | + `config_env` targeted inside the config file and corresponding `cmd_name` |
| 36 | + as denoted by `click`. |
| 37 | +
|
| 38 | + :param file_path: The path to the configuration file |
| 39 | + :param config_env: The name of the sectional config_env within configuration file. |
| 40 | + :param cmd_name: sam command name as defined by click |
| 41 | + :returns dictionary containing the configuration parameters under specified config_env |
| 42 | + """ |
| 43 | + resolved_config = {} |
| 44 | + try: |
| 45 | + config = toml.load(file_path) |
| 46 | + except Exception as ex: |
| 47 | + LOG.error("Error reading configuration file :%s %s", file_path, str(ex)) |
| 48 | + return resolved_config |
| 49 | + if self.section: |
| 50 | + try: |
| 51 | + resolved_config = self._get_config_env(config, config_env)[cmd_name][self.section] |
| 52 | + except KeyError: |
| 53 | + LOG.debug( |
| 54 | + "Error reading configuration file at %s with config_env %s, command %s, section %s", |
| 55 | + file_path, |
| 56 | + config_env, |
| 57 | + cmd_name, |
| 58 | + self.section, |
| 59 | + ) |
| 60 | + return resolved_config |
| 61 | + |
| 62 | + def _get_config_env(self, config, config_env): |
| 63 | + """ |
| 64 | +
|
| 65 | + :param config: loaded TOML configuration file into dictionary representation |
| 66 | + :param config_env: top level section defined within TOML configuration file |
| 67 | + :return: |
| 68 | + """ |
| 69 | + return config.get(config_env, config.get(DEFAULT_IDENTIFER, {})) |
| 70 | + |
| 71 | + |
| 72 | +def configuration_callback(cmd_name, option_name, config_env_name, saved_callback, provider, ctx, param, value): |
| 73 | + """ |
| 74 | + Callback for reading the config file. |
| 75 | +
|
| 76 | + Also takes care of calling user specified custom callback afterwards. |
| 77 | +
|
| 78 | + :param cmd_name: `sam` command name derived from click. |
| 79 | + :param option_name: The name of the option. This is used for error messages. |
| 80 | + :param config_env_name: `top` level section within configuration file |
| 81 | + :param saved_callback: User-specified callback to be called later. |
| 82 | + :param provider: A callable that parses the configuration file and returns a dictionary |
| 83 | + of the configuration parameters. Will be called as |
| 84 | + `provider(file_path, config_env, cmd_name)`. |
| 85 | + :param ctx: Click context |
| 86 | + :param param: Click parameter |
| 87 | + :param value: Specified value for config_env |
| 88 | + :returns specified callback or the specified value for config_env. |
| 89 | + """ |
| 90 | + |
| 91 | + # ctx, param and value are default arguments for click specified callbacks. |
| 92 | + ctx.default_map = ctx.default_map or {} |
| 93 | + cmd_name = cmd_name or ctx.info_name |
| 94 | + param.default = DEFAULT_IDENTIFER |
| 95 | + config_env_name = value or config_env_name |
| 96 | + config = get_ctx_defaults(cmd_name, provider, ctx, config_env_name=config_env_name) |
| 97 | + ctx.default_map.update(config) |
| 98 | + |
| 99 | + return saved_callback(ctx, param, value) if saved_callback else value |
| 100 | + |
| 101 | + |
| 102 | +def get_ctx_defaults(cmd_name, provider, ctx, config_env_name=DEFAULT_IDENTIFER): |
| 103 | + """ |
| 104 | + Get the set of the parameters that are needed to be set into the click command. |
| 105 | + This function also figures out the command name by looking up current click context's parent |
| 106 | + and constructing the parsed command name that is used in default configuration file. |
| 107 | + If a given cmd_name is start-api, the parsed name is "local_start_api". |
| 108 | + provider is called with `config_file`, `config_env_name` and `parsed_cmd_name`. |
| 109 | +
|
| 110 | + :param cmd_name: `sam` command name |
| 111 | + :param provider: provider to be called for reading configuration file |
| 112 | + :param ctx: Click context |
| 113 | + :param config_env_name: config-env within configuration file |
| 114 | + :return: dictionary of defaults for parameters |
| 115 | + """ |
| 116 | + |
| 117 | + cwd = getattr(ctx, "config_path", None) |
| 118 | + config_file = os.path.join(cwd if cwd else os.getcwd(), DEFAULT_CONFIG_FILE_NAME) |
| 119 | + config = {} |
| 120 | + if os.path.isfile(config_file): |
| 121 | + LOG.debug("Config file location: %s", os.path.abspath(config_file)) |
| 122 | + |
| 123 | + # Find parent of current context |
| 124 | + _parent = ctx.parent |
| 125 | + _cmd_names = [] |
| 126 | + # Need to find the total set of commands that current command is part of. |
| 127 | + if cmd_name != ctx.info_name: |
| 128 | + _cmd_names = [cmd_name] |
| 129 | + _cmd_names.append(ctx.info_name) |
| 130 | + # Go through all parents till a parent of a context exists. |
| 131 | + while _parent.parent: |
| 132 | + info_name = _parent.info_name |
| 133 | + _cmd_names.append(info_name) |
| 134 | + _parent = _parent.parent |
| 135 | + |
| 136 | + # construct a parsed name that is of the format: a_b_c_d |
| 137 | + parsed_cmd_name = "_".join(reversed([cmd.replace("-", "_").replace(" ", "_") for cmd in _cmd_names])) |
| 138 | + |
| 139 | + config = provider(config_file, config_env_name, parsed_cmd_name) |
| 140 | + |
| 141 | + return config |
| 142 | + |
| 143 | + |
| 144 | +def configuration_option(*param_decls, **attrs): |
| 145 | + """ |
| 146 | + Adds configuration file support to a click application. |
| 147 | +
|
| 148 | + This will create an option of type `STRING` expecting the config_env in the |
| 149 | + configuration file, by default this config_env is `default`. When specified, |
| 150 | + the requisite portion of the configuration file is considered as the |
| 151 | + source of truth. |
| 152 | +
|
| 153 | + The default name of the option is `--config-env`. |
| 154 | +
|
| 155 | + This decorator accepts the same arguments as `click.option`. |
| 156 | + In addition, the following keyword arguments are available: |
| 157 | + :param cmd_name: The command name. Default: `ctx.info_name` |
| 158 | + :param config_env_name: The config_env name. This is used to determine which part of the configuration |
| 159 | + needs to be read. |
| 160 | + :param provider: A callable that parses the configuration file and returns a dictionary |
| 161 | + of the configuration parameters. Will be called as |
| 162 | + `provider(file_path, config_env, cmd_name) |
| 163 | + """ |
| 164 | + param_decls = param_decls or ("--config-env",) |
| 165 | + option_name = param_decls[0] |
| 166 | + |
| 167 | + def decorator(f): |
| 168 | + |
| 169 | + attrs.setdefault("is_eager", True) |
| 170 | + attrs.setdefault("help", "Read config-env from Configuration File.") |
| 171 | + attrs.setdefault("expose_value", False) |
| 172 | + # --config-env is hidden and can potentially be opened up in the future. |
| 173 | + attrs.setdefault("hidden", True) |
| 174 | + # explicitly ignore values passed to --config-env, can be opened up in the future. |
| 175 | + config_env_name = DEFAULT_IDENTIFER |
| 176 | + provider = attrs.pop("provider") |
| 177 | + attrs["type"] = click.STRING |
| 178 | + saved_callback = attrs.pop("callback", None) |
| 179 | + partial_callback = functools.partial( |
| 180 | + configuration_callback, None, option_name, config_env_name, saved_callback, provider |
| 181 | + ) |
| 182 | + attrs["callback"] = partial_callback |
| 183 | + return click.option(*param_decls, **attrs)(f) |
| 184 | + |
| 185 | + return decorator |
| 186 | + |
| 187 | + |
| 188 | +# End section copied from [[click_config_file][https://github.com/phha/click_config_file/blob/master/click_config_file.py] |
0 commit comments