idf.py 33 KB

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