idf.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650
  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 2018 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 sys
  29. import argparse
  30. import os
  31. import os.path
  32. import subprocess
  33. import multiprocessing
  34. import re
  35. import shutil
  36. import json
  37. class FatalError(RuntimeError):
  38. """
  39. Wrapper class for runtime errors that aren't caused by bugs in idf.py or the build proces.s
  40. """
  41. pass
  42. # Use this Python interpreter for any subprocesses we launch
  43. PYTHON = sys.executable
  44. # note: os.environ changes don't automatically propagate to child processes,
  45. # you have to pass env=os.environ explicitly anywhere that we create a process
  46. os.environ["PYTHON"] = sys.executable
  47. # Make flavors, across the various kinds of Windows environments & POSIX...
  48. if "MSYSTEM" in os.environ: # MSYS
  49. MAKE_CMD = "make"
  50. MAKE_GENERATOR = "MSYS Makefiles"
  51. elif os.name == 'nt': # other Windows
  52. MAKE_CMD = "mingw32-make"
  53. MAKE_GENERATOR = "MinGW Makefiles"
  54. else:
  55. MAKE_CMD = "make"
  56. MAKE_GENERATOR = "Unix Makefiles"
  57. GENERATORS = \
  58. [
  59. # ('generator name', 'build command line', 'version command line', 'verbose flag')
  60. ("Ninja", ["ninja"], ["ninja", "--version"], "-v"),
  61. (MAKE_GENERATOR, [MAKE_CMD, "-j", str(multiprocessing.cpu_count() + 2)], [MAKE_CMD, "--version"], "VERBOSE=1"),
  62. ]
  63. GENERATOR_CMDS = dict((a[0], a[1]) for a in GENERATORS)
  64. GENERATOR_VERBOSE = dict((a[0], a[3]) for a in GENERATORS)
  65. def _run_tool(tool_name, args, cwd):
  66. def quote_arg(arg):
  67. " Quote 'arg' if necessary "
  68. if " " in arg and not (arg.startswith('"') or arg.startswith("'")):
  69. return "'" + arg + "'"
  70. return arg
  71. display_args = " ".join(quote_arg(arg) for arg in args)
  72. print("Running %s in directory %s" % (tool_name, quote_arg(cwd)))
  73. print('Executing "%s"...' % str(display_args))
  74. try:
  75. # Note: we explicitly pass in os.environ here, as we may have set IDF_PATH there during startup
  76. subprocess.check_call(args, env=os.environ, cwd=cwd)
  77. except subprocess.CalledProcessError as e:
  78. raise FatalError("%s failed with exit code %d" % (tool_name, e.returncode))
  79. def check_environment():
  80. """
  81. Verify the environment contains the top-level tools we need to operate
  82. (cmake will check a lot of other things)
  83. """
  84. if not executable_exists(["cmake", "--version"]):
  85. raise FatalError("'cmake' must be available on the PATH to use idf.py")
  86. # find the directory idf.py is in, then the parent directory of this, and assume this is IDF_PATH
  87. detected_idf_path = os.path.realpath(os.path.join(os.path.dirname(__file__), ".."))
  88. if "IDF_PATH" in os.environ:
  89. set_idf_path = os.path.realpath(os.environ["IDF_PATH"])
  90. if set_idf_path != detected_idf_path:
  91. print("WARNING: IDF_PATH environment variable is set to %s but idf.py path indicates IDF directory %s. "
  92. "Using the environment variable directory, but results may be unexpected..."
  93. % (set_idf_path, detected_idf_path))
  94. else:
  95. print("Setting IDF_PATH environment variable: %s" % detected_idf_path)
  96. os.environ["IDF_PATH"] = detected_idf_path
  97. # check Python version
  98. if sys.version_info[0] < 3:
  99. print("WARNING: Support for Python 2 is deprecated and will be removed in future versions.")
  100. elif sys.version_info[0] == 3 and sys.version_info[1] < 6:
  101. print("WARNING: Python 3 versions older than 3.6 are not supported.")
  102. # check Python dependencies
  103. print("Checking Python dependencies...")
  104. try:
  105. subprocess.check_call([os.environ["PYTHON"],
  106. os.path.join(os.environ["IDF_PATH"], "tools", "check_python_dependencies.py")],
  107. env=os.environ)
  108. except subprocess.CalledProcessError:
  109. raise SystemExit(1)
  110. def executable_exists(args):
  111. try:
  112. subprocess.check_output(args)
  113. return True
  114. except Exception:
  115. return False
  116. def detect_cmake_generator():
  117. """
  118. Find the default cmake generator, if none was specified. Raises an exception if no valid generator is found.
  119. """
  120. for (generator, _, version_check, _) in GENERATORS:
  121. if executable_exists(version_check):
  122. return generator
  123. raise FatalError("To use idf.py, either the 'ninja' or 'GNU make' build tool must be available in the PATH")
  124. def _strip_quotes(value, regexp=re.compile(r"^\"(.*)\"$|^'(.*)'$|^(.*)$")):
  125. """
  126. Strip quotes like CMake does during parsing cache entries
  127. """
  128. return [x for x in regexp.match(value).groups() if x is not None][0].rstrip()
  129. def _new_cmakecache_entries(cache_path, new_cache_entries):
  130. if not os.path.exists(cache_path):
  131. return True
  132. current_cache = parse_cmakecache(cache_path)
  133. if new_cache_entries:
  134. current_cache = parse_cmakecache(cache_path)
  135. for entry in new_cache_entries:
  136. key, value = entry.split("=", 1)
  137. current_value = current_cache.get(key, None)
  138. if current_value is None or _strip_quotes(value) != current_value:
  139. return True
  140. return False
  141. def _ensure_build_directory(args, always_run_cmake=False):
  142. """Check the build directory exists and that cmake has been run there.
  143. If this isn't the case, create the build directory (if necessary) and
  144. do an initial cmake run to configure it.
  145. This function will also check args.generator parameter. If the parameter is incompatible with
  146. the build directory, an error is raised. If the parameter is None, this function will set it to
  147. an auto-detected default generator or to the value already configured in the build directory.
  148. """
  149. project_dir = args.project_dir
  150. # Verify the project directory
  151. if not os.path.isdir(project_dir):
  152. if not os.path.exists(project_dir):
  153. raise FatalError("Project directory %s does not exist")
  154. else:
  155. raise FatalError("%s must be a project directory")
  156. if not os.path.exists(os.path.join(project_dir, "CMakeLists.txt")):
  157. raise FatalError("CMakeLists.txt not found in project directory %s" % project_dir)
  158. # Verify/create the build directory
  159. build_dir = args.build_dir
  160. if not os.path.isdir(build_dir):
  161. os.makedirs(build_dir)
  162. cache_path = os.path.join(build_dir, "CMakeCache.txt")
  163. if always_run_cmake or _new_cmakecache_entries(cache_path, args.define_cache_entry):
  164. if args.generator is None:
  165. args.generator = detect_cmake_generator()
  166. try:
  167. cmake_args = ["cmake", "-G", args.generator, "-DPYTHON_DEPS_CHECKED=1", "-DESP_PLATFORM=1"]
  168. if not args.no_warnings:
  169. cmake_args += ["--warn-uninitialized"]
  170. if args.no_ccache:
  171. cmake_args += ["-DCCACHE_DISABLE=1"]
  172. if args.define_cache_entry:
  173. cmake_args += ["-D" + d for d in args.define_cache_entry]
  174. cmake_args += [project_dir]
  175. _run_tool("cmake", cmake_args, cwd=args.build_dir)
  176. except Exception:
  177. # don't allow partially valid CMakeCache.txt files,
  178. # to keep the "should I run cmake?" logic simple
  179. if os.path.exists(cache_path):
  180. os.remove(cache_path)
  181. raise
  182. # Learn some things from the CMakeCache.txt file in the build directory
  183. cache = parse_cmakecache(cache_path)
  184. try:
  185. generator = cache["CMAKE_GENERATOR"]
  186. except KeyError:
  187. generator = detect_cmake_generator()
  188. if args.generator is None:
  189. args.generator = generator # reuse the previously configured generator, if none was given
  190. if generator != args.generator:
  191. raise FatalError("Build is configured for generator '%s' not '%s'. Run 'idf.py fullclean' to start again."
  192. % (generator, args.generator))
  193. try:
  194. home_dir = cache["CMAKE_HOME_DIRECTORY"]
  195. if os.path.normcase(os.path.realpath(home_dir)) != os.path.normcase(os.path.realpath(project_dir)):
  196. raise FatalError("Build directory '%s' configured for project '%s' not '%s'. Run 'idf.py fullclean' to start again."
  197. % (build_dir, os.path.realpath(home_dir), os.path.realpath(project_dir)))
  198. except KeyError:
  199. pass # if cmake failed part way, CMAKE_HOME_DIRECTORY may not be set yet
  200. def parse_cmakecache(path):
  201. """
  202. Parse the CMakeCache file at 'path'.
  203. Returns a dict of name:value.
  204. CMakeCache entries also each have a "type", but this is currently ignored.
  205. """
  206. result = {}
  207. with open(path) as f:
  208. for line in f:
  209. # cmake cache lines look like: CMAKE_CXX_FLAGS_DEBUG:STRING=-g
  210. # groups are name, type, value
  211. m = re.match(r"^([^#/:=]+):([^:=]+)=(.*)\n$", line)
  212. if m:
  213. result[m.group(1)] = m.group(3)
  214. return result
  215. def build_target(target_name, args):
  216. """
  217. Execute the target build system to build target 'target_name'
  218. Calls _ensure_build_directory() which will run cmake to generate a build
  219. directory (with the specified generator) as needed.
  220. """
  221. _ensure_build_directory(args)
  222. generator_cmd = GENERATOR_CMDS[args.generator]
  223. if not args.no_ccache:
  224. # Setting CCACHE_BASEDIR & CCACHE_NO_HASHDIR ensures that project paths aren't stored in the ccache entries
  225. # (this means ccache hits can be shared between different projects. It may mean that some debug information
  226. # will point to files in another project, if these files are perfect duplicates of each other.)
  227. #
  228. # It would be nicer to set these from cmake, but there's no cross-platform way to set build-time environment
  229. # os.environ["CCACHE_BASEDIR"] = args.build_dir
  230. # os.environ["CCACHE_NO_HASHDIR"] = "1"
  231. pass
  232. if args.verbose:
  233. generator_cmd += [GENERATOR_VERBOSE[args.generator]]
  234. _run_tool(generator_cmd[0], generator_cmd + [target_name], args.build_dir)
  235. def _get_esptool_args(args):
  236. esptool_path = os.path.join(os.environ["IDF_PATH"], "components/esptool_py/esptool/esptool.py")
  237. if args.port is None:
  238. args.port = get_default_serial_port()
  239. result = [PYTHON, esptool_path]
  240. result += ["-p", args.port]
  241. result += ["-b", str(args.baud)]
  242. with open(os.path.join(args.build_dir, "flasher_args.json")) as f:
  243. flasher_args = json.load(f)
  244. extra_esptool_args = flasher_args["extra_esptool_args"]
  245. result += ["--after", extra_esptool_args["after"]]
  246. return result
  247. def flash(action, args):
  248. """
  249. Run esptool to flash the entire project, from an argfile generated by the build system
  250. """
  251. flasher_args_path = { # action -> name of flasher args file generated by build system
  252. "bootloader-flash": "flash_bootloader_args",
  253. "partition_table-flash": "flash_partition_table_args",
  254. "app-flash": "flash_app_args",
  255. "flash": "flash_project_args",
  256. }[action]
  257. esptool_args = _get_esptool_args(args)
  258. esptool_args += ["write_flash", "@" + flasher_args_path]
  259. _run_tool("esptool.py", esptool_args, args.build_dir)
  260. def erase_flash(action, args):
  261. esptool_args = _get_esptool_args(args)
  262. esptool_args += ["erase_flash"]
  263. _run_tool("esptool.py", esptool_args, args.build_dir)
  264. def monitor(action, args):
  265. """
  266. Run idf_monitor.py to watch build output
  267. """
  268. if args.port is None:
  269. args.port = get_default_serial_port()
  270. desc_path = os.path.join(args.build_dir, "project_description.json")
  271. if not os.path.exists(desc_path):
  272. _ensure_build_directory(args)
  273. with open(desc_path, "r") as f:
  274. project_desc = json.load(f)
  275. elf_file = os.path.join(args.build_dir, project_desc["app_elf"])
  276. if not os.path.exists(elf_file):
  277. raise FatalError("ELF file '%s' not found. You need to build & flash the project before running 'monitor', "
  278. "and the binary on the device must match the one in the build directory exactly. "
  279. "Try 'idf.py flash monitor'." % elf_file)
  280. idf_monitor = os.path.join(os.environ["IDF_PATH"], "tools/idf_monitor.py")
  281. monitor_args = [PYTHON, idf_monitor]
  282. if args.port is not None:
  283. monitor_args += ["-p", args.port]
  284. monitor_args += ["-b", project_desc["monitor_baud"]]
  285. monitor_args += [elf_file]
  286. idf_py = [PYTHON] + get_commandline_options() # commands to re-run idf.py
  287. monitor_args += ["-m", " ".join("'%s'" % a for a in idf_py)]
  288. if "MSYSTEM" in os.environ:
  289. monitor_args = ["winpty"] + monitor_args
  290. _run_tool("idf_monitor", monitor_args, args.project_dir)
  291. def clean(action, args):
  292. if not os.path.isdir(args.build_dir):
  293. print("Build directory '%s' not found. Nothing to clean." % args.build_dir)
  294. return
  295. build_target("clean", args)
  296. def reconfigure(action, args):
  297. _ensure_build_directory(args, True)
  298. def _delete_windows_symlinks(directory):
  299. """
  300. It deletes symlinks recursively on Windows. It is useful for Python 2 which doesn't detect symlinks on Windows.
  301. """
  302. deleted_paths = []
  303. if os.name == 'nt':
  304. import ctypes
  305. for root, dirnames, filenames in os.walk(directory):
  306. for d in dirnames:
  307. full_path = os.path.join(root, d)
  308. try:
  309. full_path = full_path.decode('utf-8')
  310. except Exception:
  311. pass
  312. if ctypes.windll.kernel32.GetFileAttributesW(full_path) & 0x0400:
  313. os.rmdir(full_path)
  314. deleted_paths.append(full_path)
  315. return deleted_paths
  316. def fullclean(action, args):
  317. build_dir = args.build_dir
  318. if not os.path.isdir(build_dir):
  319. print("Build directory '%s' not found. Nothing to clean." % build_dir)
  320. return
  321. if len(os.listdir(build_dir)) == 0:
  322. print("Build directory '%s' is empty. Nothing to clean." % build_dir)
  323. return
  324. if not os.path.exists(os.path.join(build_dir, "CMakeCache.txt")):
  325. raise FatalError("Directory '%s' doesn't seem to be a CMake build directory. Refusing to automatically "
  326. "delete files in this directory. Delete the directory manually to 'clean' it." % build_dir)
  327. red_flags = ["CMakeLists.txt", ".git", ".svn"]
  328. for red in red_flags:
  329. red = os.path.join(build_dir, red)
  330. if os.path.exists(red):
  331. raise FatalError("Refusing to automatically delete files in directory containing '%s'. Delete files manually if you're sure." % red)
  332. # OK, delete everything in the build directory...
  333. # Note: Python 2.7 doesn't detect symlinks on Windows (it is supported form 3.2). Tools promising to not
  334. # follow symlinks will actually follow them. Deleting the build directory with symlinks deletes also items
  335. # outside of this directory.
  336. deleted_symlinks = _delete_windows_symlinks(build_dir)
  337. if args.verbose and len(deleted_symlinks) > 1:
  338. print('The following symlinks were identified and removed:\n%s' % "\n".join(deleted_symlinks))
  339. for f in os.listdir(build_dir): # TODO: once we are Python 3 only, this can be os.scandir()
  340. f = os.path.join(build_dir, f)
  341. if args.verbose:
  342. print('Removing: %s' % f)
  343. if os.path.isdir(f):
  344. shutil.rmtree(f)
  345. else:
  346. os.remove(f)
  347. def _safe_relpath(path, start=None):
  348. """ Return a relative path, same as os.path.relpath, but only if this is possible.
  349. It is not possible on Windows, if the start directory and the path are on different drives.
  350. """
  351. try:
  352. return os.path.relpath(path, os.curdir if start is None else start)
  353. except ValueError:
  354. return os.path.abspath(path)
  355. def print_closing_message(args):
  356. # print a closing message of some kind
  357. #
  358. if "flash" in str(args.actions):
  359. print("Done")
  360. return
  361. # Otherwise, if we built any binaries print a message about
  362. # how to flash them
  363. def print_flashing_message(title, key):
  364. print("\n%s build complete. To flash, run this command:" % title)
  365. with open(os.path.join(args.build_dir, "flasher_args.json")) as f:
  366. flasher_args = json.load(f)
  367. def flasher_path(f):
  368. return _safe_relpath(os.path.join(args.build_dir, f))
  369. if key != "project": # flashing a single item
  370. cmd = ""
  371. if key == "bootloader": # bootloader needs --flash-mode, etc to be passed in
  372. cmd = " ".join(flasher_args["write_flash_args"]) + " "
  373. cmd += flasher_args[key]["offset"] + " "
  374. cmd += flasher_path(flasher_args[key]["file"])
  375. else: # flashing the whole project
  376. cmd = " ".join(flasher_args["write_flash_args"]) + " "
  377. flash_items = sorted(((o,f) for (o,f) in flasher_args["flash_files"].items() if len(o) > 0),
  378. key=lambda x: int(x[0], 0))
  379. for o,f in flash_items:
  380. cmd += o + " " + flasher_path(f) + " "
  381. print("%s -p %s -b %s --after %s write_flash %s" % (
  382. _safe_relpath("%s/components/esptool_py/esptool/esptool.py" % os.environ["IDF_PATH"]),
  383. args.port or "(PORT)",
  384. args.baud,
  385. flasher_args["extra_esptool_args"]["after"],
  386. cmd.strip()))
  387. print("or run 'idf.py -p %s %s'" % (args.port or "(PORT)", key + "-flash" if key != "project" else "flash",))
  388. if "all" in args.actions or "build" in args.actions:
  389. print_flashing_message("Project", "project")
  390. else:
  391. if "app" in args.actions:
  392. print_flashing_message("App", "app")
  393. if "partition_table" in args.actions:
  394. print_flashing_message("Partition Table", "partition_table")
  395. if "bootloader" in args.actions:
  396. print_flashing_message("Bootloader", "bootloader")
  397. ACTIONS = {
  398. # action name : ( function (or alias), dependencies, order-only dependencies )
  399. "all": (build_target, [], ["reconfigure", "menuconfig", "clean", "fullclean"]),
  400. "build": ("all", [], []), # build is same as 'all' target
  401. "clean": (clean, [], ["fullclean"]),
  402. "fullclean": (fullclean, [], []),
  403. "reconfigure": (reconfigure, [], ["menuconfig"]),
  404. "menuconfig": (build_target, [], []),
  405. "confserver": (build_target, [], []),
  406. "size": (build_target, ["app"], []),
  407. "size-components": (build_target, ["app"], []),
  408. "size-files": (build_target, ["app"], []),
  409. "bootloader": (build_target, [], []),
  410. "bootloader-clean": (build_target, [], []),
  411. "bootloader-flash": (flash, ["bootloader"], ["erase_flash"]),
  412. "app": (build_target, [], ["clean", "fullclean", "reconfigure"]),
  413. "app-flash": (flash, ["app"], ["erase_flash"]),
  414. "efuse_common_table": (build_target, [], ["reconfigure"]),
  415. "efuse_custom_table": (build_target, [], ["reconfigure"]),
  416. "show_efuse_table": (build_target, [], ["reconfigure"]),
  417. "partition_table": (build_target, [], ["reconfigure"]),
  418. "partition_table-flash": (flash, ["partition_table"], ["erase_flash"]),
  419. "flash": (flash, ["all"], ["erase_flash"]),
  420. "erase_flash": (erase_flash, [], []),
  421. "monitor": (monitor, [], ["flash", "partition_table-flash", "bootloader-flash", "app-flash"]),
  422. "erase_otadata": (build_target, [], []),
  423. "read_otadata": (build_target, [], []),
  424. }
  425. def get_commandline_options():
  426. """ Return all the command line options up to but not including the action """
  427. result = []
  428. for a in sys.argv:
  429. if a in ACTIONS.keys():
  430. break
  431. else:
  432. result.append(a)
  433. return result
  434. def get_default_serial_port():
  435. """ Return a default serial port. esptool can do this (smarter), but it can create
  436. inconsistencies where esptool.py uses one port and idf_monitor uses another.
  437. Same logic as esptool.py search order, reverse sort by name and choose the first port.
  438. """
  439. # Import is done here in order to move it after the check_environment() ensured that pyserial has been installed
  440. import serial.tools.list_ports
  441. ports = list(reversed(sorted(
  442. p.device for p in serial.tools.list_ports.comports())))
  443. try:
  444. print("Choosing default port %s (use '-p PORT' option to set a specific serial port)" % ports[0].encode('ascii', 'ignore'))
  445. return ports[0]
  446. except IndexError:
  447. raise RuntimeError("No serial ports found. Connect a device, or use '-p PORT' option to set a specific port.")
  448. # Import the actions, arguments extension file
  449. if os.path.exists(os.path.join(os.getcwd(), "idf_ext.py")):
  450. sys.path.append(os.getcwd())
  451. try:
  452. from idf_ext import add_action_extensions, add_argument_extensions
  453. except ImportError:
  454. print("Error importing extension file idf_ext.py. Skipping.")
  455. print("Please make sure that it contains implementations (even if they're empty implementations) of")
  456. print("add_action_extensions and add_argument_extensions.")
  457. def main():
  458. if sys.version_info[0] != 2 or sys.version_info[1] != 7:
  459. print("Note: You are using Python %d.%d.%d. Python 3 support is new, please report any problems "
  460. "you encounter. Search for 'Setting the Python Interpreter' in the ESP-IDF docs if you want to use "
  461. "Python 2.7." % sys.version_info[:3])
  462. # Add actions extensions
  463. try:
  464. add_action_extensions({
  465. "build_target": build_target,
  466. "reconfigure": reconfigure,
  467. "flash": flash,
  468. "monitor": monitor,
  469. "clean": clean,
  470. "fullclean": fullclean
  471. }, ACTIONS)
  472. except NameError:
  473. pass
  474. parser = argparse.ArgumentParser(description='ESP-IDF build management tool')
  475. parser.add_argument('-p', '--port', help="Serial port",
  476. default=os.environ.get('ESPPORT', None))
  477. parser.add_argument('-b', '--baud', help="Baud rate",
  478. default=os.environ.get('ESPBAUD', 460800))
  479. parser.add_argument('-C', '--project-dir', help="Project directory", default=os.getcwd())
  480. parser.add_argument('-B', '--build-dir', help="Build directory", default=None)
  481. parser.add_argument('-G', '--generator', help="Cmake generator", choices=GENERATOR_CMDS.keys())
  482. parser.add_argument('-n', '--no-warnings', help="Disable Cmake warnings", action="store_true")
  483. parser.add_argument('-v', '--verbose', help="Verbose build output", action="store_true")
  484. parser.add_argument('-D', '--define-cache-entry', help="Create a cmake cache entry", nargs='+')
  485. parser.add_argument('--no-ccache', help="Disable ccache. Otherwise, if ccache is available on the PATH then it will be used for faster builds.",
  486. action="store_true")
  487. parser.add_argument('actions', help="Actions (build targets or other operations)", nargs='+',
  488. choices=ACTIONS.keys())
  489. # Add arguments extensions
  490. try:
  491. add_argument_extensions(parser)
  492. except NameError:
  493. pass
  494. args = parser.parse_args()
  495. check_environment()
  496. # Advanced parameter checks
  497. if args.build_dir is not None and os.path.realpath(args.project_dir) == os.path.realpath(args.build_dir):
  498. raise FatalError("Setting the build directory to the project directory is not supported. Suggest dropping "
  499. "--build-dir option, the default is a 'build' subdirectory inside the project directory.")
  500. if args.build_dir is None:
  501. args.build_dir = os.path.join(args.project_dir, "build")
  502. args.build_dir = os.path.realpath(args.build_dir)
  503. completed_actions = set()
  504. def execute_action(action, remaining_actions):
  505. (function, dependencies, order_dependencies) = ACTIONS[action]
  506. # very simple dependency management, build a set of completed actions and make sure
  507. # all dependencies are in it
  508. for dep in dependencies:
  509. if dep not in completed_actions:
  510. execute_action(dep, remaining_actions)
  511. for dep in order_dependencies:
  512. if dep in remaining_actions and dep not in completed_actions:
  513. execute_action(dep, remaining_actions)
  514. if action in completed_actions:
  515. pass # we've already done this, don't do it twice...
  516. elif function in ACTIONS: # alias of another action
  517. execute_action(function, remaining_actions)
  518. else:
  519. function(action, args)
  520. completed_actions.add(action)
  521. actions = list(args.actions)
  522. while len(actions) > 0:
  523. execute_action(actions[0], actions[1:])
  524. actions.pop(0)
  525. print_closing_message(args)
  526. if __name__ == "__main__":
  527. try:
  528. # On MSYS2 we need to run idf.py with "winpty" in order to be able to cancel the subprocesses properly on
  529. # keyboard interrupt (CTRL+C).
  530. # Using an own global variable for indicating that we are running with "winpty" seems to be the most suitable
  531. # option as os.environment['_'] contains "winpty" only when it is run manually from console.
  532. WINPTY_VAR = 'WINPTY'
  533. WINPTY_EXE = 'winpty'
  534. if ('MSYSTEM' in os.environ) and (not os.environ['_'].endswith(WINPTY_EXE) and WINPTY_VAR not in os.environ):
  535. os.environ[WINPTY_VAR] = '1' # the value is of no interest to us
  536. # idf.py calls itself with "winpty" and WINPTY global variable set
  537. ret = subprocess.call([WINPTY_EXE, sys.executable] + sys.argv, env=os.environ)
  538. if ret:
  539. raise SystemExit(ret)
  540. else:
  541. main()
  542. except FatalError as e:
  543. print(e)
  544. sys.exit(2)