common.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. # coding=utf-8
  2. import sys
  3. import os
  4. from collections import namedtuple
  5. import logging
  6. import json
  7. import typing
  8. DEFAULT_TARGET = "esp32"
  9. TARGET_PLACEHOLDER = "@t"
  10. WILDCARD_PLACEHOLDER = "@w"
  11. NAME_PLACEHOLDER = "@n"
  12. FULL_NAME_PLACEHOLDER = "@f"
  13. INDEX_PLACEHOLDER = "@i"
  14. # ConfigRule represents one --config argument of find_apps.py.
  15. # file_name is the name of the sdkconfig file fragment, optionally with a single wildcard ('*' character).
  16. # file_name can also be empty to indicate that the default configuration of the app should be used.
  17. # config_name is the name of the corresponding build configuration, or None if the value of wildcard is to be used.
  18. # For example:
  19. # filename='', config_name='default' — represents the default app configuration, and gives it a name 'default'
  20. # filename='sdkconfig.*', config_name=None - represents the set of configurations, names match the wildcard value
  21. ConfigRule = namedtuple("ConfigRule", ["file_name", "config_name"])
  22. def config_rules_from_str(rule_strings): # type: (typing.List[str]) -> typing.List[ConfigRule]
  23. """
  24. Helper function to convert strings like 'file_name=config_name' into ConfigRule objects
  25. :param rule_strings: list of rules as strings
  26. :return: list of ConfigRules
  27. """
  28. rules = [] # type: typing.List[ConfigRule]
  29. for rule_str in rule_strings:
  30. items = rule_str.split("=", 2)
  31. rules.append(ConfigRule(items[0], items[1] if len(items) == 2 else None))
  32. return rules
  33. class BuildItem(object):
  34. """
  35. Instance of this class represents one build of an application.
  36. The parameters which distinguish the build are passed to the constructor.
  37. """
  38. def __init__(
  39. self,
  40. app_path,
  41. work_dir,
  42. build_path,
  43. build_log_path,
  44. target,
  45. sdkconfig_path,
  46. config_name,
  47. build_system,
  48. ):
  49. # These internal variables store the paths with environment variables and placeholders;
  50. # Public properties with similar names use the _expand method to get the actual paths.
  51. self._app_dir = app_path
  52. self._work_dir = work_dir
  53. self._build_dir = build_path
  54. self._build_log_path = build_log_path
  55. self.sdkconfig_path = sdkconfig_path
  56. self.config_name = config_name
  57. self.target = target
  58. self.build_system = build_system
  59. self._app_name = os.path.basename(os.path.normpath(app_path))
  60. # Some miscellaneous build properties which are set later, at the build stage
  61. self.index = None
  62. self.verbose = False
  63. self.dry_run = False
  64. self.keep_going = False
  65. @property
  66. def app_dir(self):
  67. """
  68. :return: directory of the app
  69. """
  70. return self._expand(self._app_dir)
  71. @property
  72. def work_dir(self):
  73. """
  74. :return: directory where the app should be copied to, prior to the build. Can be None, which means that the app
  75. directory should be used.
  76. """
  77. return self._expand(self._work_dir)
  78. @property
  79. def build_dir(self):
  80. """
  81. :return: build directory, either relative to the work directory (if relative path is used) or absolute path.
  82. """
  83. return self._expand(self._build_dir)
  84. @property
  85. def build_log_path(self):
  86. """
  87. :return: path of the build log file
  88. """
  89. return self._expand(self._build_log_path)
  90. def __repr__(self):
  91. return "Build app {} for target {}, sdkconfig {} in {}".format(
  92. self.app_dir,
  93. self.target,
  94. self.sdkconfig_path or "(default)",
  95. self.build_dir,
  96. )
  97. def to_json(self): # type: () -> str
  98. """
  99. :return: JSON string representing this object
  100. """
  101. return self._to_json(self._app_dir, self._work_dir, self._build_dir, self._build_log_path)
  102. def to_json_expanded(self): # type: () -> str
  103. """
  104. :return: JSON string representing this object, with all placeholders in paths expanded
  105. """
  106. return self._to_json(self.app_dir, self.work_dir, self.build_dir, self.build_log_path)
  107. def _to_json(self, app_dir, work_dir, build_dir, build_log_path): # type: (str, str, str, str) -> str
  108. """
  109. Internal function, called by to_json and to_json_expanded
  110. """
  111. return json.dumps({
  112. "build_system": self.build_system,
  113. "app_dir": app_dir,
  114. "work_dir": work_dir,
  115. "build_dir": build_dir,
  116. "build_log_path": build_log_path,
  117. "sdkconfig": self.sdkconfig_path,
  118. "config": self.config_name,
  119. "target": self.target,
  120. "verbose": self.verbose,
  121. })
  122. @staticmethod
  123. def from_json(json_str): # type: (typing.Text) -> BuildItem
  124. """
  125. :return: Get the BuildItem from a JSON string
  126. """
  127. d = json.loads(str(json_str))
  128. result = BuildItem(
  129. app_path=d["app_dir"],
  130. work_dir=d["work_dir"],
  131. build_path=d["build_dir"],
  132. build_log_path=d["build_log_path"],
  133. sdkconfig_path=d["sdkconfig"],
  134. config_name=d["config"],
  135. target=d["target"],
  136. build_system=d["build_system"],
  137. )
  138. result.verbose = d["verbose"]
  139. return result
  140. def _expand(self, path): # type: (str) -> str
  141. """
  142. Internal method, expands any of the placeholders in {app,work,build} paths.
  143. """
  144. if not path:
  145. return path
  146. if self.index is not None:
  147. path = path.replace(INDEX_PLACEHOLDER, str(self.index))
  148. path = path.replace(TARGET_PLACEHOLDER, self.target)
  149. path = path.replace(NAME_PLACEHOLDER, self._app_name)
  150. if (FULL_NAME_PLACEHOLDER in path): # to avoid recursion to the call to app_dir in the next line:
  151. path = path.replace(FULL_NAME_PLACEHOLDER, self.app_dir.replace(os.path.sep, "_"))
  152. wildcard_pos = path.find(WILDCARD_PLACEHOLDER)
  153. if wildcard_pos != -1:
  154. if self.config_name:
  155. # if config name is defined, put it in place of the placeholder
  156. path = path.replace(WILDCARD_PLACEHOLDER, self.config_name)
  157. else:
  158. # otherwise, remove the placeholder and one character on the left
  159. # (which is usually an underscore, dash, or other delimiter)
  160. left_of_wildcard = max(0, wildcard_pos - 1)
  161. right_of_wildcard = wildcard_pos + len(WILDCARD_PLACEHOLDER)
  162. path = path[0:left_of_wildcard] + path[right_of_wildcard:]
  163. path = os.path.expandvars(path)
  164. return path
  165. class BuildSystem(object):
  166. """
  167. Class representing a build system.
  168. Derived classes implement the methods below.
  169. Objects of these classes aren't instantiated, instead the class (type object) is used.
  170. """
  171. NAME = "undefined"
  172. @staticmethod
  173. def build(self):
  174. raise NotImplementedError()
  175. @staticmethod
  176. def is_app(path):
  177. raise NotImplementedError()
  178. @staticmethod
  179. def supported_targets(app_path):
  180. raise NotImplementedError()
  181. class BuildError(RuntimeError):
  182. pass
  183. def setup_logging(args):
  184. """
  185. Configure logging module according to the number of '--verbose'/'-v' arguments and the --log-file argument.
  186. :param args: namespace obtained from argparse
  187. """
  188. if not args.verbose:
  189. log_level = logging.WARNING
  190. elif args.verbose == 1:
  191. log_level = logging.INFO
  192. else:
  193. log_level = logging.DEBUG
  194. logging.basicConfig(
  195. format="%(levelname)s: %(message)s",
  196. stream=args.log_file or sys.stderr,
  197. level=log_level,
  198. )