Restructured CLI logic

This commit is contained in:
2025-07-10 21:26:44 +02:00
parent 8457325b5c
commit c160c58a5c
44 changed files with 97 additions and 155 deletions

0
cli/fix/__init__.py Normal file
View File

47
cli/fix/ini_py.py Normal file
View File

@@ -0,0 +1,47 @@
#!/usr/bin/env python3
"""
This script creates __init__.py files in every subdirectory under the specified
folder relative to the project root.
"""
import os
import argparse
def create_init_files(root_folder):
"""
Walk through all subdirectories of root_folder and create an __init__.py file
in each directory if it doesn't already exist.
"""
for dirpath, dirnames, filenames in os.walk(root_folder):
init_file = os.path.join(dirpath, '__init__.py')
if not os.path.exists(init_file):
open(init_file, 'w').close()
print(f"Created: {init_file}")
else:
print(f"Skipped (already exists): {init_file}")
def main():
parser = argparse.ArgumentParser(
description='Create __init__.py files in every subdirectory.'
)
parser.add_argument(
'folder',
help='Relative path to the target folder (e.g., cli/fix)'
)
args = parser.parse_args()
# Determine the absolute path based on the current working directory
root_folder = os.path.abspath(args.folder)
if not os.path.isdir(root_folder):
print(f"Error: The folder '{args.folder}' does not exist or is not a directory.")
exit(1)
create_init_files(root_folder)
if __name__ == '__main__':
main()

57
cli/fix/tabs.py Normal file
View File

@@ -0,0 +1,57 @@
#!/usr/bin/env python3
import os
import argparse
from pathlib import Path
FILES_FIXED = []
def fix_tabs_in_file(file_path):
"""Replaces tab characters with two spaces in the specified file."""
with open(file_path, "r", encoding="utf-8") as f:
lines = f.readlines()
if any('\t' in line for line in lines):
fixed_lines = [line.replace('\t', ' ') for line in lines]
with open(file_path, "w", encoding="utf-8") as f:
f.writelines(fixed_lines)
FILES_FIXED.append(str(file_path))
def find_yml_files(path):
"""Yield all .yml files under a given path recursively."""
for file in path.rglob("*.yml"):
if file.is_file():
yield file
def main():
parser = argparse.ArgumentParser(
description="Fix tab characters in all .yml files under a given path (recursively)."
)
parser.add_argument(
"path",
nargs="?",
default="./",
help="Base path to search for .yml files (default: ./)"
)
args = parser.parse_args()
base_path = Path(args.path).resolve()
if not base_path.exists():
print(f"❌ Path does not exist: {base_path}")
exit(1)
print(f"🔍 Searching for .yml files under: {base_path}\n")
for yml_file in find_yml_files(base_path):
fix_tabs_in_file(yml_file)
if FILES_FIXED:
print("✅ Fixed tab characters in the following files:")
for f in FILES_FIXED:
print(f" - {f}")
else:
print("✅ No tabs found in any .yml files.")
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,83 @@
#!/usr/bin/env python3
"""
Script to ensure each Ansible role under ../roles/ with a given prefix has a vars/main.yml
containing the correct application_id. Can preview actions or overwrite mismatches.
"""
import argparse
import sys
import yaml
from pathlib import Path
def process_role(role_dir: Path, prefix: str, preview: bool, overwrite: bool):
name = role_dir.name
if not name.startswith(prefix):
return
# Expected application_id is role name minus prefix
expected_id = name[len(prefix):]
vars_dir = role_dir / "vars"
vars_file = vars_dir / "main.yml"
if vars_file.exists():
# Load existing variables
try:
existing = yaml.safe_load(vars_file.read_text()) or {}
except yaml.YAMLError as e:
print(f"Error parsing YAML in {vars_file}: {e}", file=sys.stderr)
return
actual_id = existing.get("application_id")
if actual_id == expected_id:
# Already correct
return
if overwrite:
# Update only application_id
existing["application_id"] = expected_id
if preview:
print(f"[PREVIEW] Would update {vars_file}: application_id -> {expected_id}")
else:
with open(vars_file, "w") as f:
yaml.safe_dump(existing, f, default_flow_style=False, sort_keys=False)
print(f"Updated {vars_file}: application_id -> {expected_id}")
else:
print(f"Mismatch in {vars_file}: application_id='{actual_id}', expected='{expected_id}'")
else:
# Create new vars/main.yml
if preview:
print(f"[PREVIEW] Would create {vars_file} with application_id: {expected_id}")
else:
vars_dir.mkdir(parents=True, exist_ok=True)
content = {"application_id": expected_id}
with open(vars_file, "w") as f:
yaml.safe_dump(content, f, default_flow_style=False, sort_keys=False)
print(f"Created {vars_file} with application_id: {expected_id}")
def main():
parser = argparse.ArgumentParser(
description="Ensure vars/main.yml for roles with a given prefix has correct application_id"
)
parser.add_argument(
"--prefix", required=True,
help="Role name prefix to filter (e.g. 'web-', 'svc-', 'desk-')"
)
parser.add_argument(
"--preview", action="store_true",
help="Show what would be done without making changes"
)
parser.add_argument(
"--overwrite", action="store_true",
help="If vars/main.yml exists but application_id mismatches, overwrite only that key"
)
args = parser.parse_args()
# Determine roles directory relative to this script
script_dir = Path(__file__).resolve().parent
roles_dir = (script_dir.parent / "roles").resolve()
if not roles_dir.is_dir():
print(f"Roles directory not found: {roles_dir}", file=sys.stderr)
sys.exit(1)
for role in sorted(roles_dir.iterdir()):
if role.is_dir():
process_role(role, args.prefix, args.preview, args.overwrite)
if __name__ == "__main__":
main()