idf.py 25 KB

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