idf.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804
  1. #!/usr/bin/env python
  2. #
  3. # SPDX-FileCopyrightText: 2019-2022 Espressif Systems (Shanghai) CO LTD
  4. #
  5. # SPDX-License-Identifier: Apache-2.0
  6. #
  7. # 'idf.py' is a top-level config/build command line tool for ESP-IDF
  8. #
  9. # You don't have to use idf.py, you can use cmake directly
  10. # (or use cmake in an IDE)
  11. # WARNING: we don't check for Python build-time dependencies until
  12. # check_environment() function below. If possible, avoid importing
  13. # any external libraries here - put in external script, or import in
  14. # their specific function instead.
  15. from __future__ import annotations
  16. import codecs
  17. import json
  18. import locale
  19. import os
  20. import os.path
  21. import signal
  22. import subprocess
  23. import sys
  24. from collections import Counter, OrderedDict, _OrderedDictKeysView
  25. from importlib import import_module
  26. from pkgutil import iter_modules
  27. from types import FrameType
  28. from typing import Any, Callable, Dict, List, Optional, TextIO, Union
  29. # pyc files remain in the filesystem when switching between branches which might raise errors for incompatible
  30. # idf.py extensions. Therefore, pyc file generation is turned off:
  31. sys.dont_write_bytecode = True
  32. import python_version_checker # noqa: E402
  33. try:
  34. from idf_py_actions.errors import FatalError # noqa: E402
  35. from idf_py_actions.tools import (PropertyDict, executable_exists, get_target, idf_version, # noqa: E402
  36. merge_action_lists, realpath)
  37. 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. no_args_is_help=True,
  308. context_settings={'max_content_width': 140},
  309. help=help,
  310. )
  311. self._actions = {}
  312. self.global_action_callbacks = []
  313. self.commands_with_aliases = {}
  314. if verbose_output is None:
  315. verbose_output = []
  316. self.verbose_output = verbose_output
  317. if all_actions is None:
  318. all_actions = {}
  319. shared_options = []
  320. # Global options
  321. for option_args in all_actions.get('global_options', []):
  322. option = Option(**option_args)
  323. self.params.append(option)
  324. if option.scope.is_shared:
  325. shared_options.append(option)
  326. # Global options validators
  327. self.global_action_callbacks = all_actions.get('global_action_callbacks', [])
  328. # Actions
  329. for name, action in all_actions.get('actions', {}).items():
  330. arguments = action.pop('arguments', [])
  331. options = action.pop('options', [])
  332. if arguments is None:
  333. arguments = []
  334. if options is None:
  335. options = []
  336. self._actions[name] = Action(name=name, **action)
  337. for alias in [name] + action.get('aliases', []):
  338. self.commands_with_aliases[alias] = name
  339. for argument_args in arguments:
  340. self._actions[name].params.append(Argument(**argument_args))
  341. # Add all shared options
  342. for option in shared_options:
  343. self._actions[name].params.append(option)
  344. for option_args in options:
  345. option = Option(**option_args)
  346. if option.scope.is_shared:
  347. raise FatalError(
  348. '"%s" is defined for action "%s". '
  349. ' "shared" options can be declared only on global level' % (option.name, name))
  350. # Promote options to global if see for the first time
  351. if option.scope.is_global and option.name not in [o.name for o in self.params]:
  352. self.params.append(option)
  353. self._actions[name].params.append(option)
  354. def list_commands(self, ctx: click.core.Context) -> List:
  355. return sorted(filter(lambda name: not self._actions[name].hidden, self._actions))
  356. def get_command(self, ctx: click.core.Context, name: str) -> Optional[Action]:
  357. if name in self.commands_with_aliases:
  358. return self._actions.get(self.commands_with_aliases.get(name))
  359. # Trying fallback to build target (from "all" action) if command is not known
  360. else:
  361. callback = self._actions.get('fallback')
  362. if callback:
  363. return Action(name=name, callback=callback.unwrapped_callback)
  364. return None
  365. def _print_closing_message(self, args: PropertyDict, actions: _OrderedDictKeysView) -> None:
  366. # print a closing message of some kind
  367. #
  368. if any(t in str(actions) for t in ('flash', 'dfu', 'uf2', 'uf2-app')):
  369. print('Done')
  370. return
  371. if not os.path.exists(os.path.join(args.build_dir, 'flasher_args.json')):
  372. print('Done')
  373. return
  374. # Otherwise, if we built any binaries print a message about
  375. # how to flash them
  376. def print_flashing_message(title: str, key: str) -> None:
  377. with open(os.path.join(args.build_dir, 'flasher_args.json')) as file:
  378. flasher_args: Dict[str, Any] = json.load(file)
  379. def flasher_path(f: Union[str, os.PathLike[str]]) -> str:
  380. if type(args.build_dir) is bytes:
  381. args.build_dir = args.build_dir.decode()
  382. return _safe_relpath(os.path.join(args.build_dir, f))
  383. if key != 'project': # flashing a single item
  384. if key not in flasher_args:
  385. # This is the case for 'idf.py bootloader' if Secure Boot is on, need to follow manual flashing steps
  386. print('\n%s build complete.' % title)
  387. return
  388. cmd = ''
  389. if (key == 'bootloader'): # bootloader needs --flash-mode, etc to be passed in
  390. cmd = ' '.join(flasher_args['write_flash_args']) + ' '
  391. cmd += flasher_args[key]['offset'] + ' '
  392. cmd += flasher_path(flasher_args[key]['file'])
  393. else: # flashing the whole project
  394. cmd = ' '.join(flasher_args['write_flash_args']) + ' '
  395. flash_items = sorted(
  396. ((o, f) for (o, f) in flasher_args['flash_files'].items() if len(o) > 0),
  397. key=lambda x: int(x[0], 0),
  398. )
  399. for o, f in flash_items:
  400. cmd += o + ' ' + flasher_path(f) + ' '
  401. print('\n%s build complete. To flash, run this command:' % title)
  402. print(
  403. '%s %s -p %s -b %s --before %s --after %s --chip %s %s write_flash %s' % (
  404. PYTHON,
  405. _safe_relpath('%s/components/esptool_py/esptool/esptool.py' % os.environ['IDF_PATH']),
  406. args.port or '(PORT)',
  407. args.baud,
  408. flasher_args['extra_esptool_args']['before'],
  409. flasher_args['extra_esptool_args']['after'],
  410. flasher_args['extra_esptool_args']['chip'],
  411. '--no-stub' if not flasher_args['extra_esptool_args']['stub'] else '',
  412. cmd.strip(),
  413. ))
  414. print(
  415. "or run 'idf.py -p %s %s'" % (
  416. args.port or '(PORT)',
  417. key + '-flash' if key != 'project' else 'flash',
  418. ))
  419. if 'all' in actions or 'build' in actions:
  420. print_flashing_message('Project', 'project')
  421. else:
  422. if 'app' in actions:
  423. print_flashing_message('App', 'app')
  424. if 'partition-table' in actions:
  425. print_flashing_message('Partition Table', 'partition-table')
  426. if 'bootloader' in actions:
  427. print_flashing_message('Bootloader', 'bootloader')
  428. def execute_tasks(self, tasks: List, **kwargs: str) -> OrderedDict:
  429. ctx = click.get_current_context()
  430. global_args = PropertyDict(kwargs)
  431. # Show warning if some tasks are present several times in the list
  432. dupplicated_tasks = sorted(
  433. [item for item, count in Counter(task.name for task in tasks).items() if count > 1])
  434. if dupplicated_tasks:
  435. dupes = ', '.join('"%s"' % t for t in dupplicated_tasks)
  436. print_warning(
  437. 'WARNING: Command%s found in the list of commands more than once. ' %
  438. ('s %s are' % dupes if len(dupplicated_tasks) > 1 else ' %s is' % dupes) +
  439. 'Only first occurrence will be executed.')
  440. for task in tasks:
  441. # Set propagated global options.
  442. # These options may be set on one subcommand, but available in the list of global arguments
  443. for key in list(task.action_args):
  444. option = next((o for o in ctx.command.params if o.name == key), None)
  445. if option and (option.scope.is_global or option.scope.is_shared):
  446. local_value = task.action_args.pop(key)
  447. global_value = global_args[key]
  448. default = () if option.multiple else option.default
  449. if global_value != default and local_value != default and global_value != local_value:
  450. raise FatalError(
  451. 'Option "%s" provided for "%s" is already defined to a different value. '
  452. 'This option can appear at most once in the command line.' % (key, task.name))
  453. if local_value != default:
  454. global_args[key] = local_value
  455. # Show warnings about global arguments
  456. check_deprecation(ctx)
  457. # Make sure that define_cache_entry is mutable list and can be modified in callbacks
  458. global_args.define_cache_entry = list(global_args.define_cache_entry)
  459. # Execute all global action callback - first from idf.py itself, then from extensions
  460. for action_callback in ctx.command.global_action_callbacks:
  461. action_callback(ctx, global_args, tasks)
  462. # Build full list of tasks to and deal with dependencies and order dependencies
  463. tasks_to_run: OrderedDict = OrderedDict()
  464. while tasks:
  465. task = tasks[0]
  466. tasks_dict = dict([(t.name, t) for t in tasks])
  467. dependecies_processed = True
  468. # If task have some dependecies they have to be executed before the task.
  469. for dep in task.dependencies:
  470. if dep not in tasks_to_run.keys():
  471. # If dependent task is in the list of unprocessed tasks move to the front of the list
  472. if dep in tasks_dict.keys():
  473. dep_task = tasks.pop(tasks.index(tasks_dict[dep]))
  474. # Otherwise invoke it with default set of options
  475. # and put to the front of the list of unprocessed tasks
  476. else:
  477. print(
  478. 'Adding "%s"\'s dependency "%s" to list of commands with default set of options.' %
  479. (task.name, dep))
  480. dep_task = ctx.invoke(ctx.command.get_command(ctx, dep))
  481. # Remove options with global scope from invoke tasks because they are already in global_args
  482. for key in list(dep_task.action_args):
  483. option = next((o for o in ctx.command.params if o.name == key), None)
  484. if option and (option.scope.is_global or option.scope.is_shared):
  485. dep_task.action_args.pop(key)
  486. tasks.insert(0, dep_task)
  487. dependecies_processed = False
  488. # Order only dependencies are moved to the front of the queue if they present in command list
  489. for dep in task.order_dependencies:
  490. if dep in tasks_dict.keys() and dep not in tasks_to_run.keys():
  491. tasks.insert(0, tasks.pop(tasks.index(tasks_dict[dep])))
  492. dependecies_processed = False
  493. if dependecies_processed:
  494. # Remove task from list of unprocessed tasks
  495. tasks.pop(0)
  496. # And add to the queue
  497. if task.name not in tasks_to_run.keys():
  498. tasks_to_run.update([(task.name, task)])
  499. # Run all tasks in the queue
  500. # when global_args.dry_run is true idf.py works in idle mode and skips actual task execution
  501. if not global_args.dry_run:
  502. for task in tasks_to_run.values():
  503. name_with_aliases = task.name
  504. if task.aliases:
  505. name_with_aliases += ' (aliases: %s)' % ', '.join(task.aliases)
  506. # When machine-readable json format for help is printed, don't show info about executing action so the output is deserializable
  507. if name_with_aliases != 'help' or not task.action_args.get('json_option', False):
  508. print('Executing action: %s' % name_with_aliases)
  509. task(ctx, global_args, task.action_args)
  510. self._print_closing_message(global_args, tasks_to_run.keys())
  511. return tasks_to_run
  512. # That's a tiny parser that parse project-dir even before constructing
  513. # fully featured click parser to be sure that extensions are loaded from the right place
  514. @click.command(
  515. add_help_option=False,
  516. context_settings={
  517. 'allow_extra_args': True,
  518. 'ignore_unknown_options': True
  519. },
  520. )
  521. @click.option('-C', '--project-dir', default=os.getcwd(), type=click.Path())
  522. def parse_project_dir(project_dir: str) -> Any:
  523. return realpath(project_dir)
  524. # Set `complete_var` to not existing environment variable name to prevent early cmd completion
  525. project_dir = parse_project_dir(standalone_mode=False, complete_var='_IDF.PY_COMPLETE_NOT_EXISTING')
  526. all_actions: Dict = {}
  527. # Load extensions from components dir
  528. idf_py_extensions_path = os.path.join(os.environ['IDF_PATH'], 'tools', 'idf_py_actions')
  529. extension_dirs = [realpath(idf_py_extensions_path)]
  530. extra_paths = os.environ.get('IDF_EXTRA_ACTIONS_PATH')
  531. if extra_paths is not None:
  532. for path in extra_paths.split(';'):
  533. path = realpath(path)
  534. if path not in extension_dirs:
  535. extension_dirs.append(path)
  536. extensions = []
  537. for directory in extension_dirs:
  538. if directory and not os.path.exists(directory):
  539. print_warning('WARNING: Directory with idf.py extensions doesn\'t exist:\n %s' % directory)
  540. continue
  541. sys.path.append(directory)
  542. for _finder, name, _ispkg in sorted(iter_modules([directory])):
  543. if name.endswith('_ext'):
  544. extensions.append((name, import_module(name)))
  545. # Load component manager idf.py extensions if not explicitly disabled
  546. if os.getenv('IDF_COMPONENT_MANAGER') != '0':
  547. from idf_component_manager import idf_extensions
  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 signal_handler(_signal: int, _frame: Optional[FrameType]) -> None:
  579. # The Ctrl+C processed by other threads inside
  580. pass
  581. def main() -> None:
  582. # Processing of Ctrl+C event for all threads made by main()
  583. signal.signal(signal.SIGINT, signal_handler)
  584. # Check the environment only when idf.py is invoked regularly from command line.
  585. checks_output = None if SHELL_COMPLETE_RUN else check_environment()
  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. cli(sys.argv[1:], prog_name=PROG, complete_var=SHELL_COMPLETE_VAR)
  595. def _valid_unicode_config() -> Union[codecs.CodecInfo, bool]:
  596. # Python 2 is always good
  597. if sys.version_info[0] == 2:
  598. return True
  599. # With python 3 unicode environment is required
  600. try:
  601. return codecs.lookup(locale.getpreferredencoding()).name != 'ascii'
  602. except Exception:
  603. return False
  604. def _find_usable_locale() -> str:
  605. try:
  606. locales = subprocess.Popen(['locale', '-a'], stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0].decode('ascii', 'replace')
  607. except OSError:
  608. locales = ''
  609. usable_locales: List[str] = []
  610. for line in locales.splitlines():
  611. locale = line.strip()
  612. locale_name = locale.lower().replace('-', '')
  613. # C.UTF-8 is the best option, if supported
  614. if locale_name == 'c.utf8':
  615. return locale
  616. if locale_name.endswith('.utf8'):
  617. # Make a preference of english locales
  618. if locale.startswith('en_'):
  619. usable_locales.insert(0, locale)
  620. else:
  621. usable_locales.append(locale)
  622. if not usable_locales:
  623. raise FatalError(
  624. 'Support for Unicode filenames is required, but no suitable UTF-8 locale was found on your system.'
  625. ' Please refer to the manual for your operating system for details on locale reconfiguration.')
  626. return usable_locales[0]
  627. if __name__ == '__main__':
  628. try:
  629. if 'MSYSTEM' in os.environ:
  630. print_warning(
  631. 'MSys/Mingw is no longer supported. Please follow the getting started guide of the '
  632. 'documentation in order to set up a suitiable environment, or continue at your own risk.')
  633. elif os.name == 'posix' and not _valid_unicode_config():
  634. # Trying to find best utf-8 locale available on the system and restart python with it
  635. best_locale = _find_usable_locale()
  636. print_warning(
  637. 'Your environment is not configured to handle unicode filenames outside of ASCII range.'
  638. ' Environment variable LC_ALL is temporary set to %s for unicode support.' % best_locale)
  639. os.environ['LC_ALL'] = best_locale
  640. ret = subprocess.call([sys.executable] + sys.argv, env=os.environ)
  641. if ret:
  642. raise SystemExit(ret)
  643. else:
  644. main()
  645. except FatalError as e:
  646. print(e, file=sys.stderr)
  647. sys.exit(2)