code_template.py 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  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. assert env is not None
  35. return kwargs[v] if v in kwargs else env[v]
  36. def indent_lines(indent: str, v: Sequence[object]) -> str:
  37. content = "\n".join(
  38. itertools.chain.from_iterable(str(e).splitlines() for e in v)
  39. )
  40. content = textwrap.indent(content, prefix=indent)
  41. # Remove trailing whitespace on each line
  42. return "\n".join(map(str.rstrip, content.splitlines())).rstrip()
  43. def replace(match: re.Match[str]) -> str:
  44. indent = match.group(1)
  45. key = match.group(2)
  46. comma_before = ""
  47. comma_after = ""
  48. if key[0] == "{":
  49. key = key[1:-1]
  50. if key[0] == ",":
  51. comma_before = ", "
  52. key = key[1:]
  53. if key[-1] == ",":
  54. comma_after = ", "
  55. key = key[:-1]
  56. v = lookup(key)
  57. if indent is not None:
  58. if not isinstance(v, list):
  59. v = [v]
  60. return indent_lines(indent, v)
  61. elif isinstance(v, list):
  62. middle = ", ".join([str(x) for x in v])
  63. if len(v) == 0:
  64. return middle
  65. return comma_before + middle + comma_after
  66. else:
  67. return str(v)
  68. return self.substitution.sub(replace, self.pattern)
  69. if __name__ == "__main__":
  70. c = CodeTemplate(
  71. """\
  72. int foo($args) {
  73. $bar
  74. $bar
  75. $a+$b
  76. }
  77. int commatest(int a${,stuff})
  78. int notest(int a${,empty,})
  79. """
  80. )
  81. print(
  82. c.substitute(
  83. args=["hi", 8],
  84. bar=["what", 7],
  85. a=3,
  86. b=4,
  87. stuff=["things...", "others"],
  88. empty=[],
  89. )
  90. )