code_template.py 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. from __future__ import annotations
  2. import itertools
  3. import re
  4. import textwrap
  5. from typing import TYPE_CHECKING
  6. if TYPE_CHECKING:
  7. from collections.abc import Mapping, Sequence
  8. # match $identifier or ${identifier} and replace with value in env
  9. # If this identifier is at the beginning of whitespace on a line
  10. # and its value is a list then it is treated as
  11. # block substitution by indenting to that depth and putting each element
  12. # of the list on its own line
  13. # if the identifier is on a line starting with non-whitespace and a list
  14. # then it is comma separated ${,foo} will insert a comma before the list
  15. # if this list is not empty and ${foo,} will insert one after.
  16. class CodeTemplate:
  17. substitution_str = r"(^[^\n\S]*)?\$([^\d\W]\w*|\{,?[^\d\W]\w*\,?})"
  18. substitution = re.compile(substitution_str, re.MULTILINE)
  19. pattern: str
  20. filename: str
  21. @staticmethod
  22. def from_file(filename: str) -> CodeTemplate:
  23. with open(filename) as f:
  24. return CodeTemplate(f.read(), filename)
  25. def __init__(self, pattern: str, filename: str = "") -> None:
  26. self.pattern = pattern
  27. self.filename = filename
  28. def substitute(
  29. self, env: Mapping[str, object] | None = None, **kwargs: object
  30. ) -> str:
  31. if env is None:
  32. env = {}
  33. def lookup(v: str) -> object:
  34. if env is None:
  35. raise AssertionError("env must be non-None")
  36. return kwargs[v] if v in kwargs else env[v]
  37. def indent_lines(indent: str, v: Sequence[object]) -> str:
  38. content = "\n".join(
  39. itertools.chain.from_iterable(str(e).splitlines() for e in v)
  40. )
  41. content = textwrap.indent(content, prefix=indent)
  42. # Remove trailing whitespace on each line
  43. return "\n".join(map(str.rstrip, content.splitlines())).rstrip()
  44. def replace(match: re.Match[str]) -> str:
  45. indent = match.group(1)
  46. key = match.group(2)
  47. comma_before = ""
  48. comma_after = ""
  49. if key[0] == "{":
  50. key = key[1:-1]
  51. if key[0] == ",":
  52. comma_before = ", "
  53. key = key[1:]
  54. if key[-1] == ",":
  55. comma_after = ", "
  56. key = key[:-1]
  57. v = lookup(key)
  58. if indent is not None:
  59. if not isinstance(v, list):
  60. v = [v]
  61. return indent_lines(indent, v)
  62. elif isinstance(v, list):
  63. middle = ", ".join([str(x) for x in v])
  64. if len(v) == 0:
  65. return middle
  66. return comma_before + middle + comma_after
  67. else:
  68. return str(v)
  69. return self.substitution.sub(replace, self.pattern)
  70. if __name__ == "__main__":
  71. c = CodeTemplate(
  72. """\
  73. int foo($args) {
  74. $bar
  75. $bar
  76. $a+$b
  77. }
  78. int commatest(int a${,stuff})
  79. int notest(int a${,empty,})
  80. """
  81. )
  82. print(
  83. c.substitute(
  84. args=["hi", 8],
  85. bar=["what", 7],
  86. a=3,
  87. b=4,
  88. stuff=["things...", "others"],
  89. empty=[],
  90. )
  91. )