2019-10-08 09:39:27 +00:00
|
|
|
#!/usr/bin/env python3
|
|
|
|
"""Global settings definition."""
|
2019-10-07 12:44:45 +00:00
|
|
|
|
2019-10-07 06:52:00 +00:00
|
|
|
import os
|
|
|
|
|
2019-10-07 12:44:45 +00:00
|
|
|
import anyconfig
|
2019-10-08 22:59:40 +00:00
|
|
|
import environs
|
2019-10-08 09:30:31 +00:00
|
|
|
import jsonschema.exceptions
|
2019-10-15 08:48:18 +00:00
|
|
|
import ruamel.yaml
|
2019-10-07 12:44:45 +00:00
|
|
|
from appdirs import AppDirs
|
|
|
|
from jsonschema._utils import format_as_index
|
2019-10-07 06:52:00 +00:00
|
|
|
|
2021-01-01 12:50:41 +00:00
|
|
|
import ansibledoctor.exception
|
|
|
|
from ansibledoctor.utils import Singleton
|
2019-10-07 06:52:00 +00:00
|
|
|
|
2019-10-07 12:44:45 +00:00
|
|
|
config_dir = AppDirs("ansible-doctor").user_config_dir
|
|
|
|
default_config_file = os.path.join(config_dir, "config.yml")
|
2023-02-12 11:57:57 +00:00
|
|
|
default_envs_prefix = "ANSIBLE_DOCTOR_"
|
2019-10-07 12:44:45 +00:00
|
|
|
|
|
|
|
|
2023-06-28 07:57:00 +00:00
|
|
|
class Config:
|
2019-10-07 12:44:45 +00:00
|
|
|
"""
|
|
|
|
Create an object with all necessary settings.
|
|
|
|
|
|
|
|
Settings are loade from multiple locations in defined order (last wins):
|
|
|
|
- default settings defined by `self._get_defaults()`
|
|
|
|
- yaml config file, defaults to OS specific user config dir (https://pypi.org/project/appdirs/)
|
|
|
|
- provides cli parameters
|
|
|
|
"""
|
|
|
|
|
2019-10-08 22:56:39 +00:00
|
|
|
SETTINGS = {
|
|
|
|
"config_file": {
|
2023-02-12 11:57:57 +00:00
|
|
|
"default": default_config_file,
|
2019-10-08 22:56:39 +00:00
|
|
|
"env": "CONFIG_FILE",
|
2023-11-10 13:50:50 +00:00
|
|
|
"type": environs.Env().str,
|
2019-10-08 22:56:39 +00:00
|
|
|
},
|
2023-02-12 11:57:57 +00:00
|
|
|
"base_dir": {
|
|
|
|
"default": os.getcwd(),
|
|
|
|
"refresh": os.getcwd,
|
|
|
|
"env": "BASE_DIR",
|
2023-11-10 13:50:50 +00:00
|
|
|
"type": environs.Env().str,
|
2019-10-08 22:56:39 +00:00
|
|
|
},
|
2020-01-22 12:07:05 +00:00
|
|
|
"role_name": {
|
|
|
|
"default": "",
|
|
|
|
"env": "ROLE_NAME",
|
2023-11-10 13:50:50 +00:00
|
|
|
"type": environs.Env().str,
|
2020-01-22 12:07:05 +00:00
|
|
|
},
|
2019-10-08 22:56:39 +00:00
|
|
|
"dry_run": {
|
|
|
|
"default": False,
|
|
|
|
"env": "DRY_RUN",
|
|
|
|
"file": True,
|
2023-11-10 13:50:50 +00:00
|
|
|
"type": environs.Env().bool,
|
2019-10-08 22:56:39 +00:00
|
|
|
},
|
|
|
|
"logging.level": {
|
|
|
|
"default": "WARNING",
|
|
|
|
"env": "LOG_LEVEL",
|
|
|
|
"file": True,
|
2023-11-10 13:50:50 +00:00
|
|
|
"type": environs.Env().str,
|
2019-10-08 22:56:39 +00:00
|
|
|
},
|
|
|
|
"logging.json": {
|
|
|
|
"default": False,
|
|
|
|
"env": "LOG_JSON",
|
|
|
|
"file": True,
|
2023-11-10 13:50:50 +00:00
|
|
|
"type": environs.Env().bool,
|
2019-10-08 22:56:39 +00:00
|
|
|
},
|
|
|
|
"output_dir": {
|
|
|
|
"default": os.getcwd(),
|
2023-02-12 11:57:57 +00:00
|
|
|
"refresh": os.getcwd,
|
2019-10-08 22:56:39 +00:00
|
|
|
"env": "OUTPUT_DIR",
|
|
|
|
"file": True,
|
2023-11-10 13:50:50 +00:00
|
|
|
"type": environs.Env().str,
|
2019-10-08 22:56:39 +00:00
|
|
|
},
|
2023-02-12 11:57:57 +00:00
|
|
|
"recursive": {
|
|
|
|
"default": False,
|
|
|
|
"env": "RECURSIVE",
|
2023-11-10 13:50:50 +00:00
|
|
|
"type": environs.Env().bool,
|
2023-02-12 11:57:57 +00:00
|
|
|
},
|
2019-10-08 22:56:39 +00:00
|
|
|
"template_dir": {
|
|
|
|
"default": os.path.join(os.path.dirname(os.path.realpath(__file__)), "templates"),
|
|
|
|
"env": "TEMPLATE_DIR",
|
|
|
|
"file": True,
|
2023-11-10 13:50:50 +00:00
|
|
|
"type": environs.Env().str,
|
2019-10-08 22:56:39 +00:00
|
|
|
},
|
|
|
|
"template": {
|
|
|
|
"default": "readme",
|
|
|
|
"env": "TEMPLATE",
|
|
|
|
"file": True,
|
2023-11-10 13:50:50 +00:00
|
|
|
"type": environs.Env().str,
|
2019-10-08 22:56:39 +00:00
|
|
|
},
|
2023-06-14 11:31:01 +00:00
|
|
|
"template_autotrim": {
|
|
|
|
"default": True,
|
|
|
|
"env": "TEMPLATE_AUTOTRIM",
|
|
|
|
"file": True,
|
2023-11-10 13:50:50 +00:00
|
|
|
"type": environs.Env().bool,
|
2023-06-14 11:31:01 +00:00
|
|
|
},
|
2019-10-08 22:56:39 +00:00
|
|
|
"force_overwrite": {
|
|
|
|
"default": False,
|
|
|
|
"env": "FORCE_OVERWRITE",
|
|
|
|
"file": True,
|
2023-11-10 13:50:50 +00:00
|
|
|
"type": environs.Env().bool,
|
2019-10-08 22:56:39 +00:00
|
|
|
},
|
|
|
|
"custom_header": {
|
|
|
|
"default": "",
|
|
|
|
"env": "CUSTOM_HEADER",
|
|
|
|
"file": True,
|
2023-11-10 13:50:50 +00:00
|
|
|
"type": environs.Env().str,
|
2019-10-08 22:56:39 +00:00
|
|
|
},
|
|
|
|
"exclude_files": {
|
|
|
|
"default": [],
|
|
|
|
"env": "EXCLUDE_FILES",
|
|
|
|
"file": True,
|
2023-11-10 13:50:50 +00:00
|
|
|
"type": environs.Env().list,
|
2019-10-08 22:56:39 +00:00
|
|
|
},
|
2022-04-29 11:19:35 +00:00
|
|
|
"exclude_tags": {
|
|
|
|
"default": [],
|
|
|
|
"env": "EXCLUDE_TAGS",
|
|
|
|
"file": True,
|
2023-11-10 13:50:50 +00:00
|
|
|
"type": environs.Env().list,
|
2022-04-29 11:19:35 +00:00
|
|
|
},
|
2021-07-27 20:01:56 +00:00
|
|
|
"role_detection": {
|
|
|
|
"default": True,
|
|
|
|
"env": "ROLE_DETECTION",
|
2021-07-27 19:32:39 +00:00
|
|
|
"file": True,
|
2023-11-10 13:50:50 +00:00
|
|
|
"type": environs.Env().bool,
|
2021-07-27 19:32:39 +00:00
|
|
|
},
|
2019-10-08 22:56:39 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
ANNOTATIONS = {
|
|
|
|
"meta": {
|
|
|
|
"name": "meta",
|
2019-10-15 07:54:03 +00:00
|
|
|
"automatic": True,
|
2022-02-21 20:38:47 +00:00
|
|
|
"subtypes": ["value"],
|
2023-11-10 13:50:50 +00:00
|
|
|
"allow_multiple": False,
|
2019-10-08 22:56:39 +00:00
|
|
|
},
|
|
|
|
"todo": {
|
|
|
|
"name": "todo",
|
|
|
|
"automatic": True,
|
2022-02-21 20:38:47 +00:00
|
|
|
"subtypes": ["value"],
|
2023-11-10 13:50:50 +00:00
|
|
|
"allow_multiple": True,
|
2019-10-08 22:56:39 +00:00
|
|
|
},
|
|
|
|
"var": {
|
|
|
|
"name": "var",
|
|
|
|
"automatic": True,
|
2023-03-27 11:18:42 +00:00
|
|
|
"subtypes": ["value", "example", "description", "type", "deprecated"],
|
2023-11-10 13:50:50 +00:00
|
|
|
"allow_multiple": False,
|
2019-10-08 22:56:39 +00:00
|
|
|
},
|
|
|
|
"example": {
|
|
|
|
"name": "example",
|
2019-10-15 07:54:03 +00:00
|
|
|
"automatic": True,
|
2022-02-21 20:38:47 +00:00
|
|
|
"subtypes": [],
|
2023-11-10 13:50:50 +00:00
|
|
|
"allow_multiple": False,
|
2019-10-08 22:56:39 +00:00
|
|
|
},
|
|
|
|
"tag": {
|
|
|
|
"name": "tag",
|
|
|
|
"automatic": True,
|
2022-02-26 12:35:34 +00:00
|
|
|
"subtypes": ["value", "description"],
|
2023-11-10 13:50:50 +00:00
|
|
|
"allow_multiple": False,
|
2019-10-08 22:56:39 +00:00
|
|
|
},
|
|
|
|
}
|
|
|
|
|
2023-01-20 10:56:12 +00:00
|
|
|
def __init__(self, args=None):
|
2019-10-07 12:44:45 +00:00
|
|
|
"""
|
|
|
|
Initialize a new settings class.
|
2019-10-07 06:52:00 +00:00
|
|
|
|
2019-10-07 12:44:45 +00:00
|
|
|
:param args: An optional dict of options, arguments and commands from the CLI.
|
|
|
|
:param config_file: An optional path to a yaml config file.
|
|
|
|
:returns: None
|
|
|
|
|
|
|
|
"""
|
2023-01-20 10:56:12 +00:00
|
|
|
if args is None:
|
|
|
|
self._args = {}
|
|
|
|
else:
|
|
|
|
self._args = args
|
2019-10-08 22:56:39 +00:00
|
|
|
self._schema = None
|
|
|
|
self.config = None
|
2023-02-12 11:57:57 +00:00
|
|
|
self.is_role = False
|
|
|
|
self.set_config()
|
2019-10-07 12:44:45 +00:00
|
|
|
|
2019-10-08 22:56:39 +00:00
|
|
|
def _get_args(self, args):
|
|
|
|
cleaned = dict(filter(lambda item: item[1] is not None, args.items()))
|
2019-10-07 12:44:45 +00:00
|
|
|
|
2019-10-08 22:56:39 +00:00
|
|
|
normalized = {}
|
|
|
|
for key, value in cleaned.items():
|
|
|
|
normalized = self._add_dict_branch(normalized, key.split("."), value)
|
2019-10-07 12:44:45 +00:00
|
|
|
|
|
|
|
# Override correct log level from argparse
|
|
|
|
levels = ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]
|
2019-10-08 22:56:39 +00:00
|
|
|
log_level = levels.index(self.SETTINGS["logging.level"]["default"])
|
|
|
|
if normalized.get("logging"):
|
|
|
|
for adjustment in normalized["logging"]["level"]:
|
2019-10-07 12:44:45 +00:00
|
|
|
log_level = min(len(levels) - 1, max(log_level + adjustment, 0))
|
2019-10-08 22:56:39 +00:00
|
|
|
normalized["logging"]["level"] = levels[log_level]
|
2019-10-07 12:44:45 +00:00
|
|
|
|
2019-10-08 22:56:39 +00:00
|
|
|
return normalized
|
2019-10-07 12:44:45 +00:00
|
|
|
|
|
|
|
def _get_defaults(self):
|
2019-10-08 22:56:39 +00:00
|
|
|
normalized = {}
|
|
|
|
for key, item in self.SETTINGS.items():
|
2023-02-12 11:57:57 +00:00
|
|
|
if item.get("refresh"):
|
|
|
|
item["default"] = item["refresh"]()
|
2019-10-08 22:56:39 +00:00
|
|
|
normalized = self._add_dict_branch(normalized, key.split("."), item["default"])
|
|
|
|
|
|
|
|
self.schema = anyconfig.gen_schema(normalized)
|
|
|
|
return normalized
|
|
|
|
|
|
|
|
def _get_envs(self):
|
|
|
|
normalized = {}
|
|
|
|
for key, item in self.SETTINGS.items():
|
|
|
|
if item.get("env"):
|
2023-02-12 11:57:57 +00:00
|
|
|
envname = f"{default_envs_prefix}{item['env']}"
|
2019-10-08 22:56:39 +00:00
|
|
|
try:
|
|
|
|
value = item["type"](envname)
|
|
|
|
normalized = self._add_dict_branch(normalized, key.split("."), value)
|
|
|
|
except environs.EnvError as e:
|
2023-01-20 10:56:12 +00:00
|
|
|
if f'"{envname}" not set' in str(e):
|
2019-10-08 22:56:39 +00:00
|
|
|
pass
|
|
|
|
else:
|
2021-01-01 12:50:41 +00:00
|
|
|
raise ansibledoctor.exception.ConfigError(
|
2020-04-05 21:16:53 +00:00
|
|
|
"Unable to read environment variable", str(e)
|
2023-02-27 08:03:09 +00:00
|
|
|
) from e
|
2019-10-08 22:56:39 +00:00
|
|
|
|
|
|
|
return normalized
|
|
|
|
|
2023-02-12 11:57:57 +00:00
|
|
|
def set_config(self, base_dir=None):
|
2019-10-08 22:56:39 +00:00
|
|
|
args = self._get_args(self._args)
|
|
|
|
envs = self._get_envs()
|
2019-10-07 12:44:45 +00:00
|
|
|
defaults = self._get_defaults()
|
2019-10-08 22:56:39 +00:00
|
|
|
|
2023-02-12 11:57:57 +00:00
|
|
|
self.recursive = defaults.get("recursive")
|
|
|
|
if envs.get("recursive"):
|
|
|
|
self.recursive = envs.get("recursive")
|
|
|
|
if args.get("recursive"):
|
|
|
|
self.recursive = args.get("recursive")
|
|
|
|
if "recursive" in defaults:
|
|
|
|
defaults.pop("recursive")
|
|
|
|
|
|
|
|
self.config_file = defaults.get("config_file")
|
2019-10-08 22:56:39 +00:00
|
|
|
if envs.get("config_file"):
|
|
|
|
self.config_file = self._normalize_path(envs.get("config_file"))
|
|
|
|
if args.get("config_file"):
|
|
|
|
self.config_file = self._normalize_path(args.get("config_file"))
|
2023-02-12 11:57:57 +00:00
|
|
|
if "config_file" in defaults:
|
|
|
|
defaults.pop("config_file")
|
|
|
|
|
|
|
|
self.base_dir = defaults.get("base_dir")
|
|
|
|
if envs.get("base_dir"):
|
|
|
|
self.base_dir = self._normalize_path(envs.get("base_dir"))
|
|
|
|
if args.get("base_dir"):
|
|
|
|
self.base_dir = self._normalize_path(args.get("base_dir"))
|
|
|
|
if base_dir:
|
|
|
|
self.base_dir = base_dir
|
|
|
|
if "base_dir" in defaults:
|
|
|
|
defaults.pop("base_dir")
|
|
|
|
|
|
|
|
self.is_role = os.path.isdir(os.path.join(self.base_dir, "tasks"))
|
|
|
|
|
|
|
|
# compute role_name default
|
|
|
|
defaults["role_name"] = os.path.basename(self.base_dir)
|
2019-10-08 22:56:39 +00:00
|
|
|
|
2019-10-07 12:44:45 +00:00
|
|
|
source_files = []
|
2023-02-12 11:57:57 +00:00
|
|
|
source_files.append((self.config_file, False))
|
|
|
|
source_files.append((os.path.join(os.getcwd(), ".ansibledoctor"), True))
|
|
|
|
source_files.append((os.path.join(os.getcwd(), ".ansibledoctor.yml"), True))
|
|
|
|
source_files.append((os.path.join(os.getcwd(), ".ansibledoctor.yaml"), True))
|
2019-10-07 12:44:45 +00:00
|
|
|
|
2023-11-10 13:50:50 +00:00
|
|
|
for config, first_found in source_files:
|
2019-10-07 12:44:45 +00:00
|
|
|
if config and os.path.exists(config):
|
2023-01-20 10:56:12 +00:00
|
|
|
with open(config, encoding="utf8") as stream:
|
2019-10-07 12:44:45 +00:00
|
|
|
s = stream.read()
|
2019-10-08 09:30:31 +00:00
|
|
|
try:
|
2023-11-12 13:46:24 +00:00
|
|
|
file_dict = ruamel.yaml.YAML(typ="safe", pure=True).load(s)
|
2020-04-05 21:16:53 +00:00
|
|
|
except (
|
2023-11-10 13:50:50 +00:00
|
|
|
ruamel.yaml.composer.ComposerError,
|
|
|
|
ruamel.yaml.scanner.ScannerError,
|
2020-04-05 21:16:53 +00:00
|
|
|
) as e:
|
2023-01-20 10:56:12 +00:00
|
|
|
message = f"{e.context} {e.problem}"
|
2021-01-01 12:50:41 +00:00
|
|
|
raise ansibledoctor.exception.ConfigError(
|
2023-02-12 11:57:57 +00:00
|
|
|
f"Unable to read config file: {config}", message
|
2023-01-20 10:56:12 +00:00
|
|
|
) from e
|
2019-10-08 09:30:31 +00:00
|
|
|
|
2019-10-08 22:56:39 +00:00
|
|
|
if self._validate(file_dict):
|
|
|
|
anyconfig.merge(defaults, file_dict, ac_merge=anyconfig.MS_DICTS)
|
2019-10-07 12:44:45 +00:00
|
|
|
defaults["logging"]["level"] = defaults["logging"]["level"].upper()
|
|
|
|
|
2023-02-12 11:57:57 +00:00
|
|
|
self.config_file = config
|
|
|
|
if first_found:
|
|
|
|
break
|
|
|
|
|
2019-10-08 22:56:39 +00:00
|
|
|
if self._validate(envs):
|
|
|
|
anyconfig.merge(defaults, envs, ac_merge=anyconfig.MS_DICTS)
|
2019-10-07 12:44:45 +00:00
|
|
|
|
2019-10-08 22:56:39 +00:00
|
|
|
if self._validate(args):
|
|
|
|
anyconfig.merge(defaults, args, ac_merge=anyconfig.MS_DICTS)
|
|
|
|
|
2019-10-09 21:19:57 +00:00
|
|
|
fix_files = ["output_dir", "template_dir", "custom_header"]
|
2023-02-12 11:57:57 +00:00
|
|
|
for filename in fix_files:
|
|
|
|
if defaults[filename] and defaults[filename] != "":
|
|
|
|
defaults[filename] = self._normalize_path(defaults[filename])
|
2019-10-09 21:19:57 +00:00
|
|
|
|
|
|
|
defaults["logging"]["level"] = defaults["logging"]["level"].upper()
|
2019-10-08 22:56:39 +00:00
|
|
|
|
|
|
|
self.config = defaults
|
|
|
|
|
|
|
|
def _normalize_path(self, path):
|
|
|
|
if not os.path.isabs(path):
|
2019-10-09 21:19:57 +00:00
|
|
|
base = os.path.join(os.getcwd(), path)
|
|
|
|
return os.path.abspath(os.path.expanduser(os.path.expandvars(base)))
|
2023-01-20 10:56:12 +00:00
|
|
|
|
|
|
|
return path
|
2019-10-08 09:30:31 +00:00
|
|
|
|
2019-10-07 12:44:45 +00:00
|
|
|
def _validate(self, config):
|
|
|
|
try:
|
|
|
|
anyconfig.validate(config, self.schema, ac_schema_safe=False)
|
2019-10-08 09:30:31 +00:00
|
|
|
except jsonschema.exceptions.ValidationError as e:
|
|
|
|
schema_error = "Failed validating '{validator}' in schema{schema}\n{message}".format(
|
2019-10-07 12:44:45 +00:00
|
|
|
validator=e.validator,
|
2019-10-08 09:30:31 +00:00
|
|
|
schema=format_as_index(list(e.relative_schema_path)[:-1]),
|
2023-11-10 13:50:50 +00:00
|
|
|
message=e.message,
|
2019-10-07 12:44:45 +00:00
|
|
|
)
|
2023-01-20 10:56:12 +00:00
|
|
|
raise ansibledoctor.exception.ConfigError("Configuration error", schema_error) from e
|
2019-10-07 12:44:45 +00:00
|
|
|
|
2019-10-08 09:30:31 +00:00
|
|
|
return True
|
2019-10-07 12:44:45 +00:00
|
|
|
|
|
|
|
def _add_dict_branch(self, tree, vector, value):
|
|
|
|
key = vector[0]
|
2023-11-10 13:50:50 +00:00
|
|
|
tree[key] = (
|
|
|
|
value
|
|
|
|
if len(vector) == 1
|
2019-10-08 22:56:39 +00:00
|
|
|
else self._add_dict_branch(tree[key] if key in tree else {}, vector[1:], value)
|
2023-11-10 13:50:50 +00:00
|
|
|
)
|
2019-10-07 12:44:45 +00:00
|
|
|
return tree
|
2019-10-07 06:52:00 +00:00
|
|
|
|
|
|
|
def get_annotations_definition(self, automatic=True):
|
|
|
|
annotations = {}
|
|
|
|
if automatic:
|
2019-10-08 22:56:39 +00:00
|
|
|
for k, item in self.ANNOTATIONS.items():
|
2023-01-20 10:56:12 +00:00
|
|
|
if "automatic" in item and item["automatic"]:
|
2019-10-07 06:52:00 +00:00
|
|
|
annotations[k] = item
|
|
|
|
return annotations
|
|
|
|
|
|
|
|
def get_annotations_names(self, automatic=True):
|
|
|
|
annotations = []
|
|
|
|
if automatic:
|
2019-10-08 22:56:39 +00:00
|
|
|
for k, item in self.ANNOTATIONS.items():
|
2023-01-20 10:56:12 +00:00
|
|
|
if "automatic" in item and item["automatic"]:
|
2019-10-07 06:52:00 +00:00
|
|
|
annotations.append(k)
|
|
|
|
return annotations
|
|
|
|
|
2019-10-07 12:44:45 +00:00
|
|
|
def get_template(self):
|
2019-10-07 06:52:00 +00:00
|
|
|
"""
|
|
|
|
Get the base dir for the template to use.
|
|
|
|
|
|
|
|
:return: str abs path
|
|
|
|
"""
|
2019-10-07 12:44:45 +00:00
|
|
|
template_dir = self.config.get("template_dir")
|
|
|
|
template = self.config.get("template")
|
|
|
|
return os.path.realpath(os.path.join(template_dir, template))
|
2019-10-07 06:52:00 +00:00
|
|
|
|
|
|
|
|
|
|
|
class SingleConfig(Config, metaclass=Singleton):
|
2020-04-05 21:16:53 +00:00
|
|
|
"""Singleton config class."""
|
|
|
|
|
2019-10-07 06:52:00 +00:00
|
|
|
pass
|