codegen.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. #!/usr/bin/env python3
  2. # Copyright (c) 2022 Project CHIP Authors
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import logging
  16. import sys
  17. import click
  18. try:
  19. import coloredlogs
  20. _has_coloredlogs = True
  21. except ImportError:
  22. _has_coloredlogs = False
  23. try:
  24. from matter_idl.matter_idl_parser import CreateParser
  25. except ImportError:
  26. import os
  27. sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), 'py_matter_idl')))
  28. from matter_idl.matter_idl_parser import CreateParser
  29. # isort: off
  30. from matter_idl.generators import FileSystemGeneratorStorage, GeneratorStorage
  31. from matter_idl.generators.registry import CodeGenerator, GENERATORS
  32. class ListGeneratedFilesStorage(GeneratorStorage):
  33. """
  34. A storage that prints out file names that would have content in them.
  35. """
  36. def __init__(self):
  37. super().__init__()
  38. def get_existing_data(self, relative_path: str):
  39. return None # stdout has no pre-existing data
  40. def write_new_data(self, relative_path: str, content: str):
  41. print(relative_path)
  42. # Supported log levels, mapping string values required for argument
  43. # parsing into logging constants
  44. __LOG_LEVELS__ = {
  45. 'debug': logging.DEBUG,
  46. 'info': logging.INFO,
  47. 'warn': logging.WARN,
  48. 'fatal': logging.FATAL,
  49. }
  50. @click.command()
  51. @click.option(
  52. '--log-level',
  53. default='INFO',
  54. type=click.Choice(__LOG_LEVELS__.keys(), case_sensitive=False),
  55. help='Determines the verbosity of script output')
  56. @click.option(
  57. '--generator', '-g',
  58. default='java-jni',
  59. help='What code generator to run. The choices are: '+'|'.join(GENERATORS.keys())+'. ' +
  60. 'When using custom, provide the plugin path using `--generator custom:<path_to_plugin>:<plugin_module_name>` syntax. ' +
  61. 'For example, `--generator custom:./my_plugin:my_plugin_module` will load `./my_plugin/my_plugin_module/__init.py__` ' +
  62. 'that defines a subclass of CodeGenerator named CustomGenerator.')
  63. @click.option(
  64. '--option',
  65. multiple=True,
  66. help="Extra generator options, of the form: --option key:value")
  67. @click.option(
  68. '--output-dir',
  69. type=click.Path(exists=False),
  70. default=".",
  71. help='Where to generate the code')
  72. @click.option(
  73. '--dry-run',
  74. default=False,
  75. is_flag=True,
  76. help='If to actually generate')
  77. @click.option(
  78. '--name-only',
  79. default=False,
  80. is_flag=True,
  81. help='Output just a list of file names that would be generated')
  82. @click.option(
  83. '--expected-outputs',
  84. type=click.Path(exists=True),
  85. default=None,
  86. help='A file containing all expected outputs. Script will fail if outputs do not match')
  87. @click.argument(
  88. 'idl_path',
  89. type=click.Path(exists=True))
  90. def main(log_level, generator, option, output_dir, dry_run, name_only, expected_outputs, idl_path):
  91. """
  92. Parses MATTER IDL files (.matter) and performs SDK code generation
  93. as set up by the program arguments.
  94. """
  95. if _has_coloredlogs:
  96. coloredlogs.install(level=__LOG_LEVELS__[
  97. log_level], fmt='%(asctime)s %(levelname)-7s %(message)s')
  98. else:
  99. logging.basicConfig(
  100. level=__LOG_LEVELS__[log_level],
  101. format='%(asctime)s %(levelname)-7s %(message)s',
  102. datefmt='%Y-%m-%d %H:%M:%S'
  103. )
  104. if name_only:
  105. storage = ListGeneratedFilesStorage()
  106. else:
  107. storage = FileSystemGeneratorStorage(output_dir)
  108. logging.info("Parsing idl from %s" % idl_path)
  109. idl_tree = CreateParser().parse(open(idl_path, "rt").read())
  110. plugin_module = None
  111. if generator.startswith('custom:'):
  112. # check that the plugin path is provided
  113. custom_params = generator.split(':')
  114. if len(custom_params) != 3:
  115. logging.fatal("Custom generator format not valid. Please use --generator custom:<path>:<module>")
  116. sys.exit(1)
  117. (generator, plugin_path, plugin_module) = custom_params
  118. logging.info("Using CustomGenerator at plugin path %s.%s" % (plugin_path, plugin_module))
  119. sys.path.append(plugin_path)
  120. generator = 'CUSTOM'
  121. extra_args = {}
  122. for o in option:
  123. if ':' not in o:
  124. logging.fatal("Please specify options as '<key>:<value>'. %r is not valid. " % o)
  125. sys.exit(1)
  126. key, value = o.split(':')
  127. extra_args[key] = value
  128. logging.info("Running code generator %s" % generator)
  129. generator = CodeGenerator.FromString(generator).Create(storage, idl=idl_tree, plugin_module=plugin_module, **extra_args)
  130. generator.render(dry_run)
  131. if expected_outputs:
  132. with open(expected_outputs, 'rt') as fin:
  133. expected = set()
  134. for line in fin.readlines():
  135. line = line.strip()
  136. if line:
  137. expected.add(line)
  138. if expected != storage.generated_paths:
  139. logging.fatal("expected and generated files do not match.")
  140. extra = storage.generated_paths - expected
  141. missing = expected - storage.generated_paths
  142. for name in extra:
  143. logging.fatal(" '%s' was generated but not expected" % name)
  144. for name in missing:
  145. logging.fatal(" '%s' was expected but not generated" % name)
  146. sys.exit(1)
  147. logging.info("Done")
  148. if __name__ == '__main__':
  149. main(auto_envvar_prefix='CHIP')