Files
SnarfCode/src/iac_reverse/generator/sanitize.py
2026-05-22 00:19:30 -04:00

42 lines
1.2 KiB
Python

"""Identifier sanitization for Terraform resource names.
Converts arbitrary resource names into valid Terraform identifiers
matching the pattern: ^[a-zA-Z_][a-zA-Z0-9_]*$
"""
import re
def sanitize_identifier(name: str) -> str:
"""Convert a resource name to a valid Terraform identifier.
Terraform identifiers must match: ^[a-zA-Z_][a-zA-Z0-9_]*$
Rules applied:
- Replace any character not in [a-zA-Z0-9_] with underscore
- Collapse multiple consecutive underscores into one
- If result starts with a digit, prepend an underscore
- If result is empty or only underscores, return "_resource"
Args:
name: Any string resource name.
Returns:
A valid Terraform identifier derived from the input.
"""
# Replace any non-alphanumeric/underscore character with underscore
result = re.sub(r"[^a-zA-Z0-9_]", "_", name)
# Collapse multiple consecutive underscores into one
result = re.sub(r"_+", "_", result)
# If result is only underscores or empty, return fallback
if not result or result.strip("_") == "":
return "_resource"
# If starts with a digit, prepend underscore
if result[0].isdigit():
result = "_" + result
return result