tools.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. import os
  2. import re
  3. import subprocess
  4. import sys
  5. from io import open
  6. import click
  7. from .constants import GENERATORS
  8. from .errors import FatalError
  9. def executable_exists(args):
  10. try:
  11. subprocess.check_output(args)
  12. return True
  13. except Exception:
  14. return False
  15. def realpath(path):
  16. """
  17. Return the cannonical path with normalized case.
  18. It is useful on Windows to comparision paths in case-insensitive manner.
  19. On Unix and Mac OS X it works as `os.path.realpath()` only.
  20. """
  21. return os.path.normcase(os.path.realpath(path))
  22. def _idf_version_from_cmake():
  23. version_path = os.path.join(os.environ['IDF_PATH'], 'tools/cmake/version.cmake')
  24. regex = re.compile(r'^\s*set\s*\(\s*IDF_VERSION_([A-Z]{5})\s+(\d+)')
  25. ver = {}
  26. try:
  27. with open(version_path) as f:
  28. for line in f:
  29. m = regex.match(line)
  30. if m:
  31. ver[m.group(1)] = m.group(2)
  32. return 'v%s.%s.%s' % (ver['MAJOR'], ver['MINOR'], ver['PATCH'])
  33. except (KeyError, OSError):
  34. sys.stderr.write('WARNING: Cannot find ESP-IDF version in version.cmake\n')
  35. return None
  36. def idf_version():
  37. """Print version of ESP-IDF"""
  38. # Try to get version from git:
  39. try:
  40. version = subprocess.check_output([
  41. 'git',
  42. '--git-dir=%s' % os.path.join(os.environ['IDF_PATH'], '.git'),
  43. '--work-tree=%s' % os.environ['IDF_PATH'],
  44. 'describe', '--tags', '--dirty', '--match', 'v*.*',
  45. ]).decode('utf-8', 'ignore').strip()
  46. except (subprocess.CalledProcessError, UnicodeError):
  47. # if failed, then try to parse cmake.version file
  48. sys.stderr.write('WARNING: Git version unavailable, reading from source\n')
  49. version = _idf_version_from_cmake()
  50. return version
  51. def run_tool(tool_name, args, cwd, env=dict()):
  52. def quote_arg(arg):
  53. " Quote 'arg' if necessary "
  54. if ' ' in arg and not (arg.startswith('"') or arg.startswith("'")):
  55. return "'" + arg + "'"
  56. return arg
  57. args = [str(arg) for arg in args]
  58. display_args = ' '.join(quote_arg(arg) for arg in args)
  59. print('Running %s in directory %s' % (tool_name, quote_arg(cwd)))
  60. print('Executing "%s"...' % str(display_args))
  61. env_copy = dict(os.environ)
  62. env_copy.update(env)
  63. if sys.version_info[0] < 3:
  64. # The subprocess lib cannot accept environment variables as "unicode". Convert to str.
  65. # This encoding step is required only in Python 2.
  66. for (key, val) in env_copy.items():
  67. if not isinstance(val, str):
  68. env_copy[key] = val.encode(sys.getfilesystemencoding() or 'utf-8')
  69. try:
  70. # Note: we explicitly pass in os.environ here, as we may have set IDF_PATH there during startup
  71. subprocess.check_call(args, env=env_copy, cwd=cwd)
  72. except subprocess.CalledProcessError as e:
  73. raise FatalError('%s failed with exit code %d' % (tool_name, e.returncode))
  74. def run_target(target_name, args, env=dict()):
  75. generator_cmd = GENERATORS[args.generator]['command']
  76. if args.verbose:
  77. generator_cmd += [GENERATORS[args.generator]['verbose_flag']]
  78. run_tool(generator_cmd[0], generator_cmd + [target_name], args.build_dir, env)
  79. def _strip_quotes(value, regexp=re.compile(r"^\"(.*)\"$|^'(.*)'$|^(.*)$")):
  80. """
  81. Strip quotes like CMake does during parsing cache entries
  82. """
  83. return [x for x in regexp.match(value).groups() if x is not None][0].rstrip()
  84. def _parse_cmakecache(path):
  85. """
  86. Parse the CMakeCache file at 'path'.
  87. Returns a dict of name:value.
  88. CMakeCache entries also each have a "type", but this is currently ignored.
  89. """
  90. result = {}
  91. with open(path, encoding='utf-8') as f:
  92. for line in f:
  93. # cmake cache lines look like: CMAKE_CXX_FLAGS_DEBUG:STRING=-g
  94. # groups are name, type, value
  95. m = re.match(r'^([^#/:=]+):([^:=]+)=(.*)\n$', line)
  96. if m:
  97. result[m.group(1)] = m.group(3)
  98. return result
  99. def _new_cmakecache_entries(cache_path, new_cache_entries):
  100. if not os.path.exists(cache_path):
  101. return True
  102. if new_cache_entries:
  103. current_cache = _parse_cmakecache(cache_path)
  104. for entry in new_cache_entries:
  105. key, value = entry.split('=', 1)
  106. current_value = current_cache.get(key, None)
  107. if current_value is None or _strip_quotes(value) != current_value:
  108. return True
  109. return False
  110. def _detect_cmake_generator(prog_name):
  111. """
  112. Find the default cmake generator, if none was specified. Raises an exception if no valid generator is found.
  113. """
  114. for (generator_name, generator) in GENERATORS.items():
  115. if executable_exists(generator['version']):
  116. return generator_name
  117. raise FatalError("To use %s, either the 'ninja' or 'GNU make' build tool must be available in the PATH" % prog_name)
  118. def ensure_build_directory(args, prog_name, always_run_cmake=False):
  119. """Check the build directory exists and that cmake has been run there.
  120. If this isn't the case, create the build directory (if necessary) and
  121. do an initial cmake run to configure it.
  122. This function will also check args.generator parameter. If the parameter is incompatible with
  123. the build directory, an error is raised. If the parameter is None, this function will set it to
  124. an auto-detected default generator or to the value already configured in the build directory.
  125. """
  126. project_dir = args.project_dir
  127. # Verify the project directory
  128. if not os.path.isdir(project_dir):
  129. if not os.path.exists(project_dir):
  130. raise FatalError('Project directory %s does not exist' % project_dir)
  131. else:
  132. raise FatalError('%s must be a project directory' % project_dir)
  133. if not os.path.exists(os.path.join(project_dir, 'CMakeLists.txt')):
  134. raise FatalError('CMakeLists.txt not found in project directory %s' % project_dir)
  135. # Verify/create the build directory
  136. build_dir = args.build_dir
  137. if not os.path.isdir(build_dir):
  138. os.makedirs(build_dir)
  139. # Parse CMakeCache, if it exists
  140. cache_path = os.path.join(build_dir, 'CMakeCache.txt')
  141. cache = _parse_cmakecache(cache_path) if os.path.exists(cache_path) else {}
  142. # Validate or set IDF_TARGET
  143. _guess_or_check_idf_target(args, prog_name, cache)
  144. args.define_cache_entry.append('CCACHE_ENABLE=%d' % args.ccache)
  145. if always_run_cmake or _new_cmakecache_entries(cache_path, args.define_cache_entry):
  146. if args.generator is None:
  147. args.generator = _detect_cmake_generator(prog_name)
  148. try:
  149. cmake_args = [
  150. 'cmake',
  151. '-G',
  152. args.generator,
  153. '-DPYTHON_DEPS_CHECKED=1',
  154. '-DESP_PLATFORM=1',
  155. ]
  156. if args.cmake_warn_uninitialized:
  157. cmake_args += ['--warn-uninitialized']
  158. if args.define_cache_entry:
  159. cmake_args += ['-D' + d for d in args.define_cache_entry]
  160. cmake_args += [project_dir]
  161. run_tool('cmake', cmake_args, cwd=args.build_dir)
  162. except Exception:
  163. # don't allow partially valid CMakeCache.txt files,
  164. # to keep the "should I run cmake?" logic simple
  165. if os.path.exists(cache_path):
  166. os.remove(cache_path)
  167. raise
  168. # need to update cache so subsequent access in this method would reflect the result of the previous cmake run
  169. cache = _parse_cmakecache(cache_path) if os.path.exists(cache_path) else {}
  170. try:
  171. generator = cache['CMAKE_GENERATOR']
  172. except KeyError:
  173. generator = _detect_cmake_generator(prog_name)
  174. if args.generator is None:
  175. args.generator = (generator) # reuse the previously configured generator, if none was given
  176. if generator != args.generator:
  177. raise FatalError("Build is configured for generator '%s' not '%s'. Run '%s fullclean' to start again." %
  178. (generator, args.generator, prog_name))
  179. try:
  180. home_dir = cache['CMAKE_HOME_DIRECTORY']
  181. if realpath(home_dir) != realpath(project_dir):
  182. raise FatalError(
  183. "Build directory '%s' configured for project '%s' not '%s'. Run '%s fullclean' to start again." %
  184. (build_dir, realpath(home_dir), realpath(project_dir), prog_name))
  185. except KeyError:
  186. pass # if cmake failed part way, CMAKE_HOME_DIRECTORY may not be set yet
  187. def merge_action_lists(*action_lists):
  188. merged_actions = {
  189. 'global_options': [],
  190. 'actions': {},
  191. 'global_action_callbacks': [],
  192. }
  193. for action_list in action_lists:
  194. merged_actions['global_options'].extend(action_list.get('global_options', []))
  195. merged_actions['actions'].update(action_list.get('actions', {}))
  196. merged_actions['global_action_callbacks'].extend(action_list.get('global_action_callbacks', []))
  197. return merged_actions
  198. def get_sdkconfig_value(sdkconfig_file, key):
  199. """
  200. Return the value of given key from sdkconfig_file.
  201. If sdkconfig_file does not exist or the option is not present, returns None.
  202. """
  203. assert key.startswith('CONFIG_')
  204. if not os.path.exists(sdkconfig_file):
  205. return None
  206. # keep track of the last seen value for the given key
  207. value = None
  208. # if the value is quoted, this excludes the quotes from the value
  209. pattern = re.compile(r"^{}=\"?([^\"]*)\"?$".format(key))
  210. with open(sdkconfig_file, 'r') as f:
  211. for line in f:
  212. match = re.match(pattern, line)
  213. if match:
  214. value = match.group(1)
  215. return value
  216. def is_target_supported(project_path, supported_targets):
  217. """
  218. Returns True if the active target is supported, or False otherwise.
  219. """
  220. return get_sdkconfig_value(os.path.join(project_path, 'sdkconfig'), 'CONFIG_IDF_TARGET') in supported_targets
  221. def _guess_or_check_idf_target(args, prog_name, cache):
  222. """
  223. If CMakeCache.txt doesn't exist, and IDF_TARGET is not set in the environment, guess the value from
  224. sdkconfig or sdkconfig.defaults, and pass it to CMake in IDF_TARGET variable.
  225. Otherwise, cross-check the three settings (sdkconfig, CMakeCache, environment) and if there is
  226. mismatch, fail with instructions on how to fix this.
  227. """
  228. # Default locations of sdkconfig files.
  229. # FIXME: they may be overridden in the project or by a CMake variable (IDF-1369).
  230. sdkconfig_path = os.path.join(args.project_dir, 'sdkconfig')
  231. sdkconfig_defaults_path = os.path.join(args.project_dir, 'sdkconfig.defaults')
  232. # These are used to guess the target from sdkconfig, or set the default target by sdkconfig.defaults.
  233. idf_target_from_sdkconfig = get_sdkconfig_value(sdkconfig_path, 'CONFIG_IDF_TARGET')
  234. idf_target_from_sdkconfig_defaults = get_sdkconfig_value(sdkconfig_defaults_path, 'CONFIG_IDF_TARGET')
  235. idf_target_from_env = os.environ.get('IDF_TARGET')
  236. idf_target_from_cache = cache.get('IDF_TARGET')
  237. if not cache and not idf_target_from_env:
  238. # CMakeCache.txt does not exist yet, and IDF_TARGET is not set in the environment.
  239. guessed_target = idf_target_from_sdkconfig or idf_target_from_sdkconfig_defaults
  240. if guessed_target:
  241. if args.verbose:
  242. print("IDF_TARGET is not set, guessed '%s' from sdkconfig" % (guessed_target))
  243. args.define_cache_entry.append('IDF_TARGET=' + guessed_target)
  244. elif idf_target_from_env:
  245. # Let's check that IDF_TARGET values are consistent
  246. if idf_target_from_sdkconfig and idf_target_from_sdkconfig != idf_target_from_env:
  247. raise FatalError("Project sdkconfig was generated for target '{t_conf}', but environment variable IDF_TARGET "
  248. "is set to '{t_env}'. Run '{prog} set-target {t_env}' to generate new sdkconfig file for target {t_env}."
  249. .format(t_conf=idf_target_from_sdkconfig, t_env=idf_target_from_env, prog=prog_name))
  250. if idf_target_from_cache and idf_target_from_cache != idf_target_from_env:
  251. raise FatalError("Target settings are not consistent: '{t_env}' in the environment, '{t_cache}' in CMakeCache.txt. "
  252. "Run '{prog} fullclean' to start again."
  253. .format(t_env=idf_target_from_env, t_cache=idf_target_from_cache, prog=prog_name))
  254. elif idf_target_from_cache and idf_target_from_sdkconfig and idf_target_from_cache != idf_target_from_sdkconfig:
  255. # This shouldn't happen, unless the user manually edits CMakeCache.txt or sdkconfig, but let's check anyway.
  256. raise FatalError("Project sdkconfig was generated for target '{t_conf}', but CMakeCache.txt contains '{t_cache}'. "
  257. "To keep the setting in sdkconfig ({t_conf}) and re-generate CMakeCache.txt, run '{prog} fullclean'. "
  258. "To re-generate sdkconfig for '{t_cache}' target, run '{prog} set-target {t_cache}'."
  259. .format(t_conf=idf_target_from_sdkconfig, t_cache=idf_target_from_cache, prog=prog_name))
  260. class TargetChoice(click.Choice):
  261. """
  262. A version of click.Choice with two special features:
  263. - ignores hyphens
  264. - not case sensitive
  265. """
  266. def __init__(self, choices):
  267. super(TargetChoice, self).__init__(choices, case_sensitive=False)
  268. def convert(self, value, param, ctx):
  269. def normalize(str):
  270. return str.lower().replace('-', '')
  271. saved_token_normalize_func = ctx.token_normalize_func
  272. ctx.token_normalize_func = normalize
  273. try:
  274. return super(TargetChoice, self).convert(value, param, ctx)
  275. finally:
  276. ctx.token_normalize_func = saved_token_normalize_func