tools.py 14 KB

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