idf.py 35 KB

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