idf.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  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. # Note: 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. import serial.tools.list_ports
  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. # Make flavors, across the various kinds of Windows environments & POSIX...
  49. if "MSYSTEM" in os.environ: # MSYS
  50. MAKE_CMD = "make"
  51. MAKE_GENERATOR = "MSYS Makefiles"
  52. elif os.name == 'nt': # other Windows
  53. MAKE_CMD = "mingw32-make"
  54. MAKE_GENERATOR = "MinGW Makefiles"
  55. else:
  56. MAKE_CMD = "make"
  57. MAKE_GENERATOR = "Unix Makefiles"
  58. GENERATORS = [
  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"...' % 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. Using the environment variable directory, but results may be unexpected..."
  92. % (set_idf_path, detected_idf_path))
  93. else:
  94. print("Setting IDF_PATH environment variable: %s" % detected_idf_path)
  95. os.environ["IDF_PATH"] = detected_idf_path
  96. # check Python dependencies
  97. print("Checking Python dependencies...")
  98. try:
  99. subprocess.check_call([ os.environ["PYTHON"],
  100. os.path.join(os.environ["IDF_PATH"], "tools", "check_python_dependencies.py")],
  101. env=os.environ)
  102. except subprocess.CalledProcessError:
  103. raise SystemExit(1)
  104. def executable_exists(args):
  105. try:
  106. subprocess.check_output(args)
  107. return True
  108. except:
  109. return False
  110. def detect_cmake_generator():
  111. """
  112. Find the default cmake generator, if none was specified. Raises an exception if no valid generator is found.
  113. """
  114. for (generator, _, version_check, _) in GENERATORS:
  115. if executable_exists(version_check):
  116. return generator
  117. raise FatalError("To use idf.py, either the 'ninja' or 'GNU make' build tool must be available in the PATH")
  118. def _ensure_build_directory(args, always_run_cmake=False):
  119. """Check the build directory exists and that cmake has been run there.
  120. If this isn't the case, create the build directory (if necessary) and
  121. do an initial cmake run to configure it.
  122. This function will also check args.generator parameter. If the parameter is incompatible with
  123. the build directory, an error is raised. If the parameter is None, this function will set it to
  124. an auto-detected default generator or to the value already configured in the build directory.
  125. """
  126. project_dir = args.project_dir
  127. # Verify the project directory
  128. if not os.path.isdir(project_dir):
  129. if not os.path.exists(project_dir):
  130. raise FatalError("Project directory %s does not exist")
  131. else:
  132. raise FatalError("%s must be a project directory")
  133. if not os.path.exists(os.path.join(project_dir, "CMakeLists.txt")):
  134. raise FatalError("CMakeLists.txt not found in project directory %s" % project_dir)
  135. # Verify/create the build directory
  136. build_dir = args.build_dir
  137. if not os.path.isdir(build_dir):
  138. os.mkdir(build_dir)
  139. cache_path = os.path.join(build_dir, "CMakeCache.txt")
  140. if not os.path.exists(cache_path) or always_run_cmake:
  141. if args.generator is None:
  142. args.generator = detect_cmake_generator()
  143. try:
  144. cmake_args = ["cmake", "-G", args.generator, "-DPYTHON_DEPS_CHECKED=1"]
  145. if not args.no_warnings:
  146. cmake_args += [ "--warn-uninitialized" ]
  147. if args.no_ccache:
  148. cmake_args += [ "-DCCACHE_DISABLE=1" ]
  149. cmake_args += [ project_dir]
  150. _run_tool("cmake", cmake_args, cwd=args.build_dir)
  151. except:
  152. # don't allow partially valid CMakeCache.txt files,
  153. # to keep the "should I run cmake?" logic simple
  154. if os.path.exists(cache_path):
  155. os.remove(cache_path)
  156. raise
  157. # Learn some things from the CMakeCache.txt file in the build directory
  158. cache = parse_cmakecache(cache_path)
  159. try:
  160. generator = cache["CMAKE_GENERATOR"]
  161. except KeyError:
  162. generator = detect_cmake_generator()
  163. if args.generator is None:
  164. args.generator = generator # reuse the previously configured generator, if none was given
  165. if generator != args.generator:
  166. raise FatalError("Build is configured for generator '%s' not '%s'. Run 'idf.py fullclean' to start again."
  167. % (generator, args.generator))
  168. try:
  169. home_dir = cache["CMAKE_HOME_DIRECTORY"]
  170. if os.path.normcase(os.path.realpath(home_dir)) != os.path.normcase(os.path.realpath(project_dir)):
  171. raise FatalError("Build directory '%s' configured for project '%s' not '%s'. Run 'idf.py fullclean' to start again."
  172. % (build_dir, os.path.realpath(home_dir), os.path.realpath(project_dir)))
  173. except KeyError:
  174. pass # if cmake failed part way, CMAKE_HOME_DIRECTORY may not be set yet
  175. def parse_cmakecache(path):
  176. """
  177. Parse the CMakeCache file at 'path'.
  178. Returns a dict of name:value.
  179. CMakeCache entries also each have a "type", but this is currently ignored.
  180. """
  181. result = {}
  182. with open(path) as f:
  183. for line in f:
  184. # cmake cache lines look like: CMAKE_CXX_FLAGS_DEBUG:STRING=-g
  185. # groups are name, type, value
  186. m = re.match(r"^([^#/:=]+):([^:=]+)=(.+)\n$", line)
  187. if m:
  188. result[m.group(1)] = m.group(3)
  189. return result
  190. def build_target(target_name, args):
  191. """
  192. Execute the target build system to build target 'target_name'
  193. Calls _ensure_build_directory() which will run cmake to generate a build
  194. directory (with the specified generator) as needed.
  195. """
  196. _ensure_build_directory(args)
  197. generator_cmd = GENERATOR_CMDS[args.generator]
  198. if not args.no_ccache:
  199. # Setting CCACHE_BASEDIR & CCACHE_NO_HASHDIR ensures that project paths aren't stored in the ccache entries
  200. # (this means ccache hits can be shared between different projects. It may mean that some debug information
  201. # will point to files in another project, if these files are perfect duplicates of each other.)
  202. #
  203. # It would be nicer to set these from cmake, but there's no cross-platform way to set build-time environment
  204. #os.environ["CCACHE_BASEDIR"] = args.build_dir
  205. #os.environ["CCACHE_NO_HASHDIR"] = "1"
  206. pass
  207. if args.verbose:
  208. generator_cmd += [ GENERATOR_VERBOSE[args.generator] ]
  209. _run_tool(generator_cmd[0], generator_cmd + [target_name], args.build_dir)
  210. def _get_esptool_args(args):
  211. esptool_path = os.path.join(os.environ["IDF_PATH"], "components/esptool_py/esptool/esptool.py")
  212. if args.port is None:
  213. args.port = get_default_serial_port()
  214. result = [ PYTHON, esptool_path ]
  215. result += [ "-p", args.port ]
  216. result += [ "-b", str(args.baud) ]
  217. return result
  218. def flash(action, args):
  219. """
  220. Run esptool to flash the entire project, from an argfile generated by the build system
  221. """
  222. flasher_args_path = { # action -> name of flasher args file generated by build system
  223. "bootloader-flash": "flash_bootloader_args",
  224. "partition_table-flash": "flash_partition_table_args",
  225. "app-flash": "flash_app_args",
  226. "flash": "flash_project_args",
  227. }[action]
  228. esptool_args = _get_esptool_args(args)
  229. esptool_args += [ "write_flash", "@"+flasher_args_path ]
  230. _run_tool("esptool.py", esptool_args, args.build_dir)
  231. def erase_flash(action, args):
  232. esptool_args = _get_esptool_args(args)
  233. esptool_args += [ "erase_flash" ]
  234. _run_tool("esptool.py", esptool_args, args.build_dir)
  235. def monitor(action, args):
  236. """
  237. Run idf_monitor.py to watch build output
  238. """
  239. if args.port is None:
  240. args.port = get_default_serial_port()
  241. desc_path = os.path.join(args.build_dir, "project_description.json")
  242. if not os.path.exists(desc_path):
  243. _ensure_build_directory(args)
  244. with open(desc_path, "r") as f:
  245. project_desc = json.load(f)
  246. elf_file = os.path.join(args.build_dir, project_desc["app_elf"])
  247. if not os.path.exists(elf_file):
  248. raise FatalError("ELF file '%s' not found. You need to build & flash the project before running 'monitor', and the binary on the device must match the one in the build directory exactly. Try 'idf.py flash monitor'." % elf_file)
  249. idf_monitor = os.path.join(os.environ["IDF_PATH"], "tools/idf_monitor.py")
  250. monitor_args = [PYTHON, idf_monitor ]
  251. if args.port is not None:
  252. monitor_args += [ "-p", args.port ]
  253. monitor_args += [ "-b", project_desc["monitor_baud"] ]
  254. monitor_args += [ elf_file ]
  255. idf_py = [ PYTHON ] + get_commandline_options() # commands to re-run idf.py
  256. monitor_args += [ "-m", " ".join("'%s'" % a for a in idf_py) ]
  257. if "MSYSTEM" is os.environ:
  258. monitor_args = [ "winpty" ] + monitor_args
  259. _run_tool("idf_monitor", monitor_args, args.project_dir)
  260. def clean(action, args):
  261. if not os.path.isdir(args.build_dir):
  262. print("Build directory '%s' not found. Nothing to clean." % args.build_dir)
  263. return
  264. build_target("clean", args)
  265. def reconfigure(action, args):
  266. _ensure_build_directory(args, True)
  267. def fullclean(action, args):
  268. build_dir = args.build_dir
  269. if not os.path.isdir(build_dir):
  270. print("Build directory '%s' not found. Nothing to clean." % build_dir)
  271. return
  272. if len(os.listdir(build_dir)) == 0:
  273. print("Build directory '%s' is empty. Nothing to clean." % build_dir)
  274. return
  275. if not os.path.exists(os.path.join(build_dir, "CMakeCache.txt")):
  276. raise FatalError("Directory '%s' doesn't seem to be a CMake build directory. Refusing to automatically delete files in this directory. Delete the directory manually to 'clean' it." % build_dir)
  277. red_flags = [ "CMakeLists.txt", ".git", ".svn" ]
  278. for red in red_flags:
  279. red = os.path.join(build_dir, red)
  280. if os.path.exists(red):
  281. raise FatalError("Refusing to automatically delete files in directory containing '%s'. Delete files manually if you're sure." % red)
  282. # OK, delete everything in the build directory...
  283. for f in os.listdir(build_dir): # TODO: once we are Python 3 only, this can be os.scandir()
  284. f = os.path.join(build_dir, f)
  285. if os.path.isdir(f):
  286. shutil.rmtree(f)
  287. else:
  288. os.remove(f)
  289. def print_closing_message(args):
  290. # print a closing message of some kind
  291. #
  292. if "flash" in str(args.actions):
  293. print("Done")
  294. return
  295. # Otherwise, if we built any binaries print a message about
  296. # how to flash them
  297. def print_flashing_message(title, key):
  298. print("\n%s build complete. To flash, run this command:" % title)
  299. with open(os.path.join(args.build_dir, "flasher_args.json")) as f:
  300. flasher_args = json.load(f)
  301. def flasher_path(f):
  302. return os.path.relpath(os.path.join(args.build_dir, f))
  303. if key != "project": # flashing a single item
  304. cmd = ""
  305. if key == "bootloader": # bootloader needs --flash-mode, etc to be passed in
  306. cmd = " ".join(flasher_args["write_flash_args"]) + " "
  307. cmd += flasher_args[key]["offset"] + " "
  308. cmd += flasher_path(flasher_args[key]["file"])
  309. else: # flashing the whole project
  310. cmd = " ".join(flasher_args["write_flash_args"]) + " "
  311. flash_items = sorted(((o,f) for (o,f) in flasher_args["flash_files"].items() if len(o) > 0),
  312. key = lambda x: int(x[0], 0))
  313. for o,f in flash_items:
  314. cmd += o + " " + flasher_path(f) + " "
  315. print("%s -p %s -b %s write_flash %s" % (
  316. os.path.relpath("%s/components/esptool_py/esptool/esptool.py" % os.environ["IDF_PATH"]),
  317. args.port or "(PORT)",
  318. args.baud,
  319. cmd.strip()))
  320. print("or run 'idf.py -p %s %s'" % (args.port or "(PORT)", key + "-flash" if key != "project" else "flash",))
  321. if "all" in args.actions or "build" in args.actions:
  322. print_flashing_message("Project", "project")
  323. else:
  324. if "app" in args.actions:
  325. print_flashing_message("App", "app")
  326. if "partition_table" in args.actions:
  327. print_flashing_message("Partition Table", "partition_table")
  328. if "bootloader" in args.actions:
  329. print_flashing_message("Bootloader", "bootloader")
  330. ACTIONS = {
  331. # action name : ( function (or alias), dependencies, order-only dependencies )
  332. "all" : ( build_target, [], [ "reconfigure", "menuconfig", "clean", "fullclean" ] ),
  333. "build": ( "all", [], [] ), # build is same as 'all' target
  334. "clean": ( clean, [], [ "fullclean" ] ),
  335. "fullclean": ( fullclean, [], [] ),
  336. "reconfigure": ( reconfigure, [], [ "menuconfig" ] ),
  337. "menuconfig": ( build_target, [], [] ),
  338. "confserver": ( build_target, [], [] ),
  339. "size": ( build_target, [ "app" ], [] ),
  340. "size-components": ( build_target, [ "app" ], [] ),
  341. "size-files": ( build_target, [ "app" ], [] ),
  342. "bootloader": ( build_target, [], [] ),
  343. "bootloader-clean": ( build_target, [], [] ),
  344. "bootloader-flash": ( flash, [ "bootloader" ], [ "erase_flash"] ),
  345. "app": ( build_target, [], [ "clean", "fullclean", "reconfigure" ] ),
  346. "app-flash": ( flash, [ "app" ], [ "erase_flash"]),
  347. "partition_table": ( build_target, [], [ "reconfigure" ] ),
  348. "partition_table-flash": ( flash, [ "partition_table" ], [ "erase_flash" ]),
  349. "flash": ( flash, [ "all" ], [ "erase_flash" ] ),
  350. "erase_flash": ( erase_flash, [], []),
  351. "monitor": ( monitor, [], [ "flash", "partition_table-flash", "bootloader-flash", "app-flash" ]),
  352. }
  353. def get_commandline_options():
  354. """ Return all the command line options up to but not including the action """
  355. result = []
  356. for a in sys.argv:
  357. if a in ACTIONS.keys():
  358. break
  359. else:
  360. result.append(a)
  361. return result
  362. def get_default_serial_port():
  363. """ Return a default serial port. esptool can do this (smarter), but it can create
  364. inconsistencies where esptool.py uses one port and idf_monitor uses another.
  365. Same logic as esptool.py search order, reverse sort by name and choose the first port.
  366. """
  367. ports = list(reversed(sorted(
  368. p.device for p in serial.tools.list_ports.comports() )))
  369. try:
  370. print ("Choosing default port %s (use '-p PORT' option to set a specific serial port)" % ports[0])
  371. return ports[0]
  372. except IndexError:
  373. raise RuntimeError("No serial ports found. Connect a device, or use '-p PORT' option to set a specific port.")
  374. def main():
  375. if sys.version_info[0] != 2 or sys.version_info[1] != 7:
  376. print("Note: You are using Python %d.%d.%d. Python 3 support is new, please report any problems "
  377. "you encounter. Search for 'Setting the Python Interpreter' in the ESP-IDF docs if you want to use "
  378. "Python 2.7." % sys.version_info[:3])
  379. parser = argparse.ArgumentParser(description='ESP-IDF build management tool')
  380. parser.add_argument('-p', '--port', help="Serial port",
  381. default=os.environ.get('ESPPORT', None))
  382. parser.add_argument('-b', '--baud', help="Baud rate",
  383. default=os.environ.get('ESPBAUD', 460800))
  384. parser.add_argument('-C', '--project-dir', help="Project directory", default=os.getcwd())
  385. parser.add_argument('-B', '--build-dir', help="Build directory", default=None)
  386. parser.add_argument('-G', '--generator', help="Cmake generator", choices=GENERATOR_CMDS.keys())
  387. parser.add_argument('-n', '--no-warnings', help="Disable Cmake warnings", action="store_true")
  388. parser.add_argument('-v', '--verbose', help="Verbose build output", action="store_true")
  389. parser.add_argument('--no-ccache', help="Disable ccache. Otherwise, if ccache is available on the PATH then it will be used for faster builds.", action="store_true")
  390. parser.add_argument('actions', help="Actions (build targets or other operations)", nargs='+',
  391. choices=ACTIONS.keys())
  392. args = parser.parse_args()
  393. check_environment()
  394. # Advanced parameter checks
  395. if args.build_dir is not None and os.path.realpath(args.project_dir) == os.path.realpath(args.build_dir):
  396. raise FatalError("Setting the build directory to the project directory is not supported. Suggest dropping --build-dir option, the default is a 'build' subdirectory inside the project directory.")
  397. if args.build_dir is None:
  398. args.build_dir = os.path.join(args.project_dir, "build")
  399. args.build_dir = os.path.realpath(args.build_dir)
  400. completed_actions = set()
  401. def execute_action(action, remaining_actions):
  402. ( function, dependencies, order_dependencies ) = ACTIONS[action]
  403. # very simple dependency management, build a set of completed actions and make sure
  404. # all dependencies are in it
  405. for dep in dependencies:
  406. if not dep in completed_actions:
  407. execute_action(dep, remaining_actions)
  408. for dep in order_dependencies:
  409. if dep in remaining_actions and not dep in completed_actions:
  410. execute_action(dep, remaining_actions)
  411. if action in completed_actions:
  412. pass # we've already done this, don't do it twice...
  413. elif function in ACTIONS: # alias of another action
  414. execute_action(function, remaining_actions)
  415. else:
  416. function(action, args)
  417. completed_actions.add(action)
  418. actions = list(args.actions)
  419. while len(actions) > 0:
  420. execute_action(actions[0], actions[1:])
  421. actions.pop(0)
  422. print_closing_message(args)
  423. if __name__ == "__main__":
  424. try:
  425. main()
  426. except FatalError as e:
  427. print(e)
  428. sys.exit(2)