idf.py 32 KB

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