idf.py 32 KB

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