tools.py 14 KB

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