idf.py 33 KB

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