idf.py 36 KB

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