tools.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642
  1. # SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD
  2. # SPDX-License-Identifier: Apache-2.0
  3. import asyncio
  4. import os
  5. import re
  6. import subprocess
  7. import sys
  8. from asyncio.subprocess import Process
  9. from io import open
  10. from types import FunctionType
  11. from typing import Any, Dict, Generator, List, Match, Optional, TextIO, Tuple, Union
  12. import click
  13. import yaml
  14. from idf_py_actions.errors import NoSerialPortFoundError
  15. from .constants import GENERATORS
  16. from .errors import FatalError
  17. # Name of the program, normally 'idf.py'.
  18. # Can be overridden from idf.bat using IDF_PY_PROGRAM_NAME
  19. PROG = os.getenv('IDF_PY_PROGRAM_NAME', 'idf.py')
  20. # environment variable used during click shell completion run
  21. SHELL_COMPLETE_VAR = '_IDF.PY_COMPLETE'
  22. # was shell completion invoked?
  23. SHELL_COMPLETE_RUN = SHELL_COMPLETE_VAR in os.environ
  24. def executable_exists(args: List) -> bool:
  25. try:
  26. subprocess.check_output(args)
  27. return True
  28. except Exception:
  29. return False
  30. def realpath(path: str) -> str:
  31. """
  32. Return the cannonical path with normalized case.
  33. It is useful on Windows to comparision paths in case-insensitive manner.
  34. On Unix and Mac OS X it works as `os.path.realpath()` only.
  35. """
  36. return os.path.normcase(os.path.realpath(path))
  37. def _idf_version_from_cmake() -> Optional[str]:
  38. version_path = os.path.join(os.environ['IDF_PATH'], 'tools/cmake/version.cmake')
  39. regex = re.compile(r'^\s*set\s*\(\s*IDF_VERSION_([A-Z]{5})\s+(\d+)')
  40. ver = {}
  41. try:
  42. with open(version_path) as f:
  43. for line in f:
  44. m = regex.match(line)
  45. if m:
  46. ver[m.group(1)] = m.group(2)
  47. return 'v%s.%s.%s' % (ver['MAJOR'], ver['MINOR'], ver['PATCH'])
  48. except (KeyError, OSError):
  49. sys.stderr.write('WARNING: Cannot find ESP-IDF version in version.cmake\n')
  50. return None
  51. def get_target(path: str, sdkconfig_filename: str='sdkconfig') -> Optional[str]:
  52. path = os.path.join(path, sdkconfig_filename)
  53. return get_sdkconfig_value(path, 'CONFIG_IDF_TARGET')
  54. def idf_version() -> Optional[str]:
  55. """Print version of ESP-IDF"""
  56. # Try to get version from git:
  57. try:
  58. version: Optional[str] = subprocess.check_output([
  59. 'git',
  60. '--git-dir=%s' % os.path.join(os.environ['IDF_PATH'], '.git'),
  61. '--work-tree=%s' % os.environ['IDF_PATH'],
  62. 'describe', '--tags', '--dirty', '--match', 'v*.*',
  63. ]).decode('utf-8', 'ignore').strip()
  64. except (subprocess.CalledProcessError, UnicodeError):
  65. # if failed, then try to parse cmake.version file
  66. sys.stderr.write('WARNING: Git version unavailable, reading from source\n')
  67. version = _idf_version_from_cmake()
  68. return version
  69. def get_default_serial_port() -> Any:
  70. # Import is done here in order to move it after the check_environment()
  71. # ensured that pyserial has been installed
  72. try:
  73. import esptool
  74. import serial.tools.list_ports
  75. ports = list(sorted(p.device for p in serial.tools.list_ports.comports()))
  76. # high baud rate could cause the failure of creation of the connection
  77. esp = esptool.get_default_connected_device(serial_list=ports, port=None, connect_attempts=4,
  78. initial_baud=115200)
  79. if esp is None:
  80. raise NoSerialPortFoundError(
  81. "No serial ports found. Connect a device, or use '-p PORT' option to set a specific port.")
  82. serial_port = esp.serial_port
  83. esp._port.close()
  84. return serial_port
  85. except NoSerialPortFoundError:
  86. raise
  87. except Exception as e:
  88. raise FatalError('An exception occurred during detection of the serial port: {}'.format(e))
  89. # function prints warning when autocompletion is not being performed
  90. # set argument stream to sys.stderr for errors and exceptions
  91. def print_warning(message: str, stream: TextIO=None) -> None:
  92. if not SHELL_COMPLETE_RUN:
  93. print(message, file=stream or sys.stderr)
  94. def color_print(message: str, color: str, newline: Optional[str]='\n') -> None:
  95. """ Print a message to stderr with colored highlighting """
  96. ansi_normal = '\033[0m'
  97. sys.stderr.write('%s%s%s%s' % (color, message, ansi_normal, newline))
  98. sys.stderr.flush()
  99. def yellow_print(message: str, newline: Optional[str]='\n') -> None:
  100. ansi_yellow = '\033[0;33m'
  101. color_print(message, ansi_yellow, newline)
  102. def red_print(message: str, newline: Optional[str]='\n') -> None:
  103. ansi_red = '\033[1;31m'
  104. color_print(message, ansi_red, newline)
  105. def debug_print_idf_version() -> None:
  106. print_warning(f'ESP-IDF {idf_version() or "version unknown"}')
  107. def generate_hints(*filenames: str) -> Generator:
  108. """Getting output files and printing hints on how to resolve errors based on the output."""
  109. with open(os.path.join(os.path.dirname(__file__), 'hints.yml'), 'r') as file:
  110. hints = yaml.safe_load(file)
  111. for file_name in filenames:
  112. with open(file_name, 'r') as file:
  113. output = ' '.join(line.strip() for line in file if line.strip())
  114. for hint in hints:
  115. variables_list = hint.get('variables')
  116. hint_list, hint_vars, re_vars = [], [], []
  117. match: Optional[Match[str]] = None
  118. try:
  119. if variables_list:
  120. for variables in variables_list:
  121. hint_vars = variables['hint_variables']
  122. re_vars = variables['re_variables']
  123. regex = hint['re'].format(*re_vars)
  124. if re.compile(regex).search(output):
  125. try:
  126. hint_list.append(hint['hint'].format(*hint_vars))
  127. except KeyError as e:
  128. red_print('Argument {} missing in {}. Check hints.yml file.'.format(e, hint))
  129. sys.exit(1)
  130. else:
  131. match = re.compile(hint['re']).search(output)
  132. except KeyError as e:
  133. red_print('Argument {} missing in {}. Check hints.yml file.'.format(e, hint))
  134. sys.exit(1)
  135. except re.error as e:
  136. red_print('{} from hints.yml have {} problem. Check hints.yml file.'.format(hint['re'], e))
  137. sys.exit(1)
  138. if hint_list:
  139. for message in hint_list:
  140. yield ' '.join(['HINT:', message])
  141. elif match:
  142. extra_info = ', '.join(match.groups()) if hint.get('match_to_output', '') else ''
  143. try:
  144. yield ' '.join(['HINT:', hint['hint'].format(extra_info)])
  145. except KeyError:
  146. raise KeyError("Argument 'hint' missing in {}. Check hints.yml file.".format(hint))
  147. def fit_text_in_terminal(out: str) -> str:
  148. """Fit text in terminal, if the string is not fit replace center with `...`"""
  149. space_for_dots = 3 # Space for "..."
  150. terminal_width, _ = os.get_terminal_size()
  151. if terminal_width <= space_for_dots:
  152. # if the wide of the terminal is too small just print dots
  153. return '.' * terminal_width
  154. if len(out) >= terminal_width:
  155. elide_size = (terminal_width - space_for_dots) // 2
  156. # cut out the middle part of the output if it does not fit in the terminal
  157. return '...'.join([out[:elide_size], out[len(out) - elide_size:]])
  158. return out
  159. class RunTool:
  160. def __init__(self, tool_name: str, args: List, cwd: str, env: Dict=None, custom_error_handler: FunctionType=None, build_dir: str=None,
  161. hints: bool=True, force_progression: bool=False, interactive: bool=False) -> None:
  162. self.tool_name = tool_name
  163. self.args = args
  164. self.cwd = cwd
  165. self.env = env
  166. self.custom_error_handler = custom_error_handler
  167. # build_dir sets by tools that do not use build directory as cwd
  168. self.build_dir = build_dir or cwd
  169. self.hints = hints
  170. self.force_progression = force_progression
  171. self.interactive = interactive
  172. def __call__(self) -> None:
  173. def quote_arg(arg: str) -> str:
  174. """ Quote the `arg` with whitespace in them because it can cause problems when we call it from a subprocess."""
  175. if re.match(r"^(?![\'\"]).*\s.*", arg):
  176. return ''.join(["'", arg, "'"])
  177. return arg
  178. self.args = [str(arg) for arg in self.args]
  179. display_args = ' '.join(quote_arg(arg) for arg in self.args)
  180. print('Running %s in directory %s' % (self.tool_name, quote_arg(self.cwd)))
  181. print('Executing "%s"...' % str(display_args))
  182. env_copy = dict(os.environ)
  183. env_copy.update(self.env or {})
  184. process: Union[Process, subprocess.CompletedProcess[bytes]]
  185. if self.hints:
  186. process, stderr_output_file, stdout_output_file = asyncio.run(self.run_command(self.args, env_copy))
  187. else:
  188. process = subprocess.run(self.args, env=env_copy, cwd=self.cwd)
  189. stderr_output_file, stdout_output_file = None, None
  190. if process.returncode == 0:
  191. return
  192. if self.custom_error_handler:
  193. self.custom_error_handler(process.returncode, stderr_output_file, stdout_output_file)
  194. return
  195. if stderr_output_file and stdout_output_file:
  196. for hint in generate_hints(stderr_output_file, stdout_output_file):
  197. yellow_print(hint)
  198. raise FatalError('{} failed with exit code {}, output of the command is in the {} and {}'.format(self.tool_name, process.returncode,
  199. stderr_output_file, stdout_output_file))
  200. raise FatalError('{} failed with exit code {}'.format(self.tool_name, process.returncode))
  201. async def run_command(self, cmd: List, env_copy: Dict) -> Tuple[Process, Optional[str], Optional[str]]:
  202. """ Run the `cmd` command with capturing stderr and stdout from that function and return returncode
  203. and of the command, the id of the process, paths to captured output """
  204. log_dir_name = 'log'
  205. try:
  206. os.mkdir(os.path.join(self.build_dir, log_dir_name))
  207. except FileExistsError:
  208. pass
  209. # Note: we explicitly pass in os.environ here, as we may have set IDF_PATH there during startup
  210. # limit was added for avoiding error in idf.py confserver
  211. try:
  212. p = await asyncio.create_subprocess_exec(*cmd, env=env_copy, limit=1024 * 256, cwd=self.cwd, stdout=asyncio.subprocess.PIPE,
  213. stderr=asyncio.subprocess.PIPE)
  214. except NotImplementedError:
  215. sys.exit(f'ERROR: {sys.executable} doesn\'t support asyncio. The issue can be worked around by re-running idf.py with the "--no-hints" argument.')
  216. stderr_output_file = os.path.join(self.build_dir, log_dir_name, f'idf_py_stderr_output_{p.pid}')
  217. stdout_output_file = os.path.join(self.build_dir, log_dir_name, f'idf_py_stdout_output_{p.pid}')
  218. if p.stderr and p.stdout: # it only to avoid None type in p.std
  219. await asyncio.gather(
  220. self.read_and_write_stream(p.stderr, stderr_output_file, sys.stderr),
  221. self.read_and_write_stream(p.stdout, stdout_output_file, sys.stdout))
  222. await p.wait() # added for avoiding None returncode
  223. return p, stderr_output_file, stdout_output_file
  224. async def read_and_write_stream(self, input_stream: asyncio.StreamReader, output_filename: str,
  225. output_stream: TextIO) -> None:
  226. """read the output of the `input_stream` and then write it into `output_filename` and `output_stream`"""
  227. def delete_ansi_escape(text: str) -> str:
  228. ansi_escape = re.compile(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])')
  229. return ansi_escape.sub('', text)
  230. def print_progression(output: str) -> None:
  231. # Print a new line on top of the previous line
  232. sys.stdout.write('\x1b[K')
  233. print('\r', end='')
  234. print(fit_text_in_terminal(output.strip('\n\r')), end='', file=output_stream)
  235. async def read_stream() -> Optional[str]:
  236. try:
  237. output_b = await input_stream.readline()
  238. return output_b.decode(errors='ignore')
  239. except (asyncio.LimitOverrunError, asyncio.IncompleteReadError) as e:
  240. print(e, file=sys.stderr)
  241. return None
  242. except AttributeError:
  243. return None
  244. async def read_interactive_stream() -> Optional[str]:
  245. buffer = b''
  246. while True:
  247. output_b = await input_stream.read(1)
  248. if not output_b:
  249. return None
  250. try:
  251. return (buffer + output_b).decode()
  252. except UnicodeDecodeError:
  253. buffer += output_b
  254. if len(buffer) > 4:
  255. # Multi-byte character contain up to 4 bytes and if buffer have more then 4 bytes
  256. # and still can not decode it we can just ignore some bytes
  257. return buffer.decode(errors='ignore')
  258. try:
  259. with open(output_filename, 'w', encoding='utf8') as output_file:
  260. while True:
  261. if self.interactive:
  262. output = await read_interactive_stream()
  263. else:
  264. output = await read_stream()
  265. if not output:
  266. break
  267. output_noescape = delete_ansi_escape(output)
  268. # Always remove escape sequences when writing the build log.
  269. output_file.write(output_noescape)
  270. # If idf.py output is redirected and the output stream is not a TTY,
  271. # strip the escape sequences as well.
  272. # (There shouldn't be any, but just in case.)
  273. if not output_stream.isatty():
  274. output = output_noescape
  275. if self.force_progression and output[0] == '[' and '-v' not in self.args and output_stream.isatty():
  276. # print output in progression way but only the progression related (that started with '[') and if verbose flag is not set
  277. print_progression(output)
  278. else:
  279. output_stream.write(output)
  280. output_stream.flush()
  281. except (RuntimeError, EnvironmentError) as e:
  282. yellow_print('WARNING: The exception {} was raised and we can\'t capture all your {} and '
  283. 'hints on how to resolve errors can be not accurate.'.format(e, output_stream.name.strip('<>')))
  284. def run_tool(*args: Any, **kwargs: Any) -> None:
  285. # Added in case someone uses run_tool externally in idf.py extensions
  286. return RunTool(*args, **kwargs)()
  287. def run_target(target_name: str, args: 'PropertyDict', env: Optional[Dict]=None,
  288. custom_error_handler: FunctionType=None, force_progression: bool=False, interactive: bool=False) -> None:
  289. """Run target in build directory."""
  290. if env is None:
  291. env = {}
  292. generator_cmd = GENERATORS[args.generator]['command']
  293. if args.verbose:
  294. generator_cmd += [GENERATORS[args.generator]['verbose_flag']]
  295. # By default, GNU Make and Ninja strip away color escape sequences when they see that their stdout is redirected.
  296. # If idf.py's stdout is not redirected, the final output is a TTY, so we can tell Make/Ninja to disable stripping
  297. # of color escape sequences. (Requires Ninja v1.9.0 or later.)
  298. if sys.stdout.isatty():
  299. if 'CLICOLOR_FORCE' not in env:
  300. env['CLICOLOR_FORCE'] = '1'
  301. RunTool(generator_cmd[0], generator_cmd + [target_name], args.build_dir, env, custom_error_handler, hints=not args.no_hints,
  302. force_progression=force_progression, interactive=interactive)()
  303. def _strip_quotes(value: str, regexp: re.Pattern=re.compile(r"^\"(.*)\"$|^'(.*)'$|^(.*)$")) -> Optional[str]:
  304. """
  305. Strip quotes like CMake does during parsing cache entries
  306. """
  307. matching_values = regexp.match(value)
  308. return [x for x in matching_values.groups() if x is not None][0].rstrip() if matching_values is not None else None
  309. def _parse_cmakecache(path: str) -> Dict:
  310. """
  311. Parse the CMakeCache file at 'path'.
  312. Returns a dict of name:value.
  313. CMakeCache entries also each have a "type", but this is currently ignored.
  314. """
  315. result = {}
  316. with open(path, encoding='utf-8') as f:
  317. for line in f:
  318. # cmake cache lines look like: CMAKE_CXX_FLAGS_DEBUG:STRING=-g
  319. # groups are name, type, value
  320. m = re.match(r'^([^#/:=]+):([^:=]+)=(.*)\n$', line)
  321. if m:
  322. result[m.group(1)] = m.group(3)
  323. return result
  324. def _new_cmakecache_entries(cache_path: str, new_cache_entries: List) -> bool:
  325. if not os.path.exists(cache_path):
  326. return True
  327. if new_cache_entries:
  328. current_cache = _parse_cmakecache(cache_path)
  329. for entry in new_cache_entries:
  330. key, value = entry.split('=', 1)
  331. current_value = current_cache.get(key, None)
  332. if current_value is None or _strip_quotes(value) != current_value:
  333. return True
  334. return False
  335. def _detect_cmake_generator(prog_name: str) -> Any:
  336. """
  337. Find the default cmake generator, if none was specified. Raises an exception if no valid generator is found.
  338. """
  339. for (generator_name, generator) in GENERATORS.items():
  340. if executable_exists(generator['version']):
  341. return generator_name
  342. raise FatalError("To use %s, either the 'ninja' or 'GNU make' build tool must be available in the PATH" % prog_name)
  343. def ensure_build_directory(args: 'PropertyDict', prog_name: str, always_run_cmake: bool=False) -> None:
  344. """Check the build directory exists and that cmake has been run there.
  345. If this isn't the case, create the build directory (if necessary) and
  346. do an initial cmake run to configure it.
  347. This function will also check args.generator parameter. If the parameter is incompatible with
  348. the build directory, an error is raised. If the parameter is None, this function will set it to
  349. an auto-detected default generator or to the value already configured in the build directory.
  350. """
  351. if not executable_exists(['cmake', '--version']):
  352. debug_print_idf_version()
  353. raise FatalError(f'"cmake" must be available on the PATH to use {PROG}')
  354. project_dir = args.project_dir
  355. # Verify the project directory
  356. if not os.path.isdir(project_dir):
  357. if not os.path.exists(project_dir):
  358. raise FatalError('Project directory %s does not exist' % project_dir)
  359. else:
  360. raise FatalError('%s must be a project directory' % project_dir)
  361. if not os.path.exists(os.path.join(project_dir, 'CMakeLists.txt')):
  362. raise FatalError('CMakeLists.txt not found in project directory %s' % project_dir)
  363. # Verify/create the build directory
  364. build_dir = args.build_dir
  365. if not os.path.isdir(build_dir):
  366. os.makedirs(build_dir)
  367. # Parse CMakeCache, if it exists
  368. cache_path = os.path.join(build_dir, 'CMakeCache.txt')
  369. cache = _parse_cmakecache(cache_path) if os.path.exists(cache_path) else {}
  370. # Validate or set IDF_TARGET
  371. _guess_or_check_idf_target(args, prog_name, cache)
  372. args.define_cache_entry.append('CCACHE_ENABLE=%d' % args.ccache)
  373. if always_run_cmake or _new_cmakecache_entries(cache_path, args.define_cache_entry):
  374. if args.generator is None:
  375. args.generator = _detect_cmake_generator(prog_name)
  376. try:
  377. cmake_args = [
  378. 'cmake',
  379. '-G',
  380. args.generator,
  381. '-DPYTHON_DEPS_CHECKED=1',
  382. '-DPYTHON={}'.format(sys.executable),
  383. '-DESP_PLATFORM=1',
  384. ]
  385. if args.cmake_warn_uninitialized:
  386. cmake_args += ['--warn-uninitialized']
  387. if args.define_cache_entry:
  388. cmake_args += ['-D' + d for d in args.define_cache_entry]
  389. cmake_args += [project_dir]
  390. hints = not args.no_hints
  391. RunTool('cmake', cmake_args, cwd=args.build_dir, hints=hints)()
  392. except Exception:
  393. # don't allow partially valid CMakeCache.txt files,
  394. # to keep the "should I run cmake?" logic simple
  395. if os.path.exists(cache_path):
  396. os.remove(cache_path)
  397. raise
  398. # need to update cache so subsequent access in this method would reflect the result of the previous cmake run
  399. cache = _parse_cmakecache(cache_path) if os.path.exists(cache_path) else {}
  400. try:
  401. generator = cache['CMAKE_GENERATOR']
  402. except KeyError:
  403. generator = _detect_cmake_generator(prog_name)
  404. if args.generator is None:
  405. args.generator = (generator) # reuse the previously configured generator, if none was given
  406. if generator != args.generator:
  407. raise FatalError("Build is configured for generator '%s' not '%s'. Run '%s fullclean' to start again." %
  408. (generator, args.generator, prog_name))
  409. try:
  410. home_dir = cache['CMAKE_HOME_DIRECTORY']
  411. if realpath(home_dir) != realpath(project_dir):
  412. raise FatalError(
  413. "Build directory '%s' configured for project '%s' not '%s'. Run '%s fullclean' to start again." %
  414. (build_dir, realpath(home_dir), realpath(project_dir), prog_name))
  415. except KeyError:
  416. pass # if cmake failed part way, CMAKE_HOME_DIRECTORY may not be set yet
  417. try:
  418. python = cache['PYTHON']
  419. if python != sys.executable:
  420. raise FatalError(
  421. "'{}' is currently active in the environment while the project was configured with '{}'. "
  422. "Run '{} fullclean' to start again.".format(sys.executable, python, prog_name))
  423. except KeyError:
  424. pass
  425. def merge_action_lists(*action_lists: Dict) -> Dict:
  426. merged_actions: Dict = {
  427. 'global_options': [],
  428. 'actions': {},
  429. 'global_action_callbacks': [],
  430. }
  431. for action_list in action_lists:
  432. merged_actions['global_options'].extend(action_list.get('global_options', []))
  433. merged_actions['actions'].update(action_list.get('actions', {}))
  434. merged_actions['global_action_callbacks'].extend(action_list.get('global_action_callbacks', []))
  435. return merged_actions
  436. def get_sdkconfig_value(sdkconfig_file: str, key: str) -> Optional[str]:
  437. """
  438. Return the value of given key from sdkconfig_file.
  439. If sdkconfig_file does not exist or the option is not present, returns None.
  440. """
  441. assert key.startswith('CONFIG_')
  442. if not os.path.exists(sdkconfig_file):
  443. return None
  444. # keep track of the last seen value for the given key
  445. value = None
  446. # if the value is quoted, this excludes the quotes from the value
  447. pattern = re.compile(r"^{}=\"?([^\"]*)\"?$".format(key))
  448. with open(sdkconfig_file, 'r') as f:
  449. for line in f:
  450. match = re.match(pattern, line)
  451. if match:
  452. value = match.group(1)
  453. return value
  454. def is_target_supported(project_path: str, supported_targets: List) -> bool:
  455. """
  456. Returns True if the active target is supported, or False otherwise.
  457. """
  458. return get_target(project_path) in supported_targets
  459. def _guess_or_check_idf_target(args: 'PropertyDict', prog_name: str, cache: Dict) -> None:
  460. """
  461. If CMakeCache.txt doesn't exist, and IDF_TARGET is not set in the environment, guess the value from
  462. sdkconfig or sdkconfig.defaults, and pass it to CMake in IDF_TARGET variable.
  463. Otherwise, cross-check the three settings (sdkconfig, CMakeCache, environment) and if there is
  464. mismatch, fail with instructions on how to fix this.
  465. """
  466. # Default locations of sdkconfig files.
  467. # FIXME: they may be overridden in the project or by a CMake variable (IDF-1369).
  468. # These are used to guess the target from sdkconfig, or set the default target by sdkconfig.defaults.
  469. idf_target_from_sdkconfig = get_target(args.project_dir)
  470. idf_target_from_sdkconfig_defaults = get_target(args.project_dir, 'sdkconfig.defaults')
  471. idf_target_from_env = os.environ.get('IDF_TARGET')
  472. idf_target_from_cache = cache.get('IDF_TARGET')
  473. if not cache and not idf_target_from_env:
  474. # CMakeCache.txt does not exist yet, and IDF_TARGET is not set in the environment.
  475. guessed_target = idf_target_from_sdkconfig or idf_target_from_sdkconfig_defaults
  476. if guessed_target:
  477. if args.verbose:
  478. print("IDF_TARGET is not set, guessed '%s' from sdkconfig" % (guessed_target))
  479. args.define_cache_entry.append('IDF_TARGET=' + guessed_target)
  480. elif idf_target_from_env:
  481. # Let's check that IDF_TARGET values are consistent
  482. if idf_target_from_sdkconfig and idf_target_from_sdkconfig != idf_target_from_env:
  483. raise FatalError("Project sdkconfig was generated for target '{t_conf}', but environment variable IDF_TARGET "
  484. "is set to '{t_env}'. Run '{prog} set-target {t_env}' to generate new sdkconfig file for target {t_env}."
  485. .format(t_conf=idf_target_from_sdkconfig, t_env=idf_target_from_env, prog=prog_name))
  486. if idf_target_from_cache and idf_target_from_cache != idf_target_from_env:
  487. raise FatalError("Target settings are not consistent: '{t_env}' in the environment, '{t_cache}' in CMakeCache.txt. "
  488. "Run '{prog} fullclean' to start again."
  489. .format(t_env=idf_target_from_env, t_cache=idf_target_from_cache, prog=prog_name))
  490. elif idf_target_from_cache and idf_target_from_sdkconfig and idf_target_from_cache != idf_target_from_sdkconfig:
  491. # This shouldn't happen, unless the user manually edits CMakeCache.txt or sdkconfig, but let's check anyway.
  492. raise FatalError("Project sdkconfig was generated for target '{t_conf}', but CMakeCache.txt contains '{t_cache}'. "
  493. "To keep the setting in sdkconfig ({t_conf}) and re-generate CMakeCache.txt, run '{prog} fullclean'. "
  494. "To re-generate sdkconfig for '{t_cache}' target, run '{prog} set-target {t_cache}'."
  495. .format(t_conf=idf_target_from_sdkconfig, t_cache=idf_target_from_cache, prog=prog_name))
  496. class TargetChoice(click.Choice):
  497. """
  498. A version of click.Choice with two special features:
  499. - ignores hyphens
  500. - not case sensitive
  501. """
  502. def __init__(self, choices: List) -> None:
  503. super(TargetChoice, self).__init__(choices, case_sensitive=False)
  504. def convert(self, value: Any, param: click.Parameter, ctx: click.Context) -> Any:
  505. def normalize(string: str) -> str:
  506. return string.lower().replace('-', '')
  507. saved_token_normalize_func = ctx.token_normalize_func
  508. ctx.token_normalize_func = normalize
  509. try:
  510. return super(TargetChoice, self).convert(value, param, ctx)
  511. finally:
  512. ctx.token_normalize_func = saved_token_normalize_func
  513. class PropertyDict(dict):
  514. def __getattr__(self, name: str) -> Any:
  515. if name in self:
  516. return self[name]
  517. else:
  518. raise AttributeError("'PropertyDict' object has no attribute '%s'" % name)
  519. def __setattr__(self, name: str, value: Any) -> None:
  520. self[name] = value
  521. def __delattr__(self, name: str) -> None:
  522. if name in self:
  523. del self[name]
  524. else:
  525. raise AttributeError("'PropertyDict' object has no attribute '%s'" % name)