code_template.py 2.8 KB

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