template_builders.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. """Functions used to generate source files during build time"""
  2. import os
  3. import methods
  4. def parse_template(inherits, source, delimiter):
  5. script_template = {
  6. "inherits": inherits,
  7. "name": "",
  8. "description": "",
  9. "version": "",
  10. "script": "",
  11. "space-indent": "4",
  12. }
  13. meta_prefix = delimiter + " meta-"
  14. meta = ["name", "description", "version", "space-indent"]
  15. with open(source, "r", encoding="utf-8") as f:
  16. lines = f.readlines()
  17. for line in lines:
  18. if line.startswith(meta_prefix):
  19. line = line[len(meta_prefix) :]
  20. for m in meta:
  21. if line.startswith(m):
  22. strip_length = len(m) + 1
  23. script_template[m] = line[strip_length:].strip()
  24. else:
  25. script_template["script"] += line
  26. if script_template["space-indent"] != "":
  27. indent = " " * int(script_template["space-indent"])
  28. script_template["script"] = script_template["script"].replace(indent, "_TS_")
  29. if script_template["name"] == "":
  30. script_template["name"] = os.path.splitext(os.path.basename(source))[0].replace("_", " ").title()
  31. script_template["script"] = (
  32. script_template["script"].replace('"', '\\"').lstrip().replace("\n", "\\n").replace("\t", "_TS_")
  33. )
  34. return (
  35. f'{{ String("{script_template["inherits"]}"), '
  36. + f'String("{script_template["name"]}"), '
  37. + f'String("{script_template["description"]}"), '
  38. + f'String("{script_template["script"]}") }},'
  39. )
  40. def make_templates(target, source, env):
  41. delimiter = "#" # GDScript single line comment delimiter by default.
  42. if source:
  43. ext = os.path.splitext(str(source[0]))[1]
  44. if ext == ".cs":
  45. delimiter = "//"
  46. parsed_templates = []
  47. for filepath in source:
  48. filepath = str(filepath)
  49. node_name = os.path.basename(os.path.dirname(filepath))
  50. parsed_templates.append(parse_template(node_name, filepath, delimiter))
  51. parsed_template_string = "\n\t".join(parsed_templates)
  52. with methods.generated_wrapper(str(target[0])) as file:
  53. file.write(f"""\
  54. #include "core/object/object.h"
  55. #include "core/object/script_language.h"
  56. inline constexpr int TEMPLATES_ARRAY_SIZE = {len(parsed_templates)};
  57. static const struct ScriptLanguage::ScriptTemplate TEMPLATES[TEMPLATES_ARRAY_SIZE] = {{
  58. {parsed_template_string}
  59. }};
  60. """)