idf.py 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389
  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 fnmatch
  30. import json
  31. import locale
  32. import multiprocessing
  33. import os
  34. import os.path
  35. import re
  36. import shutil
  37. import subprocess
  38. import sys
  39. class FatalError(RuntimeError):
  40. """
  41. Wrapper class for runtime errors that aren't caused by bugs in idf.py or the build proces.s
  42. """
  43. pass
  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", sys.argv[0])
  52. # Make flavors, across the various kinds of Windows environments & POSIX...
  53. if "MSYSTEM" in os.environ: # MSYS
  54. MAKE_CMD = "make"
  55. MAKE_GENERATOR = "MSYS Makefiles"
  56. elif os.name == "nt": # other Windows
  57. MAKE_CMD = "mingw32-make"
  58. MAKE_GENERATOR = "MinGW Makefiles"
  59. else:
  60. MAKE_CMD = "make"
  61. MAKE_GENERATOR = "Unix Makefiles"
  62. GENERATORS = [
  63. # ('generator name', 'build command line', 'version command line', 'verbose flag')
  64. ("Ninja", ["ninja"], ["ninja", "--version"], "-v"),
  65. (
  66. MAKE_GENERATOR,
  67. [MAKE_CMD, "-j", str(multiprocessing.cpu_count() + 2)],
  68. [MAKE_CMD, "--version"],
  69. "VERBOSE=1",
  70. ),
  71. ]
  72. GENERATOR_CMDS = dict((a[0], a[1]) for a in GENERATORS)
  73. GENERATOR_VERBOSE = dict((a[0], a[3]) for a in GENERATORS)
  74. def _run_tool(tool_name, args, cwd):
  75. def quote_arg(arg):
  76. " Quote 'arg' if necessary "
  77. if " " in arg and not (arg.startswith('"') or arg.startswith("'")):
  78. return "'" + arg + "'"
  79. return arg
  80. args = [str(arg) for arg in args]
  81. display_args = " ".join(quote_arg(arg) for arg in args)
  82. print("Running %s in directory %s" % (tool_name, quote_arg(cwd)))
  83. print('Executing "%s"...' % str(display_args))
  84. try:
  85. # Note: we explicitly pass in os.environ here, as we may have set IDF_PATH there during startup
  86. subprocess.check_call(args, env=os.environ, cwd=cwd)
  87. except subprocess.CalledProcessError as e:
  88. raise FatalError("%s failed with exit code %d" % (tool_name, e.returncode))
  89. def _realpath(path):
  90. """
  91. Return the cannonical path with normalized case.
  92. It is useful on Windows to comparision paths in case-insensitive manner.
  93. On Unix and Mac OS X it works as `os.path.realpath()` only.
  94. """
  95. return os.path.normcase(os.path.realpath(path))
  96. def check_environment():
  97. """
  98. Verify the environment contains the top-level tools we need to operate
  99. (cmake will check a lot of other things)
  100. """
  101. if not executable_exists(["cmake", "--version"]):
  102. raise FatalError("'cmake' must be available on the PATH to use %s" % PROG)
  103. # find the directory idf.py is in, then the parent directory of this, and assume this is IDF_PATH
  104. detected_idf_path = _realpath(os.path.join(os.path.dirname(__file__), ".."))
  105. if "IDF_PATH" in os.environ:
  106. set_idf_path = _realpath(os.environ["IDF_PATH"])
  107. if set_idf_path != detected_idf_path:
  108. print(
  109. "WARNING: IDF_PATH environment variable is set to %s but %s path indicates IDF directory %s. "
  110. "Using the environment variable directory, but results may be unexpected..."
  111. % (set_idf_path, PROG, detected_idf_path)
  112. )
  113. else:
  114. print("Setting IDF_PATH environment variable: %s" % detected_idf_path)
  115. os.environ["IDF_PATH"] = detected_idf_path
  116. # check Python dependencies
  117. print("Checking Python dependencies...")
  118. try:
  119. subprocess.check_call(
  120. [
  121. os.environ["PYTHON"],
  122. os.path.join(
  123. os.environ["IDF_PATH"], "tools", "check_python_dependencies.py"
  124. ),
  125. ],
  126. env=os.environ,
  127. )
  128. except subprocess.CalledProcessError:
  129. raise SystemExit(1)
  130. def executable_exists(args):
  131. try:
  132. subprocess.check_output(args)
  133. return True
  134. except Exception:
  135. return False
  136. def detect_cmake_generator():
  137. """
  138. Find the default cmake generator, if none was specified. Raises an exception if no valid generator is found.
  139. """
  140. for (generator, _, version_check, _) in GENERATORS:
  141. if executable_exists(version_check):
  142. return generator
  143. raise FatalError(
  144. "To use %s, either the 'ninja' or 'GNU make' build tool must be available in the PATH"
  145. % PROG
  146. )
  147. def _strip_quotes(value, regexp=re.compile(r"^\"(.*)\"$|^'(.*)'$|^(.*)$")):
  148. """
  149. Strip quotes like CMake does during parsing cache entries
  150. """
  151. return [x for x in regexp.match(value).groups() if x is not None][0].rstrip()
  152. def _new_cmakecache_entries(cache_path, new_cache_entries):
  153. if not os.path.exists(cache_path):
  154. return True
  155. if new_cache_entries:
  156. current_cache = parse_cmakecache(cache_path)
  157. for entry in new_cache_entries:
  158. key, value = entry.split("=", 1)
  159. current_value = current_cache.get(key, None)
  160. if current_value is None or _strip_quotes(value) != current_value:
  161. return True
  162. return False
  163. def _ensure_build_directory(args, always_run_cmake=False):
  164. """Check the build directory exists and that cmake has been run there.
  165. If this isn't the case, create the build directory (if necessary) and
  166. do an initial cmake run to configure it.
  167. This function will also check args.generator parameter. If the parameter is incompatible with
  168. the build directory, an error is raised. If the parameter is None, this function will set it to
  169. an auto-detected default generator or to the value already configured in the build directory.
  170. """
  171. project_dir = args.project_dir
  172. # Verify the project directory
  173. if not os.path.isdir(project_dir):
  174. if not os.path.exists(project_dir):
  175. raise FatalError("Project directory %s does not exist" % project_dir)
  176. else:
  177. raise FatalError("%s must be a project directory" % project_dir)
  178. if not os.path.exists(os.path.join(project_dir, "CMakeLists.txt")):
  179. raise FatalError(
  180. "CMakeLists.txt not found in project directory %s" % project_dir
  181. )
  182. # Verify/create the build directory
  183. build_dir = args.build_dir
  184. if not os.path.isdir(build_dir):
  185. os.makedirs(build_dir)
  186. cache_path = os.path.join(build_dir, "CMakeCache.txt")
  187. args.define_cache_entry = list(args.define_cache_entry)
  188. args.define_cache_entry.append("CCACHE_ENABLE=%d" % args.ccache)
  189. if always_run_cmake or _new_cmakecache_entries(cache_path, args.define_cache_entry):
  190. if args.generator is None:
  191. args.generator = detect_cmake_generator()
  192. try:
  193. cmake_args = [
  194. "cmake",
  195. "-G",
  196. args.generator,
  197. "-DPYTHON_DEPS_CHECKED=1",
  198. "-DESP_PLATFORM=1",
  199. ]
  200. if not args.no_warnings:
  201. cmake_args += ["--warn-uninitialized"]
  202. cmake_args += ["-DWARN_UNINITIALIZED=1"]
  203. if args.define_cache_entry:
  204. cmake_args += ["-D" + d for d in args.define_cache_entry]
  205. cmake_args += [project_dir]
  206. _run_tool("cmake", cmake_args, cwd=args.build_dir)
  207. except Exception:
  208. # don't allow partially valid CMakeCache.txt files,
  209. # to keep the "should I run cmake?" logic simple
  210. if os.path.exists(cache_path):
  211. os.remove(cache_path)
  212. raise
  213. # Learn some things from the CMakeCache.txt file in the build directory
  214. cache = parse_cmakecache(cache_path)
  215. try:
  216. generator = cache["CMAKE_GENERATOR"]
  217. except KeyError:
  218. generator = detect_cmake_generator()
  219. if args.generator is None:
  220. args.generator = (
  221. generator
  222. ) # reuse the previously configured generator, if none was given
  223. if generator != args.generator:
  224. raise FatalError(
  225. "Build is configured for generator '%s' not '%s'. Run '%s fullclean' to start again."
  226. % (generator, args.generator, PROG)
  227. )
  228. try:
  229. home_dir = cache["CMAKE_HOME_DIRECTORY"]
  230. if _realpath(home_dir) != _realpath(project_dir):
  231. raise FatalError(
  232. "Build directory '%s' configured for project '%s' not '%s'. Run '%s fullclean' to start again."
  233. % (build_dir, _realpath(home_dir), _realpath(project_dir), PROG)
  234. )
  235. except KeyError:
  236. pass # if cmake failed part way, CMAKE_HOME_DIRECTORY may not be set yet
  237. def parse_cmakecache(path):
  238. """
  239. Parse the CMakeCache file at 'path'.
  240. Returns a dict of name:value.
  241. CMakeCache entries also each have a "type", but this is currently ignored.
  242. """
  243. result = {}
  244. with open(path) as f:
  245. for line in f:
  246. # cmake cache lines look like: CMAKE_CXX_FLAGS_DEBUG:STRING=-g
  247. # groups are name, type, value
  248. m = re.match(r"^([^#/:=]+):([^:=]+)=(.*)\n$", line)
  249. if m:
  250. result[m.group(1)] = m.group(3)
  251. return result
  252. def build_target(target_name, ctx, args):
  253. """
  254. Execute the target build system to build target 'target_name'
  255. Calls _ensure_build_directory() which will run cmake to generate a build
  256. directory (with the specified generator) as needed.
  257. """
  258. _ensure_build_directory(args)
  259. generator_cmd = GENERATOR_CMDS[args.generator]
  260. if args.ccache:
  261. # Setting CCACHE_BASEDIR & CCACHE_NO_HASHDIR ensures that project paths aren't stored in the ccache entries
  262. # (this means ccache hits can be shared between different projects. It may mean that some debug information
  263. # will point to files in another project, if these files are perfect duplicates of each other.)
  264. #
  265. # It would be nicer to set these from cmake, but there's no cross-platform way to set build-time environment
  266. # os.environ["CCACHE_BASEDIR"] = args.build_dir
  267. # os.environ["CCACHE_NO_HASHDIR"] = "1"
  268. pass
  269. if args.verbose:
  270. generator_cmd += [GENERATOR_VERBOSE[args.generator]]
  271. _run_tool(generator_cmd[0], generator_cmd + [target_name], args.build_dir)
  272. def _get_esptool_args(args):
  273. esptool_path = os.path.join(
  274. os.environ["IDF_PATH"], "components/esptool_py/esptool/esptool.py"
  275. )
  276. if args.port is None:
  277. args.port = get_default_serial_port()
  278. result = [PYTHON, esptool_path]
  279. result += ["-p", args.port]
  280. result += ["-b", str(args.baud)]
  281. with open(os.path.join(args.build_dir, "flasher_args.json")) as f:
  282. flasher_args = json.load(f)
  283. extra_esptool_args = flasher_args["extra_esptool_args"]
  284. result += ["--before", extra_esptool_args["before"]]
  285. result += ["--after", extra_esptool_args["after"]]
  286. return result
  287. def flash(action, ctx, args):
  288. """
  289. Run esptool to flash the entire project, from an argfile generated by the build system
  290. """
  291. flasher_args_path = { # action -> name of flasher args file generated by build system
  292. "bootloader-flash": "flash_bootloader_args",
  293. "partition_table-flash": "flash_partition_table_args",
  294. "app-flash": "flash_app_args",
  295. "flash": "flash_project_args",
  296. "encrypted-app-flash": "flash_encrypted_app_args",
  297. "encrypted-flash": "flash_encrypted_project_args",
  298. }[
  299. action
  300. ]
  301. esptool_args = _get_esptool_args(args)
  302. esptool_args += ["write_flash", "@" + flasher_args_path]
  303. _run_tool("esptool.py", esptool_args, args.build_dir)
  304. def erase_flash(action, ctx, args):
  305. esptool_args = _get_esptool_args(args)
  306. esptool_args += ["erase_flash"]
  307. _run_tool("esptool.py", esptool_args, args.build_dir)
  308. def monitor(action, ctx, args, print_filter, monitor_baud, encrypted):
  309. """
  310. Run idf_monitor.py to watch build output
  311. """
  312. if args.port is None:
  313. args.port = get_default_serial_port()
  314. desc_path = os.path.join(args.build_dir, "project_description.json")
  315. if not os.path.exists(desc_path):
  316. _ensure_build_directory(args)
  317. with open(desc_path, "r") as f:
  318. project_desc = json.load(f)
  319. elf_file = os.path.join(args.build_dir, project_desc["app_elf"])
  320. if not os.path.exists(elf_file):
  321. raise FatalError(
  322. "ELF file '%s' not found. You need to build & flash the project before running 'monitor', "
  323. "and the binary on the device must match the one in the build directory exactly. "
  324. "Try '%s flash monitor'." % (elf_file, PROG)
  325. )
  326. idf_monitor = os.path.join(os.environ["IDF_PATH"], "tools/idf_monitor.py")
  327. monitor_args = [PYTHON, idf_monitor]
  328. if args.port is not None:
  329. monitor_args += ["-p", args.port]
  330. if not monitor_baud:
  331. if os.getenv("IDF_MONITOR_BAUD"):
  332. monitor_baud = os.getenv("IDF_MONITOR_BAUD", None)
  333. elif os.getenv("MONITORBAUD"):
  334. monitor_baud = os.getenv("MONITORBAUD", None)
  335. else:
  336. monitor_baud = project_desc["monitor_baud"]
  337. monitor_args += ["-b", monitor_baud]
  338. if print_filter is not None:
  339. monitor_args += ["--print_filter", print_filter]
  340. monitor_args += [elf_file]
  341. if encrypted:
  342. monitor_args += ['--encrypted']
  343. idf_py = [PYTHON] + get_commandline_options(ctx) # commands to re-run idf.py
  344. monitor_args += ["-m", " ".join("'%s'" % a for a in idf_py)]
  345. if "MSYSTEM" in os.environ:
  346. monitor_args = ["winpty"] + monitor_args
  347. _run_tool("idf_monitor", monitor_args, args.project_dir)
  348. def clean(action, ctx, args):
  349. if not os.path.isdir(args.build_dir):
  350. print("Build directory '%s' not found. Nothing to clean." % args.build_dir)
  351. return
  352. build_target("clean", ctx, args)
  353. def reconfigure(action, ctx, args):
  354. _ensure_build_directory(args, True)
  355. def _delete_windows_symlinks(directory):
  356. """
  357. It deletes symlinks recursively on Windows. It is useful for Python 2 which doesn't detect symlinks on Windows.
  358. """
  359. deleted_paths = []
  360. if os.name == "nt":
  361. import ctypes
  362. for root, dirnames, _filenames in os.walk(directory):
  363. for d in dirnames:
  364. full_path = os.path.join(root, d)
  365. try:
  366. full_path = full_path.decode("utf-8")
  367. except Exception:
  368. pass
  369. if ctypes.windll.kernel32.GetFileAttributesW(full_path) & 0x0400:
  370. os.rmdir(full_path)
  371. deleted_paths.append(full_path)
  372. return deleted_paths
  373. def fullclean(action, ctx, args):
  374. build_dir = args.build_dir
  375. if not os.path.isdir(build_dir):
  376. print("Build directory '%s' not found. Nothing to clean." % build_dir)
  377. return
  378. if len(os.listdir(build_dir)) == 0:
  379. print("Build directory '%s' is empty. Nothing to clean." % build_dir)
  380. return
  381. if not os.path.exists(os.path.join(build_dir, "CMakeCache.txt")):
  382. raise FatalError(
  383. "Directory '%s' doesn't seem to be a CMake build directory. Refusing to automatically "
  384. "delete files in this directory. Delete the directory manually to 'clean' it."
  385. % build_dir
  386. )
  387. red_flags = ["CMakeLists.txt", ".git", ".svn"]
  388. for red in red_flags:
  389. red = os.path.join(build_dir, red)
  390. if os.path.exists(red):
  391. raise FatalError(
  392. "Refusing to automatically delete files in directory containing '%s'. Delete files manually if you're sure."
  393. % red
  394. )
  395. # OK, delete everything in the build directory...
  396. # Note: Python 2.7 doesn't detect symlinks on Windows (it is supported form 3.2). Tools promising to not
  397. # follow symlinks will actually follow them. Deleting the build directory with symlinks deletes also items
  398. # outside of this directory.
  399. deleted_symlinks = _delete_windows_symlinks(build_dir)
  400. if args.verbose and len(deleted_symlinks) > 1:
  401. print(
  402. "The following symlinks were identified and removed:\n%s"
  403. % "\n".join(deleted_symlinks)
  404. )
  405. for f in os.listdir(
  406. build_dir
  407. ): # TODO: once we are Python 3 only, this can be os.scandir()
  408. f = os.path.join(build_dir, f)
  409. if args.verbose:
  410. print("Removing: %s" % f)
  411. if os.path.isdir(f):
  412. shutil.rmtree(f)
  413. else:
  414. os.remove(f)
  415. def python_clean(action, ctx, args):
  416. for root, dirnames, filenames in os.walk(os.environ["IDF_PATH"]):
  417. for d in dirnames:
  418. if d == "__pycache__":
  419. dir_to_delete = os.path.join(root, d)
  420. if args.verbose:
  421. print("Removing: %s" % dir_to_delete)
  422. shutil.rmtree(dir_to_delete)
  423. for filename in fnmatch.filter(filenames, '*.py[co]'):
  424. file_to_delete = os.path.join(root, filename)
  425. if args.verbose:
  426. print("Removing: %s" % file_to_delete)
  427. os.remove(file_to_delete)
  428. def _safe_relpath(path, start=None):
  429. """ Return a relative path, same as os.path.relpath, but only if this is possible.
  430. It is not possible on Windows, if the start directory and the path are on different drives.
  431. """
  432. try:
  433. return os.path.relpath(path, os.curdir if start is None else start)
  434. except ValueError:
  435. return os.path.abspath(path)
  436. def get_commandline_options(ctx):
  437. """ Return all the command line options up to first action """
  438. # This approach ignores argument parsing done Click
  439. result = []
  440. for arg in sys.argv:
  441. if arg in ctx.command.commands_with_aliases:
  442. break
  443. result.append(arg)
  444. return result
  445. def get_default_serial_port():
  446. """ Return a default serial port. esptool can do this (smarter), but it can create
  447. inconsistencies where esptool.py uses one port and idf_monitor uses another.
  448. Same logic as esptool.py search order, reverse sort by name and choose the first port.
  449. """
  450. # Import is done here in order to move it after the check_environment() ensured that pyserial has been installed
  451. import serial.tools.list_ports
  452. ports = list(reversed(sorted(p.device for p in serial.tools.list_ports.comports())))
  453. try:
  454. print(
  455. "Choosing default port %s (use '-p PORT' option to set a specific serial port)"
  456. % ports[0].encode("ascii", "ignore")
  457. )
  458. return ports[0]
  459. except IndexError:
  460. raise RuntimeError(
  461. "No serial ports found. Connect a device, or use '-p PORT' option to set a specific port."
  462. )
  463. class PropertyDict(dict):
  464. def __getattr__(self, name):
  465. if name in self:
  466. return self[name]
  467. else:
  468. raise AttributeError("'PropertyDict' object has no attribute '%s'" % name)
  469. def __setattr__(self, name, value):
  470. self[name] = value
  471. def __delattr__(self, name):
  472. if name in self:
  473. del self[name]
  474. else:
  475. raise AttributeError("'PropertyDict' object has no attribute '%s'" % name)
  476. def init_cli():
  477. # Click is imported here to run it after check_environment()
  478. import click
  479. class Task(object):
  480. def __init__(
  481. self, callback, name, aliases, dependencies, order_dependencies, action_args
  482. ):
  483. self.callback = callback
  484. self.name = name
  485. self.dependencies = dependencies
  486. self.order_dependencies = order_dependencies
  487. self.action_args = action_args
  488. self.aliases = aliases
  489. def run(self, context, global_args, action_args=None):
  490. if action_args is None:
  491. action_args = self.action_args
  492. self.callback(self.name, context, global_args, **action_args)
  493. class Action(click.Command):
  494. def __init__(
  495. self,
  496. name=None,
  497. aliases=None,
  498. dependencies=None,
  499. order_dependencies=None,
  500. **kwargs
  501. ):
  502. super(Action, self).__init__(name, **kwargs)
  503. self.name = self.name or self.callback.__name__
  504. if aliases is None:
  505. aliases = []
  506. self.aliases = aliases
  507. self.help = self.help or self.callback.__doc__
  508. if self.help is None:
  509. self.help = ""
  510. if dependencies is None:
  511. dependencies = []
  512. if order_dependencies is None:
  513. order_dependencies = []
  514. # Show first line of help if short help is missing
  515. self.short_help = self.short_help or self.help.split("\n")[0]
  516. # Add aliases to help string
  517. if aliases:
  518. aliases_help = "Aliases: %s." % ", ".join(aliases)
  519. self.help = "\n".join([self.help, aliases_help])
  520. self.short_help = " ".join([aliases_help, self.short_help])
  521. if self.callback is not None:
  522. callback = self.callback
  523. def wrapped_callback(**action_args):
  524. return Task(
  525. callback=callback,
  526. name=self.name,
  527. dependencies=dependencies,
  528. order_dependencies=order_dependencies,
  529. action_args=action_args,
  530. aliases=self.aliases,
  531. )
  532. self.callback = wrapped_callback
  533. class Argument(click.Argument):
  534. """Positional argument"""
  535. def __init__(self, **kwargs):
  536. names = kwargs.pop("names")
  537. super(Argument, self).__init__(names, **kwargs)
  538. class Scope(object):
  539. """
  540. Scope for sub-command option.
  541. possible values:
  542. - default - only available on defined level (global/action)
  543. - global - When defined for action, also available as global
  544. - shared - Opposite to 'global': when defined in global scope, also available for all actions
  545. """
  546. SCOPES = ("default", "global", "shared")
  547. def __init__(self, scope=None):
  548. if scope is None:
  549. self._scope = "default"
  550. elif isinstance(scope, str) and scope in self.SCOPES:
  551. self._scope = scope
  552. elif isinstance(scope, Scope):
  553. self._scope = str(scope)
  554. else:
  555. raise FatalError("Unknown scope for option: %s" % scope)
  556. @property
  557. def is_global(self):
  558. return self._scope == "global"
  559. @property
  560. def is_shared(self):
  561. return self._scope == "shared"
  562. def __str__(self):
  563. return self._scope
  564. class Option(click.Option):
  565. """Option that knows whether it should be global"""
  566. def __init__(self, scope=None, **kwargs):
  567. kwargs["param_decls"] = kwargs.pop("names")
  568. super(Option, self).__init__(**kwargs)
  569. self.scope = Scope(scope)
  570. if self.scope.is_global:
  571. self.help += " This option can be used at most once either globally, or for one subcommand."
  572. class CLI(click.MultiCommand):
  573. """Action list contains all actions with options available for CLI"""
  574. def __init__(self, action_lists=None, help=None):
  575. super(CLI, self).__init__(
  576. chain=True,
  577. invoke_without_command=True,
  578. result_callback=self.execute_tasks,
  579. context_settings={"max_content_width": 140},
  580. help=help,
  581. )
  582. self._actions = {}
  583. self.global_action_callbacks = []
  584. self.commands_with_aliases = {}
  585. if action_lists is None:
  586. action_lists = []
  587. shared_options = []
  588. for action_list in action_lists:
  589. # Global options
  590. for option_args in action_list.get("global_options", []):
  591. option = Option(**option_args)
  592. self.params.append(option)
  593. if option.scope.is_shared:
  594. shared_options.append(option)
  595. for action_list in action_lists:
  596. # Global options validators
  597. self.global_action_callbacks.extend(
  598. action_list.get("global_action_callbacks", [])
  599. )
  600. for action_list in action_lists:
  601. # Actions
  602. for name, action in action_list.get("actions", {}).items():
  603. arguments = action.pop("arguments", [])
  604. options = action.pop("options", [])
  605. if arguments is None:
  606. arguments = []
  607. if options is None:
  608. options = []
  609. self._actions[name] = Action(name=name, **action)
  610. for alias in [name] + action.get("aliases", []):
  611. self.commands_with_aliases[alias] = name
  612. for argument_args in arguments:
  613. self._actions[name].params.append(Argument(**argument_args))
  614. # Add all shared options
  615. for option in shared_options:
  616. self._actions[name].params.append(option)
  617. for option_args in options:
  618. option = Option(**option_args)
  619. if option.scope.is_shared:
  620. raise FatalError(
  621. '"%s" is defined for action "%s". '
  622. ' "shared" options can be declared only on global level' % (option.name, name)
  623. )
  624. # Promote options to global if see for the first time
  625. if option.scope.is_global and option.name not in [o.name for o in self.params]:
  626. self.params.append(option)
  627. self._actions[name].params.append(option)
  628. def list_commands(self, ctx):
  629. return sorted(self._actions)
  630. def get_command(self, ctx, name):
  631. return self._actions.get(self.commands_with_aliases.get(name))
  632. def _print_closing_message(self, args, actions):
  633. # print a closing message of some kind
  634. #
  635. if "flash" in str(actions):
  636. print("Done")
  637. return
  638. # Otherwise, if we built any binaries print a message about
  639. # how to flash them
  640. def print_flashing_message(title, key):
  641. print("\n%s build complete. To flash, run this command:" % title)
  642. with open(os.path.join(args.build_dir, "flasher_args.json")) as f:
  643. flasher_args = json.load(f)
  644. def flasher_path(f):
  645. return _safe_relpath(os.path.join(args.build_dir, f))
  646. if key != "project": # flashing a single item
  647. cmd = ""
  648. if (
  649. key == "bootloader"
  650. ): # bootloader needs --flash-mode, etc to be passed in
  651. cmd = " ".join(flasher_args["write_flash_args"]) + " "
  652. cmd += flasher_args[key]["offset"] + " "
  653. cmd += flasher_path(flasher_args[key]["file"])
  654. else: # flashing the whole project
  655. cmd = " ".join(flasher_args["write_flash_args"]) + " "
  656. flash_items = sorted(
  657. (
  658. (o, f)
  659. for (o, f) in flasher_args["flash_files"].items()
  660. if len(o) > 0
  661. ),
  662. key=lambda x: int(x[0], 0),
  663. )
  664. for o, f in flash_items:
  665. cmd += o + " " + flasher_path(f) + " "
  666. print("%s %s -p %s -b %s --before %s --after %s write_flash %s" % (
  667. PYTHON,
  668. _safe_relpath("%s/components/esptool_py/esptool/esptool.py" % os.environ["IDF_PATH"]),
  669. args.port or "(PORT)",
  670. args.baud,
  671. flasher_args["extra_esptool_args"]["before"],
  672. flasher_args["extra_esptool_args"]["after"],
  673. cmd.strip(),
  674. ))
  675. print("or run 'idf.py -p %s %s'" % (
  676. args.port or "(PORT)",
  677. key + "-flash" if key != "project" else "flash",
  678. ))
  679. if "all" in actions or "build" in actions:
  680. print_flashing_message("Project", "project")
  681. else:
  682. if "app" in actions:
  683. print_flashing_message("App", "app")
  684. if "partition_table" in actions:
  685. print_flashing_message("Partition Table", "partition_table")
  686. if "bootloader" in actions:
  687. print_flashing_message("Bootloader", "bootloader")
  688. def execute_tasks(self, tasks, **kwargs):
  689. ctx = click.get_current_context()
  690. global_args = PropertyDict(ctx.params)
  691. # Set propagated global options
  692. for task in tasks:
  693. for key in list(task.action_args):
  694. option = next((o for o in ctx.command.params if o.name == key), None)
  695. if option and (option.scope.is_global or option.scope.is_shared):
  696. local_value = task.action_args.pop(key)
  697. global_value = global_args[key]
  698. default = () if option.multiple else option.default
  699. if global_value != default and local_value != default and global_value != local_value:
  700. raise FatalError(
  701. 'Option "%s" provided for "%s" is already defined to a different value. '
  702. "This option can appear at most once in the command line." % (key, task.name)
  703. )
  704. if local_value != default:
  705. global_args[key] = local_value
  706. # Validate global arguments
  707. for action_callback in ctx.command.global_action_callbacks:
  708. action_callback(ctx, global_args, tasks)
  709. # very simple dependency management
  710. completed_tasks = set()
  711. if not tasks:
  712. print(ctx.get_help())
  713. ctx.exit()
  714. while tasks:
  715. task = tasks[0]
  716. tasks_dict = dict([(t.name, t) for t in tasks])
  717. name_with_aliases = task.name
  718. if task.aliases:
  719. name_with_aliases += " (aliases: %s)" % ", ".join(task.aliases)
  720. ready_to_run = True
  721. for dep in task.dependencies:
  722. if dep not in completed_tasks:
  723. print(
  724. 'Adding %s\'s dependency "%s" to list of actions'
  725. % (task.name, dep)
  726. )
  727. dep_task = ctx.invoke(ctx.command.get_command(ctx, dep))
  728. # Remove global options from dependent tasks
  729. for key in list(dep_task.action_args):
  730. option = next((o for o in ctx.command.params if o.name == key), None)
  731. if option and (option.scope.is_global or option.scope.is_shared):
  732. dep_task.action_args.pop(key)
  733. tasks.insert(0, dep_task)
  734. ready_to_run = False
  735. for dep in task.order_dependencies:
  736. if dep in tasks_dict.keys() and dep not in completed_tasks:
  737. tasks.insert(0, tasks.pop(tasks.index(tasks_dict[dep])))
  738. ready_to_run = False
  739. if ready_to_run:
  740. tasks.pop(0)
  741. if task.name in completed_tasks:
  742. print(
  743. "Skipping action that is already done: %s"
  744. % name_with_aliases
  745. )
  746. else:
  747. print("Executing action: %s" % name_with_aliases)
  748. task.run(ctx, global_args, task.action_args)
  749. completed_tasks.add(task.name)
  750. self._print_closing_message(global_args, completed_tasks)
  751. @staticmethod
  752. def merge_action_lists(*action_lists):
  753. merged_actions = {
  754. "global_options": [],
  755. "actions": {},
  756. "global_action_callbacks": [],
  757. }
  758. for action_list in action_lists:
  759. merged_actions["global_options"].extend(
  760. action_list.get("global_options", [])
  761. )
  762. merged_actions["actions"].update(action_list.get("actions", {}))
  763. merged_actions["global_action_callbacks"].extend(
  764. action_list.get("global_action_callbacks", [])
  765. )
  766. return merged_actions
  767. # That's a tiny parser that parse project-dir even before constructing
  768. # fully featured click parser to be sure that extensions are loaded from the right place
  769. @click.command(
  770. add_help_option=False,
  771. context_settings={"allow_extra_args": True, "ignore_unknown_options": True},
  772. )
  773. @click.option("-C", "--project-dir", default=os.getcwd())
  774. def parse_project_dir(project_dir):
  775. return _realpath(project_dir)
  776. project_dir = parse_project_dir(standalone_mode=False)
  777. # Load base idf commands
  778. def validate_root_options(ctx, args, tasks):
  779. args.project_dir = _realpath(args.project_dir)
  780. if args.build_dir is not None and args.project_dir == _realpath(args.build_dir):
  781. raise FatalError(
  782. "Setting the build directory to the project directory is not supported. Suggest dropping "
  783. "--build-dir option, the default is a 'build' subdirectory inside the project directory."
  784. )
  785. if args.build_dir is None:
  786. args.build_dir = os.path.join(args.project_dir, "build")
  787. args.build_dir = _realpath(args.build_dir)
  788. def serial_action_global_callback(ctx, global_args, tasks):
  789. encryption = any([task.name in ("encrypted-flash", "encrypted-app-flash") for task in tasks])
  790. if encryption:
  791. for task in tasks:
  792. if task.name == "monitor":
  793. task.action_args["encrypted"] = True
  794. break
  795. # Possible keys for action dict are: global_options, actions and global_action_callbacks
  796. global_options = [
  797. {
  798. "names": ["-D", "--define-cache-entry"],
  799. "help": "Create a cmake cache entry.",
  800. "scope": "global",
  801. "multiple": True,
  802. }
  803. ]
  804. root_options = {
  805. "global_options": [
  806. {
  807. "names": ["-C", "--project-dir"],
  808. "help": "Project directory.",
  809. "type": click.Path(),
  810. "default": os.getcwd(),
  811. },
  812. {
  813. "names": ["-B", "--build-dir"],
  814. "help": "Build directory.",
  815. "type": click.Path(),
  816. "default": None,
  817. },
  818. {
  819. "names": ["-n", "--no-warnings"],
  820. "help": "Disable Cmake warnings.",
  821. "is_flag": True,
  822. "default": False,
  823. },
  824. {
  825. "names": ["-v", "--verbose"],
  826. "help": "Verbose build output.",
  827. "is_flag": True,
  828. "default": False,
  829. },
  830. {
  831. "names": ["--ccache/--no-ccache"],
  832. "help": "Use ccache in build. Disabled by default, unless IDF_CCACHE_ENABLE environment variable is set to a non-zero value.",
  833. "is_flag": True,
  834. "default": os.getenv("IDF_CCACHE_ENABLE") not in [None, "", "0"],
  835. },
  836. {
  837. "names": ["-G", "--generator"],
  838. "help": "CMake generator.",
  839. "type": click.Choice(GENERATOR_CMDS.keys()),
  840. },
  841. ],
  842. "global_action_callbacks": [validate_root_options],
  843. }
  844. build_actions = {
  845. "actions": {
  846. "all": {
  847. "aliases": ["build"],
  848. "callback": build_target,
  849. "short_help": "Build the project.",
  850. "help": "Build the project. This can involve multiple steps:\n\n"
  851. + "1. Create the build directory if needed. The sub-directory 'build' is used to hold build output, "
  852. + "although this can be changed with the -B option.\n\n"
  853. + "2. Run CMake as necessary to configure the project and generate build files for the main build tool.\n\n"
  854. + "3. Run the main build tool (Ninja or GNU Make). By default, the build tool is automatically detected "
  855. + "but it can be explicitly set by passing the -G option to idf.py.\n\n",
  856. "options": global_options,
  857. "order_dependencies": [
  858. "reconfigure",
  859. "menuconfig",
  860. "clean",
  861. "fullclean",
  862. ],
  863. },
  864. "menuconfig": {
  865. "callback": build_target,
  866. "help": 'Run "menuconfig" project configuration tool.',
  867. "options": global_options,
  868. },
  869. "confserver": {
  870. "callback": build_target,
  871. "help": "Run JSON configuration server.",
  872. "options": global_options,
  873. },
  874. "size": {
  875. "callback": build_target,
  876. "help": "Print basic size information about the app.",
  877. "options": global_options,
  878. "dependencies": ["app"],
  879. },
  880. "size-components": {
  881. "callback": build_target,
  882. "help": "Print per-component size information.",
  883. "options": global_options,
  884. "dependencies": ["app"],
  885. },
  886. "size-files": {
  887. "callback": build_target,
  888. "help": "Print per-source-file size information.",
  889. "options": global_options,
  890. "dependencies": ["app"],
  891. },
  892. "bootloader": {
  893. "callback": build_target,
  894. "help": "Build only bootloader.",
  895. "options": global_options,
  896. },
  897. "app": {
  898. "callback": build_target,
  899. "help": "Build only the app.",
  900. "order_dependencies": ["clean", "fullclean", "reconfigure"],
  901. "options": global_options,
  902. },
  903. "efuse_common_table": {
  904. "callback": build_target,
  905. "help": "Genereate C-source for IDF's eFuse fields.",
  906. "order_dependencies": ["reconfigure"],
  907. "options": global_options,
  908. },
  909. "efuse_custom_table": {
  910. "callback": build_target,
  911. "help": "Genereate C-source for user's eFuse fields.",
  912. "order_dependencies": ["reconfigure"],
  913. "options": global_options,
  914. },
  915. "show_efuse_table": {
  916. "callback": build_target,
  917. "help": "Print eFuse table.",
  918. "order_dependencies": ["reconfigure"],
  919. "options": global_options,
  920. },
  921. "partition_table": {
  922. "callback": build_target,
  923. "help": "Build only partition table.",
  924. "order_dependencies": ["reconfigure"],
  925. "options": global_options,
  926. },
  927. "erase_otadata": {
  928. "callback": build_target,
  929. "help": "Erase otadata partition.",
  930. "options": global_options,
  931. },
  932. "read_otadata": {
  933. "callback": build_target,
  934. "help": "Read otadata partition.",
  935. "options": global_options,
  936. },
  937. }
  938. }
  939. clean_actions = {
  940. "actions": {
  941. "reconfigure": {
  942. "callback": reconfigure,
  943. "short_help": "Re-run CMake.",
  944. "help": "Re-run CMake even if it doesn't seem to need re-running. This isn't necessary during normal usage, "
  945. + "but can be useful after adding/removing files from the source tree, or when modifying CMake cache variables. "
  946. + "For example, \"idf.py -DNAME='VALUE' reconfigure\" "
  947. + 'can be used to set variable "NAME" in CMake cache to value "VALUE".',
  948. "options": global_options,
  949. "order_dependencies": ["menuconfig"],
  950. },
  951. "clean": {
  952. "callback": clean,
  953. "short_help": "Delete build output files from the build directory.",
  954. "help": "Delete build output files from the build directory , forcing a 'full rebuild' the next time "
  955. + "the project is built. Cleaning doesn't delete CMake configuration output and some other files",
  956. "order_dependencies": ["fullclean"],
  957. },
  958. "fullclean": {
  959. "callback": fullclean,
  960. "short_help": "Delete the entire build directory contents.",
  961. "help": "Delete the entire build directory contents. This includes all CMake configuration output."
  962. + "The next time the project is built, CMake will configure it from scratch. "
  963. + "Note that this option recursively deletes all files in the build directory, so use with care."
  964. + "Project configuration is not deleted.",
  965. },
  966. "python-clean": {
  967. "callback": python_clean,
  968. "short_help": "Delete generated Python byte code from the IDF directory",
  969. "help": ("Delete generated Python byte code from the IDF directory "
  970. "which may cause issues when switching between IDF and Python versions. "
  971. "It is advised to run this target after switching versions.")
  972. },
  973. }
  974. }
  975. baud_rate = {
  976. "names": ["-b", "--baud"],
  977. "help": "Baud rate for flashing. The default value can be set with the ESPBAUD environment variable.",
  978. "scope": "global",
  979. "envvar": "ESPBAUD",
  980. "default": 460800,
  981. }
  982. port = {
  983. "names": ["-p", "--port"],
  984. "help": "Serial port. The default value can be set with the ESPPORT environment variable.",
  985. "scope": "global",
  986. "envvar": "ESPPORT",
  987. "default": None,
  988. }
  989. serial_actions = {
  990. "actions": {
  991. "flash": {
  992. "callback": flash,
  993. "help": "Flash the project.",
  994. "options": global_options + [baud_rate, port],
  995. "dependencies": ["all"],
  996. "order_dependencies": ["erase_flash"],
  997. },
  998. "erase_flash": {
  999. "callback": erase_flash,
  1000. "help": "Erase entire flash chip.",
  1001. "options": [baud_rate, port],
  1002. },
  1003. "monitor": {
  1004. "callback": monitor,
  1005. "help": "Display serial output.",
  1006. "options": [
  1007. port, {
  1008. "names": ["--print-filter", "--print_filter"],
  1009. "help":
  1010. ("Filter monitor output.\n"
  1011. "Restrictions on what to print can be specified as a series of <tag>:<log_level> items "
  1012. "where <tag> is the tag string and <log_level> is a character from the set "
  1013. "{N, E, W, I, D, V, *} referring to a level. "
  1014. 'For example, "tag1:W" matches and prints only the outputs written with '
  1015. 'ESP_LOGW("tag1", ...) or at lower verbosity level, i.e. ESP_LOGE("tag1", ...). '
  1016. 'Not specifying a <log_level> or using "*" defaults to Verbose level.\n'
  1017. 'Please see the IDF Monitor section of the ESP-IDF documentation '
  1018. 'for a more detailed description and further examples.'),
  1019. "default":
  1020. None,
  1021. }, {
  1022. "names": ["--monitor-baud", "-B"],
  1023. "type":
  1024. click.INT,
  1025. "help": ("Baud rate for monitor.\n"
  1026. "If this option is not provided IDF_MONITOR_BAUD and MONITORBAUD "
  1027. "environment variables and project_description.json in build directory "
  1028. "(generated by CMake from project's sdkconfig) "
  1029. "will be checked for default value."),
  1030. }, {
  1031. "names": ["--encrypted", "-E"],
  1032. "is_flag": True,
  1033. "help": ("Enable encrypted flash targets.\n"
  1034. "IDF Monitor will invoke encrypted-flash and encrypted-app-flash targets "
  1035. "if this option is set. This option is set by default if IDF Monitor was invoked "
  1036. "together with encrypted-flash or encrypted-app-flash target."),
  1037. }
  1038. ],
  1039. "order_dependencies": [
  1040. "flash",
  1041. "encrypted-flash",
  1042. "partition_table-flash",
  1043. "bootloader-flash",
  1044. "app-flash",
  1045. "encrypted-app-flash",
  1046. ],
  1047. },
  1048. "partition_table-flash": {
  1049. "callback": flash,
  1050. "help": "Flash partition table only.",
  1051. "options": [baud_rate, port],
  1052. "dependencies": ["partition_table"],
  1053. "order_dependencies": ["erase_flash"],
  1054. },
  1055. "bootloader-flash": {
  1056. "callback": flash,
  1057. "help": "Flash bootloader only.",
  1058. "options": [baud_rate, port],
  1059. "dependencies": ["bootloader"],
  1060. "order_dependencies": ["erase_flash"],
  1061. },
  1062. "app-flash": {
  1063. "callback": flash,
  1064. "help": "Flash the app only.",
  1065. "options": [baud_rate, port],
  1066. "dependencies": ["app"],
  1067. "order_dependencies": ["erase_flash"],
  1068. },
  1069. "encrypted-app-flash": {
  1070. "callback": flash,
  1071. "help": "Flash the encrypted app only.",
  1072. "dependencies": ["app"],
  1073. "order_dependencies": ["erase_flash"],
  1074. },
  1075. "encrypted-flash": {
  1076. "callback": flash,
  1077. "help": "Flash the encrypted project.",
  1078. "dependencies": ["all"],
  1079. "order_dependencies": ["erase_flash"],
  1080. },
  1081. },
  1082. "global_action_callbacks": [serial_action_global_callback],
  1083. }
  1084. base_actions = CLI.merge_action_lists(
  1085. root_options, build_actions, clean_actions, serial_actions
  1086. )
  1087. all_actions = [base_actions]
  1088. # Load extensions
  1089. if os.path.exists(os.path.join(project_dir, "idf_ext.py")):
  1090. sys.path.append(project_dir)
  1091. try:
  1092. from idf_ext import action_extensions
  1093. except ImportError:
  1094. print("Error importing extension file idf_ext.py. Skipping.")
  1095. print(
  1096. "Please make sure that it contains implementation (even if it's empty) of add_action_extensions"
  1097. )
  1098. # Add actions extensions
  1099. try:
  1100. all_actions.append(action_extensions(base_actions, project_dir))
  1101. except NameError:
  1102. pass
  1103. return CLI(help="ESP-IDF build management", action_lists=all_actions)
  1104. def main():
  1105. check_environment()
  1106. cli = init_cli()
  1107. cli(prog_name=PROG)
  1108. def _valid_unicode_config():
  1109. # Python 2 is always good
  1110. if sys.version_info[0] == 2:
  1111. return True
  1112. # With python 3 unicode environment is required
  1113. try:
  1114. return codecs.lookup(locale.getpreferredencoding()).name != "ascii"
  1115. except Exception:
  1116. return False
  1117. def _find_usable_locale():
  1118. try:
  1119. locales = subprocess.Popen(
  1120. ["locale", "-a"], stdout=subprocess.PIPE, stderr=subprocess.PIPE
  1121. ).communicate()[0]
  1122. except OSError:
  1123. locales = ""
  1124. if isinstance(locales, bytes):
  1125. locales = locales.decode("ascii", "replace")
  1126. usable_locales = []
  1127. for line in locales.splitlines():
  1128. locale = line.strip()
  1129. locale_name = locale.lower().replace("-", "")
  1130. # C.UTF-8 is the best option, if supported
  1131. if locale_name == "c.utf8":
  1132. return locale
  1133. if locale_name.endswith(".utf8"):
  1134. # Make a preference of english locales
  1135. if locale.startswith("en_"):
  1136. usable_locales.insert(0, locale)
  1137. else:
  1138. usable_locales.append(locale)
  1139. if not usable_locales:
  1140. raise FatalError(
  1141. "Support for Unicode filenames is required, but no suitable UTF-8 locale was found on your system."
  1142. " Please refer to the manual for your operating system for details on locale reconfiguration."
  1143. )
  1144. return usable_locales[0]
  1145. if __name__ == "__main__":
  1146. try:
  1147. # On MSYS2 we need to run idf.py with "winpty" in order to be able to cancel the subprocesses properly on
  1148. # keyboard interrupt (CTRL+C).
  1149. # Using an own global variable for indicating that we are running with "winpty" seems to be the most suitable
  1150. # option as os.environment['_'] contains "winpty" only when it is run manually from console.
  1151. WINPTY_VAR = "WINPTY"
  1152. WINPTY_EXE = "winpty"
  1153. if ("MSYSTEM" in os.environ) and (
  1154. not os.environ.get("_", "").endswith(WINPTY_EXE) and WINPTY_VAR not in os.environ
  1155. ):
  1156. if 'menuconfig' in sys.argv:
  1157. # don't use winpty for menuconfig because it will print weird characters
  1158. main()
  1159. else:
  1160. os.environ[WINPTY_VAR] = "1" # the value is of no interest to us
  1161. # idf.py calls itself with "winpty" and WINPTY global variable set
  1162. ret = subprocess.call(
  1163. [WINPTY_EXE, sys.executable] + sys.argv, env=os.environ
  1164. )
  1165. if ret:
  1166. raise SystemExit(ret)
  1167. elif os.name == "posix" and not _valid_unicode_config():
  1168. # Trying to find best utf-8 locale available on the system and restart python with it
  1169. best_locale = _find_usable_locale()
  1170. print(
  1171. "Your environment is not configured to handle unicode filenames outside of ASCII range."
  1172. " Environment variable LC_ALL is temporary set to %s for unicode support."
  1173. % best_locale
  1174. )
  1175. os.environ["LC_ALL"] = best_locale
  1176. ret = subprocess.call([sys.executable] + sys.argv, env=os.environ)
  1177. if ret:
  1178. raise SystemExit(ret)
  1179. else:
  1180. main()
  1181. except FatalError as e:
  1182. print(e)
  1183. sys.exit(2)