Files
computer-playbook/utils/roles/entity_name.py
T
kevinveenbirkenbachandClaude Opus 4.7 85f1caccc7 refactor(utils): consolidate role-scoped helpers under utils/roles and split templating
Tighten the utils namespace so each subpackage owns one concern:

- utils/applications/* moves under utils/roles/applications/* (helpers
  that operate on the runtime applications dict and meta/services.yml).
- utils/service_registry.py and utils/database_service.py move under
  utils/roles/applications/services/ as registry.py and database.py.
- utils/entity_name_utils.py becomes utils/roles/entity_name.py.
- utils/invokable.py, utils/valid_deploy_id.py, and the existing
  utils/roles/resource_validation.py group under utils/roles/validation/
  as invokable.py, deploy_id.py, and resources.py.
- utils/templating.py and utils/jinja_strict.py split into
  utils/templating/ansible.py (Templar + TrustedAsTemplate, lookup-env
  shortcut) and utils/templating/jinja.py (vanilla Jinja2 Environment,
  multi-pass strict render).

Every caller in utils, cli, plugins, roles/<role>/{filter,lookup}_plugins,
tests, and the docs that link to the moved files is updated to the new
import paths. Test files mirror the new source layout
(tests/unit/utils/{roles,templating}/...).

New READMEs at utils/cleanup/, utils/roles/, utils/roles/applications/services/,
utils/roles/validation/, and utils/templating/ follow the
documentation.md and readme_md.md guidelines.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-08 03:53:43 +02:00

53 lines
1.6 KiB
Python

from pathlib import Path
from utils import PROJECT_ROOT
from utils.cache.yaml import load_yaml
def load_categories_tree(categories_file):
return load_yaml(categories_file)["roles"]
def flatten_categories(tree, prefix=""):
"""Flattens nested category tree to all possible category paths."""
result = []
for k, v in tree.items():
current = f"{prefix}-{k}" if prefix else k
result.append(current)
if isinstance(v, dict):
for sk, sv in v.items():
if isinstance(sv, dict):
result.extend(flatten_categories({sk: sv}, current))
return result
def get_entity_name(role_name):
"""
Get the entity name from a role name by removing the
longest matching category path from categories.yml.
"""
possible_locations = [
str(Path(str(Path.cwd())) / "roles" / "categories.yml"),
str(PROJECT_ROOT / "roles" / "categories.yml"),
"roles/categories.yml",
]
categories_file = None
for loc in possible_locations:
if Path(loc).exists():
categories_file = loc
break
if not categories_file:
return role_name
categories_tree = load_categories_tree(categories_file)
all_category_paths = flatten_categories(categories_tree)
role_name_lc = role_name.lower()
all_category_paths = [cat.lower() for cat in all_category_paths]
for cat in sorted(all_category_paths, key=len, reverse=True):
if role_name_lc.startswith(cat + "-"):
return role_name[len(cat) + 1 :]
if role_name_lc == cat:
return ""
return role_name