Created IAC reverse generator
This commit is contained in:
41
src/iac_reverse/generator/sanitize.py
Normal file
41
src/iac_reverse/generator/sanitize.py
Normal file
@@ -0,0 +1,41 @@
|
||||
"""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
|
||||
Reference in New Issue
Block a user