idf.py 52 KB

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