idf.py 49 KB

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