import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TARGET_DIRS = ['0_proyecto', '1_trasfondo', '2_atlas', '3_personajes', '4_diegesis', '5_aventuras']
OUTPUT_FILE = os.path.join(BASE_DIR, 'indice.yaml')
def get_slug(filename):
"""Obtiene el slug del nombre de archivo."""
return os.path.splitext(filename)[0]
def build_tree(base_path):
"""Construye recursivamente el árbol de directorios y archivos."""
try:
items = sorted(os.listdir(base_path))
except FileNotFoundError:
return {}
has_subdir = any(os.path.isdir(os.path.join(base_path, item)) for item in items)
if not has_subdir:
slugs = []
for item in items:
if item.endswith('.md'):
slugs.append(get_slug(item))
return slugs
else:
tree = {}
for item in items:
path = os.path.join(base_path, item)
if os.path.isdir(path):
subtree = build_tree(path)
if subtree:
tree[item] = subtree
elif item.endswith('.md'):
slug = get_slug(item)
tree[slug] = slug
return tree
def to_yaml(data, indent=0):
"""Convierte la estructura de datos a formato YAML."""
lines = []
prefix = ' ' * indent
if isinstance(data, list):
for item in data:
lines.append(f"{prefix}- {item}")
elif isinstance(data, dict):
for key, value in data.items():
if isinstance(value, (dict, list)):
lines.append(f"{prefix}{key}:")
lines.extend(to_yaml(value, indent + 2))
else:
lines.append(f"{prefix}{key}: {value}")
return lines
def main():
"""Función principal que genera el índice."""
full_tree = {}
for dir_name in TARGET_DIRS:
full_path = os.path.join(BASE_DIR, dir_name)
if os.path.exists(full_path):
full_tree[dir_name] = build_tree(full_path)
yaml_lines = to_yaml(full_tree)
with open(OUTPUT_FILE, 'w', encoding='utf-8') as f:
f.write('\n'.join(yaml_lines))
f.write('\n')
print(f"Generado {OUTPUT_FILE}")
if __name__ == '__main__':
main()