idf.py 52 KB

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