idf.py 28 KB

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