hcl_variables.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. """A small, fail-closed reader for OpenTofu `variable` blocks.
  2. It is not an HCL parser. It reads exactly the shapes this repository uses in
  3. `variable` blocks and raises HclError on anything else, so a new shape cannot
  4. slip past the settings coverage test unseen.
  5. Understood:
  6. - `variable "name" { ... }` at the top level of a .tf file, with the
  7. attributes type, default, description, sensitive, nullable and any number of
  8. `validation { ... }` blocks.
  9. - Strings with backslash escapes, `#`, `//` and `/* */` comments, and
  10. multi-line expressions in brackets, braces or parentheses.
  11. - Literal values: strings, numbers, true/false/null, and lists and objects
  12. built from them (for defaults, and for the assignments of a tfvars file read
  13. by `parse_assignments`). A comment may follow any value.
  14. Refused (HclError): heredocs, `${` or `%{` template sequences inside a string,
  15. unbalanced brackets, an unknown attribute or block inside a variable, a
  16. repeated attribute, a duplicate variable name in one directory, a variable
  17. label that is not a plain quoted name.
  18. """
  19. from __future__ import annotations
  20. import json
  21. import re
  22. from dataclasses import dataclass, field
  23. from pathlib import Path
  24. NAME_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_-]*")
  25. ATTRIBUTES = frozenset({"type", "default", "description", "sensitive", "nullable"})
  26. OPEN = {"{": "}", "[": "]", "(": ")"}
  27. CLOSE = frozenset(OPEN.values())
  28. class HclError(ValueError):
  29. """The file has a shape this reader does not understand."""
  30. @dataclass
  31. class Variable:
  32. name: str
  33. type: str | None = None
  34. has_default: bool = False
  35. default: object = None
  36. sensitive: bool = False
  37. description: str | None = None
  38. validations: int = 0
  39. source: str = ""
  40. raw: dict = field(default_factory=dict)
  41. def _skip_string(text: str, i: int, lenient: bool = False) -> int:
  42. """Return the index after the string that starts at text[i] == '"'.
  43. Lenient mode is for blocks that are not variables (resources and so on),
  44. which are only skipped, never read: template sequences are stepped over.
  45. """
  46. i += 1
  47. while i < len(text):
  48. c = text[i]
  49. if c == "\\":
  50. i += 2
  51. continue
  52. if c == '"':
  53. return i + 1
  54. if c in "$%" and text[i + 1 : i + 2] == "{":
  55. if not lenient:
  56. raise HclError("template sequence inside a string is not understood")
  57. i = _read_balanced(text, i + 1, lenient=True)
  58. continue
  59. if c == "\n":
  60. raise HclError("newline inside a quoted string")
  61. i += 1
  62. raise HclError("unterminated string")
  63. def _skip_ws_comments(text: str, i: int, newlines: bool = True) -> int:
  64. while i < len(text):
  65. c = text[i]
  66. if c in " \t\r" or (newlines and c == "\n"):
  67. i += 1
  68. elif c == "#" or text.startswith("//", i):
  69. while i < len(text) and text[i] != "\n":
  70. i += 1
  71. elif text.startswith("/*", i):
  72. end = text.find("*/", i + 2)
  73. if end < 0:
  74. raise HclError("unterminated block comment")
  75. i = end + 2
  76. else:
  77. break
  78. return i
  79. HEREDOC_RE = re.compile(r"<<-?([A-Za-z_][A-Za-z0-9_]*)[ \t]*\n")
  80. def _skip_heredoc(text: str, i: int) -> int:
  81. m = HEREDOC_RE.match(text, i)
  82. if not m:
  83. raise HclError("heredoc marker is not understood")
  84. end = re.compile(rf"^[ \t]*{m.group(1)}[ \t]*$", re.MULTILINE).search(text, m.end())
  85. if not end:
  86. raise HclError("unterminated heredoc")
  87. return end.end()
  88. def _read_balanced(text: str, i: int, lenient: bool = False) -> int:
  89. """text[i] is an opener; return the index after its matching closer."""
  90. stack = [OPEN[text[i]]]
  91. i += 1
  92. while i < len(text):
  93. c = text[i]
  94. if c == '"':
  95. i = _skip_string(text, i, lenient)
  96. continue
  97. if c == "#" or text.startswith("//", i) or text.startswith("/*", i):
  98. i = _skip_ws_comments(text, i)
  99. continue
  100. if text.startswith("<<", i):
  101. if not lenient:
  102. raise HclError("heredoc is not understood")
  103. i = _skip_heredoc(text, i)
  104. continue
  105. if c in OPEN:
  106. stack.append(OPEN[c])
  107. elif c in CLOSE:
  108. if not stack or stack.pop() != c:
  109. raise HclError("mismatched bracket")
  110. if not stack:
  111. return i + 1
  112. i += 1
  113. raise HclError("unbalanced bracket")
  114. def _read_expression(text: str, i: int) -> int:
  115. """Read an expression to the end of its logical line; return the end index."""
  116. while i < len(text):
  117. c = text[i]
  118. if c == "\n":
  119. return i
  120. if c == '"':
  121. i = _skip_string(text, i)
  122. elif c in OPEN:
  123. i = _read_balanced(text, i)
  124. elif c in CLOSE:
  125. raise HclError("unexpected closing bracket")
  126. elif c == "#" or text.startswith("//", i) or text.startswith("/*", i):
  127. i = _skip_ws_comments(text, i, newlines=False)
  128. elif text.startswith("<<", i):
  129. raise HclError("heredoc is not understood")
  130. else:
  131. i += 1
  132. return i
  133. NUMBER_RE = re.compile(r"-?[0-9]+(\.[0-9]+)?")
  134. KEY_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_-]*")
  135. MAX_DEPTH = 8
  136. def _parse_value(text: str, i: int, depth: int = 0):
  137. """Parse one literal at text[i]; return (value, index after it)."""
  138. if depth > MAX_DEPTH:
  139. raise HclError("literal is nested too deeply")
  140. i = _skip_ws_comments(text, i)
  141. if i >= len(text):
  142. raise HclError("expected a value")
  143. c = text[i]
  144. if c == '"':
  145. end = _skip_string(text, i)
  146. return json.loads(text[i:end]), end
  147. if c == "[":
  148. out: list = []
  149. i += 1
  150. while True:
  151. i = _skip_ws_comments(text, i)
  152. if text.startswith("]", i):
  153. return out, i + 1
  154. value, i = _parse_value(text, i, depth + 1)
  155. out.append(value)
  156. i = _skip_ws_comments(text, i)
  157. if text.startswith(",", i):
  158. i += 1
  159. elif not text.startswith("]", i):
  160. raise HclError("list items must be separated by commas")
  161. if c == "{":
  162. obj: dict = {}
  163. i += 1
  164. while True:
  165. i = _skip_ws_comments(text, i)
  166. if text.startswith("}", i):
  167. return obj, i + 1
  168. if text.startswith('"', i):
  169. end = _skip_string(text, i)
  170. key = json.loads(text[i:end])
  171. i = end
  172. else:
  173. m = KEY_RE.match(text, i)
  174. if not m:
  175. raise HclError("object key is not understood")
  176. key, i = m.group(0), m.end()
  177. i = _skip_ws_comments(text, i, newlines=False)
  178. if not (text.startswith("=", i) or text.startswith(":", i)):
  179. raise HclError(f"object key {key!r} has no value")
  180. if key in obj:
  181. raise HclError(f"object key {key!r} is repeated")
  182. obj[key], i = _parse_value(text, i + 1, depth + 1)
  183. i = _skip_ws_comments(text, i, newlines=False)
  184. if text.startswith(",", i):
  185. i += 1
  186. elif i < len(text) and text[i] == "}":
  187. continue
  188. elif i < len(text) and text[i] != "\n":
  189. raise HclError("object entries are separated by a comma or a new line")
  190. for word, value in (("true", True), ("false", False), ("null", None)):
  191. if text.startswith(word, i) and not re.match(
  192. r"[A-Za-z0-9_.-]", text[i + len(word) : i + len(word) + 1]
  193. ):
  194. return value, i + len(word)
  195. m = NUMBER_RE.match(text, i)
  196. if m and not re.match(r"[A-Za-z0-9_.-]", text[m.end() : m.end() + 1]):
  197. s = m.group(0)
  198. return (float(s) if "." in s else int(s)), m.end()
  199. raise HclError(f"not a simple literal: {text[i : i + 30]!r}")
  200. def _literal(expr: str):
  201. """Evaluate a literal expression. Anything else is an HclError."""
  202. value, end = _parse_value(expr, 0)
  203. if _skip_ws_comments(expr, end) != len(expr):
  204. raise HclError(f"trailing text after a value: {expr[end:].strip()[:30]!r}")
  205. return value
  206. def parse_assignments(text: str, source: str = "<text>") -> dict:
  207. """The top-level `name = literal` lines of a tfvars-style file.
  208. Fails closed: a block, a heredoc, a repeated name, a value that is not a
  209. simple literal, or anything else on a top-level line is an HclError.
  210. """
  211. out: dict = {}
  212. i = 0
  213. while True:
  214. i = _skip_ws_comments(text, i)
  215. if i >= len(text):
  216. return out
  217. m = NAME_RE.match(text, i)
  218. if not m:
  219. raise HclError(f"{source}: unexpected text at top level")
  220. name = m.group(0)
  221. i = _skip_ws_comments(text, m.end(), newlines=False)
  222. if not text.startswith("=", i) or text.startswith("==", i):
  223. raise HclError(f"{source}: {name}: expected '=' (blocks are not understood)")
  224. if name in out:
  225. raise HclError(f"{source}: {name} is assigned twice")
  226. start = _skip_ws_comments(text, i + 1, newlines=False)
  227. end = _read_expression(text, start)
  228. if not text[start:end].strip():
  229. raise HclError(f"{source}: {name}: empty value")
  230. try:
  231. out[name] = _literal(text[start:end])
  232. except HclError as exc:
  233. raise HclError(f"{source}: {name}: {exc}") from exc
  234. i = end
  235. def _normalize_type(expr: str) -> str:
  236. """Compact a type expression; a newline between attributes is a comma."""
  237. out = re.sub(r"\s*\n\s*", ",", expr.strip())
  238. out = re.sub(r"\s+", "", out)
  239. out = re.sub(r",+", ",", out)
  240. return re.sub(r"([{(\[]),|,([})\]])", r"\1\2", out)
  241. def _parse_body(body: str, name: str, source: str) -> Variable:
  242. var = Variable(name=name, source=source)
  243. seen: set[str] = set()
  244. i = 0
  245. while True:
  246. i = _skip_ws_comments(body, i)
  247. if i >= len(body):
  248. break
  249. m = NAME_RE.match(body, i)
  250. if not m:
  251. raise HclError(f"{source}: variable {name}: unexpected text in body")
  252. key = m.group(0)
  253. i = _skip_ws_comments(body, m.end(), newlines=False)
  254. if body.startswith("=", i) and not body.startswith("==", i):
  255. if key not in ATTRIBUTES:
  256. raise HclError(f"{source}: variable {name}: unknown attribute {key}")
  257. if key in seen:
  258. raise HclError(f"{source}: variable {name}: repeated attribute {key}")
  259. seen.add(key)
  260. start = _skip_ws_comments(body, i + 1, newlines=False)
  261. end = _read_expression(body, start)
  262. expr = body[start:end].strip()
  263. if not expr:
  264. raise HclError(f"{source}: variable {name}: empty {key}")
  265. var.raw[key] = expr
  266. if key == "type":
  267. var.type = _normalize_type(expr)
  268. elif key == "default":
  269. var.has_default = True
  270. var.default = _literal(expr)
  271. elif key == "sensitive":
  272. if expr not in ("true", "false"):
  273. raise HclError(
  274. f"{source}: variable {name}: sensitive must be a bool literal"
  275. )
  276. var.sensitive = expr == "true"
  277. elif key == "description":
  278. var.description = _literal(expr)
  279. i = end
  280. elif body.startswith("{", i):
  281. if key != "validation":
  282. raise HclError(f"{source}: variable {name}: unknown block {key}")
  283. i = _read_balanced(body, i)
  284. var.validations += 1
  285. else:
  286. raise HclError(f"{source}: variable {name}: cannot read {key!r}")
  287. if var.type is None:
  288. raise HclError(f"{source}: variable {name}: no type (every variable is typed)")
  289. return var
  290. def parse_variables(text: str, source: str = "<text>") -> list[Variable]:
  291. """Return every top-level `variable` block in one .tf file's text."""
  292. out: list[Variable] = []
  293. i = 0
  294. while True:
  295. i = _skip_ws_comments(text, i)
  296. if i >= len(text):
  297. return out
  298. m = NAME_RE.match(text, i)
  299. if not m:
  300. raise HclError(f"{source}: unexpected text at top level")
  301. keyword = m.group(0)
  302. i = _skip_ws_comments(text, m.end(), newlines=False)
  303. labels: list[str] = []
  304. while text.startswith('"', i):
  305. end = _skip_string(text, i)
  306. labels.append(json.loads(text[i:end]))
  307. i = _skip_ws_comments(text, end, newlines=False)
  308. if text.startswith("=", i):
  309. # A top-level attribute (not valid in .tf, tolerated in tfvars-like text).
  310. raise HclError(f"{source}: top-level attribute {keyword} is not understood")
  311. if not text.startswith("{", i):
  312. raise HclError(f"{source}: block {keyword} has no body")
  313. end = _read_balanced(text, i, lenient=keyword != "variable")
  314. if keyword == "variable":
  315. if len(labels) != 1 or not NAME_RE.fullmatch(labels[0]):
  316. raise HclError(f"{source}: variable block needs one plain name label")
  317. out.append(_parse_body(text[i + 1 : end - 1], labels[0], source))
  318. i = end
  319. def variables_in_dir(directory: Path) -> dict[str, Variable]:
  320. """All variables declared in the top-level *.tf files of a directory."""
  321. found: dict[str, Variable] = {}
  322. for tf in sorted(directory.glob("*.tf")):
  323. for var in parse_variables(tf.read_text(encoding="utf-8"), tf.name):
  324. if var.name in found:
  325. raise HclError(f"{directory}: duplicate variable {var.name}")
  326. found[var.name] = var
  327. return found
  328. def variable_directories(root: Path) -> list[Path]:
  329. """Every stack and module directory that holds .tf files, sorted."""
  330. dirs = []
  331. for top in ("stacks", "modules"):
  332. base = root / top
  333. if not base.is_dir():
  334. continue
  335. for d in sorted(p for p in base.iterdir() if p.is_dir()):
  336. if any(d.glob("*.tf")):
  337. dirs.append(d)
  338. else:
  339. # modules/<provider>/<role>, such as modules/aws/vpc, and
  340. # stacks/<provider>/<NN-name>, such as stacks/aws/10-access.
  341. for sub in sorted(q for q in d.iterdir() if q.is_dir()):
  342. if not sub.name.startswith(".") and any(sub.glob("*.tf")):
  343. dirs.append(sub)
  344. return dirs