idf.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776
  1. #!/usr/bin/env python
  2. #
  3. # SPDX-FileCopyrightText: 2019-2022 Espressif Systems (Shanghai) CO LTD
  4. #
  5. # SPDX-License-Identifier: Apache-2.0
  6. #
  7. # 'idf.py' is a top-level config/build command line tool for ESP-IDF
  8. #
  9. # You don't have to use idf.py, you can use cmake directly
  10. # (or use cmake in an IDE)
  11. # WARNING: we don't check for Python build-time dependencies until
  12. # check_environment() function below. If possible, avoid importing
  13. # any external libraries here - put in external script, or import in
  14. # their specific function instead.
  15. from __future__ import annotations
  16. import codecs
  17. import json
  18. import locale
  19. import os
  20. import os.path
  21. import signal
  22. import subprocess
  23. import sys
  24. from collections import Counter, OrderedDict, _OrderedDictKeysView
  25. from importlib import import_module
  26. from pkgutil import iter_modules
  27. from types import FrameType
  28. from typing import Any, Callable, Dict, List, Optional, Union
  29. # pyc files remain in the filesystem when switching between branches which might raise errors for incompatible
  30. # idf.py extensions. Therefore, pyc file generation is turned off:
  31. sys.dont_write_bytecode = True
  32. import python_version_checker # noqa: E402
  33. try:
  34. from idf_py_actions.errors import FatalError # noqa: E402
  35. from idf_py_actions.tools import (PROG, SHELL_COMPLETE_RUN, SHELL_COMPLETE_VAR, PropertyDict, # noqa: E402
  36. debug_print_idf_version, get_target, merge_action_lists, print_warning, realpath)
  37. if os.getenv('IDF_COMPONENT_MANAGER') != '0':
  38. from idf_component_manager import idf_extensions
  39. except ImportError:
  40. # For example, importing click could cause this.
  41. print('Please use idf.py only in an ESP-IDF shell environment.', file=sys.stderr)
  42. sys.exit(1)
  43. # Use this Python interpreter for any subprocesses we launch
  44. PYTHON = sys.executable
  45. # note: os.environ changes don't automatically propagate to child processes,
  46. # you have to pass env=os.environ explicitly anywhere that we create a process
  47. os.environ['PYTHON'] = sys.executable
  48. def check_environment() -> List:
  49. """
  50. Verify the environment contains the top-level tools we need to operate
  51. (cmake will check a lot of other things)
  52. """
  53. checks_output = []
  54. # verify that IDF_PATH env variable is set
  55. # find the directory idf.py is in, then the parent directory of this, and assume this is IDF_PATH
  56. detected_idf_path = realpath(os.path.join(os.path.dirname(__file__), '..'))
  57. if 'IDF_PATH' in os.environ:
  58. set_idf_path = realpath(os.environ['IDF_PATH'])
  59. if set_idf_path != detected_idf_path:
  60. print_warning(
  61. 'WARNING: IDF_PATH environment variable is set to %s but %s path indicates IDF directory %s. '
  62. 'Using the environment variable directory, but results may be unexpected...' %
  63. (set_idf_path, PROG, detected_idf_path))
  64. else:
  65. print_warning('Setting IDF_PATH environment variable: %s' % detected_idf_path)
  66. os.environ['IDF_PATH'] = detected_idf_path
  67. try:
  68. # The Python compatibility check could have been done earlier (tools/detect_python.{sh,fish}) but PATH is
  69. # not set for import at that time. Even if the check would be done before, the same check needs to be done
  70. # here as well (for example one can call idf.py from a not properly set-up environment).
  71. python_version_checker.check()
  72. except RuntimeError as e:
  73. raise FatalError(e)
  74. # check Python dependencies
  75. checks_output.append('Checking Python dependencies...')
  76. try:
  77. out = subprocess.check_output(
  78. [
  79. os.environ['PYTHON'],
  80. os.path.join(os.environ['IDF_PATH'], 'tools', 'idf_tools.py'),
  81. 'check-python-dependencies',
  82. ],
  83. env=os.environ,
  84. )
  85. checks_output.append(out.decode('utf-8', 'ignore').strip())
  86. except subprocess.CalledProcessError as e:
  87. print_warning(e.output.decode('utf-8', 'ignore'), stream=sys.stderr)
  88. debug_print_idf_version()
  89. raise SystemExit(1)
  90. return checks_output
  91. def _safe_relpath(path: str, start: Optional[str]=None) -> str:
  92. """ Return a relative path, same as os.path.relpath, but only if this is possible.
  93. It is not possible on Windows, if the start directory and the path are on different drives.
  94. """
  95. try:
  96. return os.path.relpath(path, os.curdir if start is None else start)
  97. except ValueError:
  98. return os.path.abspath(path)
  99. def init_cli(verbose_output: List=None) -> Any:
  100. # Click is imported here to run it after check_environment()
  101. import click
  102. class Deprecation(object):
  103. """Construct deprecation notice for help messages"""
  104. def __init__(self, deprecated: Union[Dict, str, bool]=False) -> None:
  105. self.deprecated = deprecated
  106. self.since = None
  107. self.removed = None
  108. self.exit_with_error = None
  109. self.custom_message = ''
  110. if isinstance(deprecated, dict):
  111. self.custom_message = deprecated.get('message', '')
  112. self.since = deprecated.get('since', None)
  113. self.removed = deprecated.get('removed', None)
  114. self.exit_with_error = deprecated.get('exit_with_error', None)
  115. elif isinstance(deprecated, str):
  116. self.custom_message = deprecated
  117. def full_message(self, type: str='Option') -> str:
  118. if self.exit_with_error:
  119. return '%s is deprecated %sand was removed%s.%s' % (
  120. type,
  121. 'since %s ' % self.since if self.since else '',
  122. ' in %s' % self.removed if self.removed else '',
  123. ' %s' % self.custom_message if self.custom_message else '',
  124. )
  125. else:
  126. return '%s is deprecated %sand will be removed in%s.%s' % (
  127. type,
  128. 'since %s ' % self.since if self.since else '',
  129. ' %s' % self.removed if self.removed else ' future versions',
  130. ' %s' % self.custom_message if self.custom_message else '',
  131. )
  132. def help(self, text: str, type: str='Option', separator: str=' ') -> str:
  133. text = text or ''
  134. return self.full_message(type) + separator + text if self.deprecated else text
  135. def short_help(self, text: str) -> str:
  136. text = text or ''
  137. return ('Deprecated! ' + text) if self.deprecated else text
  138. def check_deprecation(ctx: click.core.Context) -> None:
  139. """Prints deprecation warnings for arguments in given context"""
  140. for option in ctx.command.params:
  141. default = () if option.multiple else option.default
  142. if isinstance(option, Option) and option.deprecated and ctx.params[option.name] != default:
  143. deprecation = Deprecation(option.deprecated)
  144. if deprecation.exit_with_error:
  145. raise FatalError('Error: %s' % deprecation.full_message('Option "%s"' % option.name))
  146. else:
  147. print_warning('Warning: %s' % deprecation.full_message('Option "%s"' % option.name))
  148. class Task(object):
  149. def __init__(self, callback: Callable, name: str, aliases: List, dependencies: Optional[List],
  150. order_dependencies: Optional[List], action_args: Dict) -> None:
  151. self.callback = callback
  152. self.name = name
  153. self.dependencies = dependencies
  154. self.order_dependencies = order_dependencies
  155. self.action_args = action_args
  156. self.aliases = aliases
  157. def __call__(self, context: click.core.Context, global_args: PropertyDict, action_args: Dict=None) -> None:
  158. if action_args is None:
  159. action_args = self.action_args
  160. self.callback(self.name, context, global_args, **action_args)
  161. class Action(click.Command):
  162. def __init__(
  163. self,
  164. name: Optional[str]=None,
  165. aliases: Optional[List]=None,
  166. deprecated: Union[Dict, str, bool]=False,
  167. dependencies: Optional[List]=None,
  168. order_dependencies: Optional[List]=None,
  169. hidden: bool=False,
  170. **kwargs: Any) -> None:
  171. super(Action, self).__init__(name, **kwargs)
  172. self.name: str = self.name or self.callback.__name__
  173. self.deprecated: Union[Dict, str, bool] = deprecated
  174. self.hidden: bool = hidden
  175. if aliases is None:
  176. aliases = []
  177. self.aliases = aliases
  178. self.help: str = self.help or self.callback.__doc__ or ''
  179. if dependencies is None:
  180. dependencies = []
  181. if order_dependencies is None:
  182. order_dependencies = []
  183. # Show first line of help if short help is missing
  184. self.short_help: str = self.short_help or self.help.split('\n')[0]
  185. if deprecated:
  186. deprecation = Deprecation(deprecated)
  187. self.short_help = deprecation.short_help(self.short_help)
  188. self.help = deprecation.help(self.help, type='Command', separator='\n')
  189. # Add aliases to help string
  190. if aliases:
  191. aliases_help = 'Aliases: %s.' % ', '.join(aliases)
  192. self.help = '\n'.join([self.help, aliases_help])
  193. self.short_help = ' '.join([aliases_help, self.short_help])
  194. self.unwrapped_callback = self.callback
  195. if self.callback is not None:
  196. def wrapped_callback(**action_args: Any) -> Task:
  197. return Task(
  198. callback=self.unwrapped_callback,
  199. name=self.name,
  200. dependencies=dependencies,
  201. order_dependencies=order_dependencies,
  202. action_args=action_args,
  203. aliases=self.aliases,
  204. )
  205. self.callback = wrapped_callback
  206. def invoke(self, ctx: click.core.Context) -> click.core.Context:
  207. if self.deprecated:
  208. deprecation = Deprecation(self.deprecated)
  209. message = deprecation.full_message('Command "%s"' % self.name)
  210. if deprecation.exit_with_error:
  211. raise FatalError('Error: %s' % message)
  212. else:
  213. print_warning('Warning: %s' % message)
  214. self.deprecated = False # disable Click's built-in deprecation handling
  215. # Print warnings for options
  216. check_deprecation(ctx)
  217. return super(Action, self).invoke(ctx)
  218. class Argument(click.Argument):
  219. """
  220. Positional argument
  221. names - alias of 'param_decls'
  222. """
  223. def __init__(self, **kwargs: str):
  224. names = kwargs.pop('names')
  225. super(Argument, self).__init__(names, **kwargs)
  226. class Scope(object):
  227. """
  228. Scope for sub-command option.
  229. possible values:
  230. - default - only available on defined level (global/action)
  231. - global - When defined for action, also available as global
  232. - shared - Opposite to 'global': when defined in global scope, also available for all actions
  233. """
  234. SCOPES = ('default', 'global', 'shared')
  235. def __init__(self, scope: Union['Scope', str]=None) -> None:
  236. if scope is None:
  237. self._scope = 'default'
  238. elif isinstance(scope, str) and scope in self.SCOPES:
  239. self._scope = scope
  240. elif isinstance(scope, Scope):
  241. self._scope = str(scope)
  242. else:
  243. raise FatalError('Unknown scope for option: %s' % scope)
  244. @property
  245. def is_global(self) -> bool:
  246. return self._scope == 'global'
  247. @property
  248. def is_shared(self) -> bool:
  249. return self._scope == 'shared'
  250. def __str__(self) -> str:
  251. return self._scope
  252. class Option(click.Option):
  253. """Option that knows whether it should be global"""
  254. def __init__(self, scope: Union[Scope, str]=None, deprecated: Union[Dict, str, bool]=False, hidden: bool=False, **kwargs: str) -> None:
  255. """
  256. Keyword arguments additional to Click's Option class:
  257. names - alias of 'param_decls'
  258. deprecated - marks option as deprecated. May be boolean, string (with custom deprecation message)
  259. or dict with optional keys:
  260. since: version of deprecation
  261. removed: version when option will be removed
  262. custom_message: Additional text to deprecation warning
  263. """
  264. kwargs['param_decls'] = kwargs.pop('names')
  265. super(Option, self).__init__(**kwargs)
  266. self.deprecated = deprecated
  267. self.scope = Scope(scope)
  268. self.hidden = hidden
  269. if deprecated:
  270. deprecation = Deprecation(deprecated)
  271. self.help: str = deprecation.help(self.help)
  272. if self.envvar:
  273. self.help += ' The default value can be set with the %s environment variable.' % self.envvar
  274. if self.scope.is_global:
  275. self.help += ' This option can be used at most once either globally, or for one subcommand.'
  276. def get_help_record(self, ctx: click.core.Context) -> Any:
  277. # Backport "hidden" parameter to click 5.0
  278. if self.hidden:
  279. return None
  280. return super(Option, self).get_help_record(ctx)
  281. class CLI(click.MultiCommand):
  282. """Action list contains all actions with options available for CLI"""
  283. def __init__(self, all_actions: Dict=None, verbose_output: List=None, help: str=None) -> None:
  284. super(CLI, self).__init__(
  285. chain=True,
  286. invoke_without_command=True,
  287. result_callback=self.execute_tasks,
  288. no_args_is_help=True,
  289. context_settings={'max_content_width': 140},
  290. help=help,
  291. )
  292. self._actions = {}
  293. self.global_action_callbacks = []
  294. self.commands_with_aliases = {}
  295. if verbose_output is None:
  296. verbose_output = []
  297. self.verbose_output = verbose_output
  298. if all_actions is None:
  299. all_actions = {}
  300. shared_options = []
  301. # Global options
  302. for option_args in all_actions.get('global_options', []):
  303. option = Option(**option_args)
  304. self.params.append(option)
  305. if option.scope.is_shared:
  306. shared_options.append(option)
  307. # Global options validators
  308. self.global_action_callbacks = all_actions.get('global_action_callbacks', [])
  309. # Actions
  310. for name, action in all_actions.get('actions', {}).items():
  311. arguments = action.pop('arguments', [])
  312. options = action.pop('options', [])
  313. if arguments is None:
  314. arguments = []
  315. if options is None:
  316. options = []
  317. self._actions[name] = Action(name=name, **action)
  318. for alias in [name] + action.get('aliases', []):
  319. self.commands_with_aliases[alias] = name
  320. for argument_args in arguments:
  321. self._actions[name].params.append(Argument(**argument_args))
  322. # Add all shared options
  323. for option in shared_options:
  324. self._actions[name].params.append(option)
  325. for option_args in options:
  326. option = Option(**option_args)
  327. if option.scope.is_shared:
  328. raise FatalError(
  329. '"%s" is defined for action "%s". '
  330. ' "shared" options can be declared only on global level' % (option.name, name))
  331. # Promote options to global if see for the first time
  332. if option.scope.is_global and option.name not in [o.name for o in self.params]:
  333. self.params.append(option)
  334. self._actions[name].params.append(option)
  335. def list_commands(self, ctx: click.core.Context) -> List:
  336. return sorted(filter(lambda name: not self._actions[name].hidden, self._actions))
  337. def get_command(self, ctx: click.core.Context, name: str) -> Optional[Action]:
  338. if name in self.commands_with_aliases:
  339. return self._actions.get(self.commands_with_aliases.get(name))
  340. # Trying fallback to build target (from "all" action) if command is not known
  341. else:
  342. callback = self._actions.get('fallback')
  343. if callback:
  344. return Action(name=name, callback=callback.unwrapped_callback)
  345. return None
  346. def _print_closing_message(self, args: PropertyDict, actions: _OrderedDictKeysView) -> None:
  347. # print a closing message of some kind
  348. #
  349. if any(t in str(actions) for t in ('flash', 'dfu', 'uf2', 'uf2-app')):
  350. print('Done')
  351. return
  352. if not os.path.exists(os.path.join(args.build_dir, 'flasher_args.json')):
  353. print('Done')
  354. return
  355. # Otherwise, if we built any binaries print a message about
  356. # how to flash them
  357. def print_flashing_message(title: str, key: str) -> None:
  358. with open(os.path.join(args.build_dir, 'flasher_args.json')) as file:
  359. flasher_args: Dict[str, Any] = json.load(file)
  360. def flasher_path(f: Union[str, 'os.PathLike[str]']) -> str:
  361. if type(args.build_dir) is bytes:
  362. args.build_dir = args.build_dir.decode()
  363. return _safe_relpath(os.path.join(args.build_dir, f))
  364. if key != 'project': # flashing a single item
  365. if key not in flasher_args:
  366. # This is the case for 'idf.py bootloader' if Secure Boot is on, need to follow manual flashing steps
  367. print('\n%s build complete.' % title)
  368. return
  369. cmd = ''
  370. if (key == 'bootloader'): # bootloader needs --flash-mode, etc to be passed in
  371. cmd = ' '.join(flasher_args['write_flash_args']) + ' '
  372. cmd += flasher_args[key]['offset'] + ' '
  373. cmd += flasher_path(flasher_args[key]['file'])
  374. else: # flashing the whole project
  375. cmd = ' '.join(flasher_args['write_flash_args']) + ' '
  376. flash_items = sorted(
  377. ((o, f) for (o, f) in flasher_args['flash_files'].items() if len(o) > 0),
  378. key=lambda x: int(x[0], 0),
  379. )
  380. for o, f in flash_items:
  381. cmd += o + ' ' + flasher_path(f) + ' '
  382. print('\n%s build complete. To flash, run this command:' % title)
  383. print(
  384. '%s %s -p %s -b %s --before %s --after %s --chip %s %s write_flash %s' % (
  385. PYTHON,
  386. _safe_relpath('%s/components/esptool_py/esptool/esptool.py' % os.environ['IDF_PATH']),
  387. args.port or '(PORT)',
  388. args.baud,
  389. flasher_args['extra_esptool_args']['before'],
  390. flasher_args['extra_esptool_args']['after'],
  391. flasher_args['extra_esptool_args']['chip'],
  392. '--no-stub' if not flasher_args['extra_esptool_args']['stub'] else '',
  393. cmd.strip(),
  394. ))
  395. print(
  396. "or run 'idf.py -p %s %s'" % (
  397. args.port or '(PORT)',
  398. key + '-flash' if key != 'project' else 'flash',
  399. ))
  400. if 'all' in actions or 'build' in actions:
  401. print_flashing_message('Project', 'project')
  402. else:
  403. if 'app' in actions:
  404. print_flashing_message('App', 'app')
  405. if 'partition-table' in actions:
  406. print_flashing_message('Partition Table', 'partition-table')
  407. if 'bootloader' in actions:
  408. print_flashing_message('Bootloader', 'bootloader')
  409. def execute_tasks(self, tasks: List, **kwargs: str) -> OrderedDict:
  410. ctx = click.get_current_context()
  411. global_args = PropertyDict(kwargs)
  412. # Show warning if some tasks are present several times in the list
  413. dupplicated_tasks = sorted(
  414. [item for item, count in Counter(task.name for task in tasks).items() if count > 1])
  415. if dupplicated_tasks:
  416. dupes = ', '.join('"%s"' % t for t in dupplicated_tasks)
  417. print_warning(
  418. 'WARNING: Command%s found in the list of commands more than once. ' %
  419. ('s %s are' % dupes if len(dupplicated_tasks) > 1 else ' %s is' % dupes) +
  420. 'Only first occurrence will be executed.')
  421. for task in tasks:
  422. # Set propagated global options.
  423. # These options may be set on one subcommand, but available in the list of global arguments
  424. for key in list(task.action_args):
  425. option = next((o for o in ctx.command.params if o.name == key), None)
  426. if option and (option.scope.is_global or option.scope.is_shared):
  427. local_value = task.action_args.pop(key)
  428. global_value = global_args[key]
  429. default = () if option.multiple else option.default
  430. if global_value != default and local_value != default and global_value != local_value:
  431. raise FatalError(
  432. 'Option "%s" provided for "%s" is already defined to a different value. '
  433. 'This option can appear at most once in the command line.' % (key, task.name))
  434. if local_value != default:
  435. global_args[key] = local_value
  436. # Show warnings about global arguments
  437. check_deprecation(ctx)
  438. # Make sure that define_cache_entry is mutable list and can be modified in callbacks
  439. global_args.define_cache_entry = list(global_args.define_cache_entry)
  440. # Execute all global action callback - first from idf.py itself, then from extensions
  441. for action_callback in ctx.command.global_action_callbacks:
  442. action_callback(ctx, global_args, tasks)
  443. # Build full list of tasks to and deal with dependencies and order dependencies
  444. tasks_to_run: OrderedDict = OrderedDict()
  445. while tasks:
  446. task = tasks[0]
  447. tasks_dict = dict([(t.name, t) for t in tasks])
  448. dependecies_processed = True
  449. # If task have some dependecies they have to be executed before the task.
  450. for dep in task.dependencies:
  451. if dep not in tasks_to_run.keys():
  452. # If dependent task is in the list of unprocessed tasks move to the front of the list
  453. if dep in tasks_dict.keys():
  454. dep_task = tasks.pop(tasks.index(tasks_dict[dep]))
  455. # Otherwise invoke it with default set of options
  456. # and put to the front of the list of unprocessed tasks
  457. else:
  458. print(
  459. 'Adding "%s"\'s dependency "%s" to list of commands with default set of options.' %
  460. (task.name, dep))
  461. dep_task = ctx.invoke(ctx.command.get_command(ctx, dep))
  462. # Remove options with global scope from invoke tasks because they are already in global_args
  463. for key in list(dep_task.action_args):
  464. option = next((o for o in ctx.command.params if o.name == key), None)
  465. if option and (option.scope.is_global or option.scope.is_shared):
  466. dep_task.action_args.pop(key)
  467. tasks.insert(0, dep_task)
  468. dependecies_processed = False
  469. # Order only dependencies are moved to the front of the queue if they present in command list
  470. for dep in task.order_dependencies:
  471. if dep in tasks_dict.keys() and dep not in tasks_to_run.keys():
  472. tasks.insert(0, tasks.pop(tasks.index(tasks_dict[dep])))
  473. dependecies_processed = False
  474. if dependecies_processed:
  475. # Remove task from list of unprocessed tasks
  476. tasks.pop(0)
  477. # And add to the queue
  478. if task.name not in tasks_to_run.keys():
  479. tasks_to_run.update([(task.name, task)])
  480. # Run all tasks in the queue
  481. # when global_args.dry_run is true idf.py works in idle mode and skips actual task execution
  482. if not global_args.dry_run:
  483. for task in tasks_to_run.values():
  484. name_with_aliases = task.name
  485. if task.aliases:
  486. name_with_aliases += ' (aliases: %s)' % ', '.join(task.aliases)
  487. # When machine-readable json format for help is printed, don't show info about executing action so the output is deserializable
  488. if name_with_aliases != 'help' or not task.action_args.get('json_option', False):
  489. print('Executing action: %s' % name_with_aliases)
  490. task(ctx, global_args, task.action_args)
  491. self._print_closing_message(global_args, tasks_to_run.keys())
  492. return tasks_to_run
  493. # That's a tiny parser that parse project-dir even before constructing
  494. # fully featured click parser to be sure that extensions are loaded from the right place
  495. @click.command(
  496. add_help_option=False,
  497. context_settings={
  498. 'allow_extra_args': True,
  499. 'ignore_unknown_options': True
  500. },
  501. )
  502. @click.option('-C', '--project-dir', default=os.getcwd(), type=click.Path())
  503. def parse_project_dir(project_dir: str) -> Any:
  504. return realpath(project_dir)
  505. # Set `complete_var` to not existing environment variable name to prevent early cmd completion
  506. project_dir = parse_project_dir(standalone_mode=False, complete_var='_IDF.PY_COMPLETE_NOT_EXISTING')
  507. all_actions: Dict = {}
  508. # Load extensions from components dir
  509. idf_py_extensions_path = os.path.join(os.environ['IDF_PATH'], 'tools', 'idf_py_actions')
  510. extension_dirs = [realpath(idf_py_extensions_path)]
  511. extra_paths = os.environ.get('IDF_EXTRA_ACTIONS_PATH')
  512. if extra_paths is not None:
  513. for path in extra_paths.split(';'):
  514. path = realpath(path)
  515. if path not in extension_dirs:
  516. extension_dirs.append(path)
  517. extensions = []
  518. for directory in extension_dirs:
  519. if directory and not os.path.exists(directory):
  520. print_warning('WARNING: Directory with idf.py extensions doesn\'t exist:\n %s' % directory)
  521. continue
  522. sys.path.append(directory)
  523. for _finder, name, _ispkg in sorted(iter_modules([directory])):
  524. if name.endswith('_ext'):
  525. extensions.append((name, import_module(name)))
  526. # Load component manager idf.py extensions if not explicitly disabled
  527. if os.getenv('IDF_COMPONENT_MANAGER') != '0':
  528. extensions.append(('component_manager_ext', idf_extensions))
  529. # Optional load `pyclang` for additional clang-tidy related functionalities
  530. try:
  531. from pyclang import idf_extension
  532. extensions.append(('idf_clang_tidy_ext', idf_extension))
  533. except ImportError:
  534. pass
  535. for name, extension in extensions:
  536. try:
  537. all_actions = merge_action_lists(all_actions, extension.action_extensions(all_actions, project_dir))
  538. except AttributeError:
  539. print_warning('WARNING: Cannot load idf.py extension "%s"' % name)
  540. # Load extensions from project dir
  541. if os.path.exists(os.path.join(project_dir, 'idf_ext.py')):
  542. sys.path.append(project_dir)
  543. try:
  544. from idf_ext import action_extensions
  545. except ImportError:
  546. print_warning('Error importing extension file idf_ext.py. Skipping.')
  547. print_warning(
  548. "Please make sure that it contains implementation (even if it's empty) of add_action_extensions")
  549. try:
  550. all_actions = merge_action_lists(all_actions, action_extensions(all_actions, project_dir))
  551. except NameError:
  552. pass
  553. cli_help = (
  554. 'ESP-IDF CLI build management tool. '
  555. 'For commands that are not known to idf.py an attempt to execute it as a build system target will be made. '
  556. 'Selected target: {}'.format(get_target(project_dir)))
  557. return CLI(help=cli_help, verbose_output=verbose_output, all_actions=all_actions)
  558. def signal_handler(_signal: int, _frame: Optional[FrameType]) -> None:
  559. # The Ctrl+C processed by other threads inside
  560. pass
  561. def main() -> None:
  562. # Processing of Ctrl+C event for all threads made by main()
  563. signal.signal(signal.SIGINT, signal_handler)
  564. # Check the environment only when idf.py is invoked regularly from command line.
  565. checks_output = None if SHELL_COMPLETE_RUN else check_environment()
  566. try:
  567. cli = init_cli(verbose_output=checks_output)
  568. except ImportError:
  569. if SHELL_COMPLETE_RUN:
  570. pass
  571. else:
  572. raise
  573. else:
  574. cli(sys.argv[1:], prog_name=PROG, complete_var=SHELL_COMPLETE_VAR)
  575. def _valid_unicode_config() -> Union[codecs.CodecInfo, bool]:
  576. # Python 2 is always good
  577. if sys.version_info[0] == 2:
  578. return True
  579. # With python 3 unicode environment is required
  580. try:
  581. return codecs.lookup(locale.getpreferredencoding()).name != 'ascii'
  582. except Exception:
  583. return False
  584. def _find_usable_locale() -> str:
  585. try:
  586. locales = subprocess.Popen(['locale', '-a'], stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0].decode('ascii', 'replace')
  587. except OSError:
  588. locales = ''
  589. usable_locales: List[str] = []
  590. for line in locales.splitlines():
  591. locale = line.strip()
  592. locale_name = locale.lower().replace('-', '')
  593. # C.UTF-8 is the best option, if supported
  594. if locale_name == 'c.utf8':
  595. return locale
  596. if locale_name.endswith('.utf8'):
  597. # Make a preference of english locales
  598. if locale.startswith('en_'):
  599. usable_locales.insert(0, locale)
  600. else:
  601. usable_locales.append(locale)
  602. if not usable_locales:
  603. raise FatalError(
  604. 'Support for Unicode filenames is required, but no suitable UTF-8 locale was found on your system.'
  605. ' Please refer to the manual for your operating system for details on locale reconfiguration.')
  606. return usable_locales[0]
  607. if __name__ == '__main__':
  608. try:
  609. if 'MSYSTEM' in os.environ:
  610. print_warning(
  611. 'MSys/Mingw is no longer supported. Please follow the getting started guide of the '
  612. 'documentation in order to set up a suitiable environment, or continue at your own risk.')
  613. elif os.name == 'posix' and not _valid_unicode_config():
  614. # Trying to find best utf-8 locale available on the system and restart python with it
  615. best_locale = _find_usable_locale()
  616. print_warning(
  617. 'Your environment is not configured to handle unicode filenames outside of ASCII range.'
  618. ' Environment variable LC_ALL is temporary set to %s for unicode support.' % best_locale)
  619. os.environ['LC_ALL'] = best_locale
  620. ret = subprocess.call([sys.executable] + sys.argv, env=os.environ)
  621. if ret:
  622. raise SystemExit(ret)
  623. else:
  624. main()
  625. except FatalError as e:
  626. print(e, file=sys.stderr)
  627. sys.exit(2)