fix: black

This commit is contained in:
egarette@silique.fr 2026-06-21 16:53:52 +02:00
parent ff9b0f00de
commit dc52ad6ad5
5 changed files with 135 additions and 66 deletions

View file

@ -15,6 +15,7 @@ details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
from .ansible import Inventory
from .__version__ import __version__
@ -34,25 +35,31 @@ class RougailOutputAnsible:
self.kwargs = kwargs
def run(self):
output = self.rougailconfig['ansible.output']
if output == 'doc':
output = self.rougailconfig["ansible.output"]
if output == "doc":
from .doc import Doc
data = Doc(self.config, rougailconfig=self.rougailconfig, **self.kwargs)
else:
data = Inventory(self.config, rougailconfig=self.rougailconfig, **self.kwargs)
data = Inventory(
self.config, rougailconfig=self.rougailconfig, **self.kwargs
)
return data.run()
def print(self):
output = self.rougailconfig['ansible.output']
if output == 'doc':
output = self.rougailconfig["ansible.output"]
if output == "doc":
from .doc import Doc
data = Doc(self.config, rougailconfig=self.rougailconfig, **self.kwargs)
else:
data = Inventory(self.config, rougailconfig=self.rougailconfig, **self.kwargs)
data = Inventory(
self.config, rougailconfig=self.rougailconfig, **self.kwargs
)
return data.print()
RougailOutput = RougailOutputAnsible
__all__ = ("RougailOutputAnsible", '__version__')
__all__ = ("RougailOutputAnsible", "__version__")

View file

@ -18,8 +18,10 @@ You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
"""
from rougail.error import DictConsistencyError
from rougail.output_doc.i18n import _
try:
from rougail.output_doc.annotator import Annotator as AnnotatorDoc
except:
@ -27,11 +29,18 @@ except:
if AnnotatorDoc:
class Annotator(AnnotatorDoc):
level = 96
def __init__(self, *args):
super().__init__(*args, force_default_value=True, force_display_unknown_optional_variable=True)
super().__init__(
*args,
force_default_value=True,
force_display_unknown_optional_variable=True,
)
# host_namespace = self.objectspace.rougailconfig["ansible.inventory.host_namespace"]
# namespaces = self.objectspace.parents["."]
# if not namespaces:

View file

@ -38,7 +38,9 @@ class Inventory(RougailOutputJson):
def exporter(self) -> None:
self.host_namespace = self.rougailconfig["ansible.host_namespace"]
self.no_namespace_in_vars = self.rougailconfig["ansible.inventory.no_namespace_in_vars"]
self.no_namespace_in_vars = self.rougailconfig[
"ansible.inventory.no_namespace_in_vars"
]
self.export_warnings = self.rougailconfig["ansible.inventory.export_warnings"]
self.hosts = {}
super().exporter()
@ -47,7 +49,11 @@ class Inventory(RougailOutputJson):
return True
def parse_variable(self, option, child, namespace):
if self.support_namespace and namespace and "ansible_host" in option.information.get("tags", tuple()):
if (
self.support_namespace
and namespace
and "ansible_host" in option.information.get("tags", tuple())
):
hosts = option.value.get()
if not isinstance(hosts, list):
hosts = [hosts]
@ -56,6 +62,7 @@ class Inventory(RougailOutputJson):
else:
self.hosts[namespace] = hosts
super().parse_variable(option, child, namespace)
#
# def manage_errors(self) -> bool:
# if not super().manage_errors():
@ -135,6 +142,7 @@ class Inventory(RougailOutputJson):
ret["_meta"]["hostvars"][host] = {"ansible_host": domain_name}
if self.no_namespace_in_vars:
from rougail.tiramisu import normalize_family
host_namespace = normalize_family(host)
if host_namespace in self.dico:
ret["_meta"]["hostvars"][host].update(
@ -144,7 +152,9 @@ class Inventory(RougailOutputJson):
if host in namespaces:
for namespace in namespaces[host]:
if namespace in self.dico:
ret["_meta"]["hostvars"][host][namespace] = self.dico[namespace]
ret["_meta"]["hostvars"][host][namespace] = (
self.dico[namespace]
)
else:
ret["_meta"]["hostvars"][host].update(self.dico)
if host in extra_vars:

View file

@ -18,6 +18,7 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
from .i18n import _
from pathlib import Path
try:
from ..output_doc.config import OutPuts
except:
@ -75,9 +76,12 @@ ansible:
default: inventory
choices:
- inventory
"""]
""",
]
if doc_outputs:
options[-1] += f"""
options[
-1
] += f"""
- doc
host_namespace: hosts # {_('Namespace with host values')}
@ -99,7 +103,9 @@ ansible:
"""
for output in doc_outputs:
options[-1] += f" - {output}\n"
options[-1] += f"""
options[
-1
] += f"""
collection_type:
description: {_('collection contents')}
choices:

