idf.py 33 KB

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