idf.py 33 KB

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