View file

@ -42,7 +42,8 @@ class Doc(RougailOutputDoc):
) -> None:
self.config = config
self.ori_rougailconfig = rougailconfig
self.doc_rougailconfig = {"doc.tabulars.with_commandline": False,
self.doc_rougailconfig = {
"doc.tabulars.with_commandline": False,
"doc.tabulars.with_environment": False,
"main_namespace": None,
"step.output": "ansible",
@ -63,7 +64,11 @@ class Doc(RougailOutputDoc):
super().__init__(config, rougailconfig=self.doc_rougailconfig, **kwargs)
def run(self) -> str:
types = [config.name() for config in self.config if config.name() != self.ori_rougailconfig["ansible.host_namespace"]]
types = [
config.name()
for config in self.config
if config.name() != self.ori_rougailconfig["ansible.host_namespace"]
]
self.root_config = self.config
self.load()
self.load_formatter()
@ -78,37 +83,51 @@ class Doc(RougailOutputDoc):
config.property.read_only()
hidden = CommentedMap()
config.property.remove("mandatory")
self._example_parse_family(config.value.get(), hidden, dump_type="hidden", with_true_path=True)
self._example_parse_family(
config.value.get(), hidden, dump_type="hidden", with_true_path=True
)
config.property.read_write()
self.ansible_name = self.ori_rougailconfig["ansible.doc.project_name"]
self._build_defaults(config)
# FIXME self._build_vars(examples)
# Description
author = self.ori_rougailconfig["ansible.doc.author"]
name = f'{author}.{self.ansible_name}'
name = f"{author}.{self.ansible_name}"
help_ = None
description = None
if self.ansible_name in self.informations:
if "help" in self.informations[self.ansible_name]["informations"]:
help_ = self.informations[self.ansible_name]["informations"].pop("help")
if "description" in self.informations[self.ansible_name]["informations"]:
description = self.informations[self.ansible_name]["informations"]["description"]
description = self.informations[self.ansible_name]["informations"][
"description"
]
title = f"{name} - {description}"
else:
title = name
else:
title = name
datas = [self.formatter.title(title, 1, collapse=False)]
datas.append(_('This repository contains the {0} Ansible collection.').format(self.formatter.prop(name, False, False, False)))
datas.append(
_("This repository contains the {0} Ansible collection.").format(
self.formatter.prop(name, False, False, False)
)
)
if help_:
datas.append("\n".join(help_))
self.doc_rougailconfig["doc.title_level"] = 2
for type_ in self.informations:
current_informations = self.informations[type_]["informations"]
if "description" in current_informations:
current_informations["description"] = _('The group variables "{0}" - {1}').format(current_informations["name"], current_informations["description"])
current_informations["description"] = _(
'The group variables "{0}" - {1}'
).format(
current_informations["name"], current_informations["description"]
)
else:
current_informations["description"] = _("The group variables {0}").format(current_informations["name"])
current_informations["description"] = _(
"The group variables {0}"
).format(current_informations["name"])
datas.append(self.formatter.title(_("Variables"), 2, collapse=False))
self.formatter.options()
datas.extend(self.formatter.dict_to_dict(self.informations, level=3))
@ -128,7 +147,7 @@ class Doc(RougailOutputDoc):
found = False
if not found:
continue
y["vars"][t] = f'{{{{ my_{t} }}}}'
y["vars"][t] = f"{{{{ my_{t} }}}}"
#
rougail_version = float(SUPPORTED_VERSION[-1])
if "version" in types:
@ -137,7 +156,7 @@ class Doc(RougailOutputDoc):
key = "version"
if hidden:
msg = ("Hidden variables can only be modified within a structure file.")
msg = "Hidden variables can only be modified within a structure file."
datas.append(self.formatter.display_family_informations([msg]))
end_family = self.formatter.end_family(level=2, collapse=False)
if end_family:
@ -146,7 +165,7 @@ class Doc(RougailOutputDoc):
datas.append(self.formatter.title(_("Example Playbook with Rougail"), 3))
structural = {key: rougail_version}
for t in types:
structural[f'my_{t}'] = {'type': t}
structural[f"my_{t}"] = {"type": t}
if structural:
customize = CommentedMap()
old_config = self.config
@ -155,26 +174,34 @@ class Doc(RougailOutputDoc):
test_config.property.remove("mandatory")
test_config = test_config.forcepermissive
self.config = test_config
self._example_parse_family(test_config.value.get(), customize, dump_type="empty", with_secret_manager=False, with_true_path=True)
self._example_parse_family(
test_config.value.get(),
customize,
dump_type="empty",
with_secret_manager=False,
with_true_path=True,
)
self.config = old_config
datas.append(_("Add to your structural file something like:"))
datas.append(self.formatter.yaml(dump(structural), yaml_version="1.2"))
for t in types:
if t in customize and t in hidden:
structural[f'my_{t}'].update(customize[t])
structural[f"my_{t}"].update(customize[t])
datas.append(_("Customizing hidden variables in structure file:"))
datas.append(self.formatter.yaml(dump(structural), yaml_version="1.2"))
text = [_('Do not forget to add Rougail structure file as Rougail types.')]
text = [_("Do not forget to add Rougail structure file as Rougail types.")]
datas.append(self.formatter.display_family_informations(text))
user_data = {}
for t in types:
if t in examples:
user_data.update({f'my_{t}': examples[t]})
user_data.update({f"my_{t}": examples[t]})
if user_data:
datas.append(_("For example you can add an YAML user data with something like:"))
datas.append(
_("For example you can add an YAML user data with something like:")
)
datas.append(self.formatter.yaml(dump(user_data)))
datas.append(_("Add to your Play:"))
_dump = "\n".join([d[2:] for d in (" " + dump(yaml)).split('\n')])
_dump = "\n".join([d[2:] for d in (" " + dump(yaml)).split("\n")])
datas.append(self.formatter.yaml(_dump))
#
examples = self._gen_doc_examples(config, True)
@ -189,12 +216,16 @@ class Doc(RougailOutputDoc):
for y in yaml:
if not y["vars"]:
del y["vars"][t]
_dump = "\n".join([d[2:] for d in (" " + dump(yaml)).split('\n')])
_dump = "\n".join([d[2:] for d in (" " + dump(yaml)).split("\n")])
end_family = self.formatter.end_family(level=3)
if end_family:
datas.append(end_family)
datas.append(self.formatter.title(_("Example Playbook without Rougail"), 3))
datas.append(self.formatter.display_family_informations([_('The variables will not be properly validated without Rougail.')]))
datas.append(
self.formatter.display_family_informations(
[_("The variables will not be properly validated without Rougail.")]
)
)
datas.append(self.formatter.yaml(_dump))
end_family = self.formatter.end_family(level=3)
if end_family:
@ -224,7 +255,8 @@ class Doc(RougailOutputDoc):
playbook_description = playbooks[playbook_name]
else:
playbook_description = f"Collection | {playbook_import}"
yaml = {"name": playbook_description,
yaml = {
"name": playbook_description,
"hosts": "servers",
"vars": {},
}
@ -233,7 +265,8 @@ class Doc(RougailOutputDoc):
if self.collection_type != "playbooks" and not done:
roles_dir = self.root_directory / "roles"
if roles_dir.is_dir():
yaml = {"name": description,
yaml = {
"name": description,
"hosts": "servers",
"vars": {},
}
@ -245,7 +278,11 @@ class Doc(RougailOutputDoc):
yaml["roles"].append({"role": f"{name}.{role_name}"})
lst = [yaml]
if not done:
raise Exception(_('Unable to find a Playbook in playbooks/ directory or a role in roles/ directory'))
raise Exception(
_(
"Unable to find a Playbook in playbooks/ directory or a role in roles/ directory"
)
)
return lst
def _build_defaults(self, config):
@ -266,5 +303,5 @@ class Doc(RougailOutputDoc):
else:
filedir = self.root_directory / write_type
filedir.mkdir(exist_ok=True)
with (filedir / "main.yml").open('w') as fh:
with (filedir / "main.yml").open("w") as fh:
fh.write(f"---\n{dump(results)}\n")