codepregen.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  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 itertools
  16. import logging
  17. import multiprocessing
  18. import os
  19. import sys
  20. import click
  21. try:
  22. from pregenerate import FindPregenerationTargets, TargetFilter
  23. except ImportError:
  24. sys.path.append(os.path.abspath(os.path.dirname(__file__)))
  25. from pregenerate import FindPregenerationTargets, TargetFilter
  26. from pregenerate.executors import DryRunner, ShellRunner
  27. from pregenerate.types import IdlFileType
  28. try:
  29. import coloredlogs
  30. _has_coloredlogs = True
  31. except ImportError:
  32. _has_coloredlogs = False
  33. # Supported log levels, mapping string values required for argument
  34. # parsing into logging constants
  35. __LOG_LEVELS__ = {
  36. 'debug': logging.DEBUG,
  37. 'info': logging.INFO,
  38. 'warn': logging.WARN,
  39. 'fatal': logging.FATAL,
  40. }
  41. def _ParallelGenerateOne(arg):
  42. """
  43. Helper method to be passed to multiprocessing parallel generation of
  44. items.
  45. """
  46. arg[0].Generate(arg[1])
  47. @click.command()
  48. @click.option(
  49. '--log-level',
  50. default='INFO',
  51. type=click.Choice(__LOG_LEVELS__.keys(), case_sensitive=False),
  52. help='Determines the verbosity of script output')
  53. @click.option(
  54. '--parallel/--no-parallel',
  55. default=True,
  56. help='Do parallel/multiprocessing codegen.')
  57. @click.option(
  58. '--dry-run/--no-dry-run',
  59. default=False,
  60. help='Do not actually execute commands, just log')
  61. @click.option(
  62. '--generator',
  63. default='all',
  64. type=click.Choice(['all', 'zap', 'codegen']),
  65. help='To what code generator to restrict the generation.')
  66. @click.option(
  67. '--input-glob',
  68. default=None,
  69. multiple=True,
  70. help='Restrict file generation inputs to the specified glob patterns.')
  71. @click.option(
  72. '--sdk-root',
  73. default=None,
  74. help='Path to the SDK root (where .zap/.matter files exist).')
  75. @click.option(
  76. '--external-root',
  77. default=None,
  78. multiple=True,
  79. help='Path to an external app root (where .zap/.matter files exist).')
  80. @click.argument('output_dir')
  81. def main(log_level, parallel, dry_run, generator, input_glob, sdk_root, external_root, output_dir):
  82. if _has_coloredlogs:
  83. coloredlogs.install(level=__LOG_LEVELS__[
  84. log_level], fmt='%(asctime)s %(levelname)-7s %(message)s')
  85. else:
  86. logging.basicConfig(
  87. level=__LOG_LEVELS__[log_level],
  88. format='%(asctime)s %(levelname)-7s %(message)s',
  89. datefmt='%Y-%m-%d %H:%M:%S'
  90. )
  91. if not sdk_root:
  92. sdk_root = os.path.join(os.path.dirname(
  93. os.path.realpath(__file__)), '..')
  94. sdk_root = os.path.abspath(sdk_root)
  95. if not output_dir:
  96. raise Exception("Missing output directory")
  97. output_dir = os.path.abspath(output_dir)
  98. logging.info(f"Pre-generating {sdk_root} data into {output_dir}")
  99. if not dry_run:
  100. runner = ShellRunner()
  101. else:
  102. runner = DryRunner()
  103. filter = TargetFilter(path_glob=input_glob)
  104. if generator == 'zap':
  105. filter.file_type = IdlFileType.ZAP
  106. elif generator == 'codegen':
  107. filter.file_type = IdlFileType.MATTER
  108. targets = FindPregenerationTargets(sdk_root, external_root, filter, runner)
  109. runner.ensure_directory_exists(output_dir)
  110. if parallel:
  111. target_and_dir = zip(targets, itertools.repeat(output_dir))
  112. with multiprocessing.Pool() as pool:
  113. for _ in pool.imap_unordered(_ParallelGenerateOne, target_and_dir):
  114. pass
  115. else:
  116. for target in targets:
  117. target.Generate(output_dir)
  118. logging.info("Done")
  119. if __name__ == '__main__':
  120. main()