idf.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  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. import sys
  25. import argparse
  26. import os
  27. import os.path
  28. import subprocess
  29. import multiprocessing
  30. import re
  31. import shutil
  32. import json
  33. class FatalError(RuntimeError):
  34. """
  35. Wrapper class for runtime errors that aren't caused by bugs in idf.py or the build proces.s
  36. """
  37. pass
  38. # Use this Python interpreter for any subprocesses we launch
  39. PYTHON=sys.executable
  40. # note: os.environ changes don't automatically propagate to child processes,
  41. # you have to pass this in explicitly
  42. os.environ["PYTHON"]=sys.executable
  43. # Make flavors, across the various kinds of Windows environments & POSIX...
  44. if "MSYSTEM" in os.environ: # MSYS
  45. MAKE_CMD = "make"
  46. MAKE_GENERATOR = "MSYS Makefiles"
  47. elif os.name == 'nt': # other Windows
  48. MAKE_CMD = "mingw32-make"
  49. MAKE_GENERATOR = "MinGW Makefiles"
  50. else:
  51. MAKE_CMD = "make"
  52. MAKE_GENERATOR = "Unix Makefiles"
  53. GENERATORS = [
  54. # ('generator name', 'build command line', 'version command line', 'verbose flag')
  55. ("Ninja", [ "ninja" ], [ "ninja", "--version" ], "-v"),
  56. (MAKE_GENERATOR, [ MAKE_CMD, "-j", str(multiprocessing.cpu_count()+2) ], [ "make", "--version" ], "VERBOSE=1"),
  57. ]
  58. GENERATOR_CMDS = dict( (a[0], a[1]) for a in GENERATORS )
  59. GENERATOR_VERBOSE = dict( (a[0], a[3]) for a in GENERATORS )
  60. def _run_tool(tool_name, args, cwd):
  61. def quote_arg(arg):
  62. " Quote 'arg' if necessary "
  63. if " " in arg and not (arg.startswith('"') or arg.startswith("'")):
  64. return "'" + arg + "'"
  65. return arg
  66. display_args = " ".join(quote_arg(arg) for arg in args)
  67. print("Running %s in directory %s" % (tool_name, quote_arg(cwd)))
  68. print('Executing "%s"...' % display_args)
  69. try:
  70. # Note: we explicitly pass in os.environ here, as we may have set IDF_PATH there during startup
  71. subprocess.check_call(args, env=os.environ, cwd=cwd)
  72. except subprocess.CalledProcessError as e:
  73. raise FatalError("%s failed with exit code %d" % (tool_name, e.returncode))
  74. def check_environment():
  75. """
  76. Verify the environment contains the top-level tools we need to operate
  77. (cmake will check a lot of other things)
  78. """
  79. if not executable_exists(["cmake", "--version"]):
  80. raise FatalError("'cmake' must be available on the PATH to use idf.py")
  81. # find the directory idf.py is in, then the parent directory of this, and assume this is IDF_PATH
  82. detected_idf_path = os.path.realpath(os.path.join(os.path.dirname(__file__), ".."))
  83. if "IDF_PATH" in os.environ:
  84. set_idf_path = os.path.realpath(os.environ["IDF_PATH"])
  85. if set_idf_path != detected_idf_path:
  86. 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..."
  87. % (set_idf_path, detected_idf_path))
  88. else:
  89. os.environ["IDF_PATH"] = detected_idf_path
  90. def executable_exists(args):
  91. try:
  92. subprocess.check_output(args)
  93. return True
  94. except:
  95. return False
  96. def detect_cmake_generator():
  97. """
  98. Find the default cmake generator, if none was specified. Raises an exception if no valid generator is found.
  99. """
  100. for (generator, _, version_check, _) in GENERATORS:
  101. if executable_exists(version_check):
  102. return generator
  103. raise FatalError("To use idf.py, either the 'ninja' or 'GNU make' build tool must be available in the PATH")
  104. def _ensure_build_directory(args, always_run_cmake=False):
  105. """Check the build directory exists and that cmake has been run there.
  106. If this isn't the case, create the build directory (if necessary) and
  107. do an initial cmake run to configure it.
  108. This function will also check args.generator parameter. If the parameter is incompatible with
  109. the build directory, an error is raised. If the parameter is None, this function will set it to
  110. an auto-detected default generator or to the value already configured in the build directory.
  111. """
  112. project_dir = args.project_dir
  113. # Verify the project directory
  114. if not os.path.isdir(project_dir):
  115. if not os.path.exists(project_dir):
  116. raise FatalError("Project directory %s does not exist")
  117. else:
  118. raise FatalError("%s must be a project directory")
  119. if not os.path.exists(os.path.join(project_dir, "CMakeLists.txt")):
  120. raise FatalError("CMakeLists.txt not found in project directory %s" % project_dir)
  121. # Verify/create the build directory
  122. build_dir = args.build_dir
  123. if not os.path.isdir(build_dir):
  124. os.mkdir(build_dir)
  125. cache_path = os.path.join(build_dir, "CMakeCache.txt")
  126. if not os.path.exists(cache_path) or always_run_cmake:
  127. if args.generator is None:
  128. args.generator = detect_cmake_generator()
  129. try:
  130. cmake_args = ["cmake", "-G", args.generator]
  131. if not args.no_warnings:
  132. cmake_args += [ "--warn-uninitialized" ]
  133. if args.no_ccache:
  134. cmake_args += [ "-DCCACHE_DISABLE=1" ]
  135. cmake_args += [ project_dir]
  136. _run_tool("cmake", cmake_args, cwd=args.build_dir)
  137. except:
  138. # don't allow partially valid CMakeCache.txt files,
  139. # to keep the "should I run cmake?" logic simple
  140. if os.path.exists(cache_path):
  141. os.remove(cache_path)
  142. raise
  143. # Learn some things from the CMakeCache.txt file in the build directory
  144. cache = parse_cmakecache(cache_path)
  145. try:
  146. generator = cache["CMAKE_GENERATOR"]
  147. except KeyError:
  148. generator = detect_cmake_generator()
  149. if args.generator is None:
  150. args.generator = generator # reuse the previously configured generator, if none was given
  151. if generator != args.generator:
  152. raise FatalError("Build is configured for generator '%s' not '%s'. Run 'idf.py fullclean' to start again."
  153. % (generator, args.generator))
  154. try:
  155. home_dir = cache["CMAKE_HOME_DIRECTORY"]
  156. if os.path.normcase(os.path.realpath(home_dir)) != os.path.normcase(os.path.realpath(project_dir)):
  157. raise FatalError("Build directory '%s' configured for project '%s' not '%s'. Run 'idf.py fullclean' to start again."
  158. % (build_dir, os.path.realpath(home_dir), os.path.realpath(project_dir)))
  159. except KeyError:
  160. pass # if cmake failed part way, CMAKE_HOME_DIRECTORY may not be set yet
  161. def parse_cmakecache(path):
  162. """
  163. Parse the CMakeCache file at 'path'.
  164. Returns a dict of name:value.
  165. CMakeCache entries also each have a "type", but this is currently ignored.
  166. """
  167. result = {}
  168. with open(path) as f:
  169. for line in f:
  170. # cmake cache lines look like: CMAKE_CXX_FLAGS_DEBUG:STRING=-g
  171. # groups are name, type, value
  172. m = re.match(r"^([^#/:=]+):([^:=]+)=(.+)\n$", line)
  173. if m:
  174. result[m.group(1)] = m.group(3)
  175. return result
  176. def build_target(target_name, args):
  177. """
  178. Execute the target build system to build target 'target_name'
  179. Calls _ensure_build_directory() which will run cmake to generate a build
  180. directory (with the specified generator) as needed.
  181. """
  182. _ensure_build_directory(args)
  183. generator_cmd = GENERATOR_CMDS[args.generator]
  184. if not args.no_ccache:
  185. # Setting CCACHE_BASEDIR & CCACHE_NO_HASHDIR ensures that project paths aren't stored in the ccache entries
  186. # (this means ccache hits can be shared between different projects. It may mean that some debug information
  187. # will point to files in another project, if these files are perfect duplicates of each other.)
  188. #
  189. # It would be nicer to set these from cmake, but there's no cross-platform way to set build-time environment
  190. #os.environ["CCACHE_BASEDIR"] = args.build_dir
  191. #os.environ["CCACHE_NO_HASHDIR"] = "1"
  192. pass
  193. if args.verbose:
  194. generator_cmd += [ GENERATOR_VERBOSE[args.generator] ]
  195. _run_tool(generator_cmd[0], generator_cmd + [target_name], args.build_dir)
  196. def _get_esptool_args(args):
  197. esptool_path = os.path.join(os.environ["IDF_PATH"], "components/esptool_py/esptool/esptool.py")
  198. result = [ PYTHON, esptool_path ]
  199. if args.port is not None:
  200. result += [ "-p", args.port ]
  201. result += [ "-b", str(args.baud) ]
  202. return result
  203. def flash(action, args):
  204. """
  205. Run esptool to flash the entire project, from an argfile generated by the build system
  206. """
  207. flasher_args_path = { # action -> name of flasher args file generated by build system
  208. "bootloader-flash": "flash_bootloader_args",
  209. "partition_table-flash": "flash_partition_table_args",
  210. "app-flash": "flash_app_args",
  211. "flash": "flash_project_args",
  212. }[action]
  213. esptool_args = _get_esptool_args(args)
  214. esptool_args += [ "write_flash", "@"+flasher_args_path ]
  215. _run_tool("esptool.py", esptool_args, args.build_dir)
  216. def erase_flash(action, args):
  217. esptool_args = _get_esptool_args(args)
  218. esptool_args += [ "erase_flash" ]
  219. _run_tool("esptool.py", esptool_args, args.build_dir)
  220. def monitor(action, args):
  221. """
  222. Run idf_monitor.py to watch build output
  223. """
  224. desc_path = os.path.join(args.build_dir, "project_description.json")
  225. if not os.path.exists(desc_path):
  226. _ensure_build_directory(args)
  227. with open(desc_path, "r") as f:
  228. project_desc = json.load(f)
  229. elf_file = os.path.join(args.build_dir, project_desc["app_elf"])
  230. if not os.path.exists(elf_file):
  231. 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)
  232. idf_monitor = os.path.join(os.environ["IDF_PATH"], "tools/idf_monitor.py")
  233. monitor_args = [PYTHON, idf_monitor ]
  234. if args.port is not None:
  235. monitor_args += [ "-p", args.port ]
  236. monitor_args += [ "-b", project_desc["monitor_baud"] ]
  237. monitor_args += [ elf_file ]
  238. idf_py = [ PYTHON ] + get_commandline_options() # commands to re-run idf.py
  239. monitor_args += [ "-m", " ".join("'%s'" % a for a in idf_py) ]
  240. if "MSYSTEM" is os.environ:
  241. monitor_args = [ "winpty" ] + monitor_args
  242. _run_tool("idf_monitor", monitor_args, args.project_dir)
  243. def clean(action, args):
  244. if not os.path.isdir(args.build_dir):
  245. print("Build directory '%s' not found. Nothing to clean." % args.build_dir)
  246. return
  247. build_target("clean", args)
  248. def reconfigure(action, args):
  249. _ensure_build_directory(args, True)
  250. def fullclean(action, args):
  251. build_dir = args.build_dir
  252. if not os.path.isdir(build_dir):
  253. print("Build directory '%s' not found. Nothing to clean." % build_dir)
  254. return
  255. if len(os.listdir(build_dir)) == 0:
  256. print("Build directory '%s' is empty. Nothing to clean." % build_dir)
  257. return
  258. if not os.path.exists(os.path.join(build_dir, "CMakeCache.txt")):
  259. 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)
  260. red_flags = [ "CMakeLists.txt", ".git", ".svn" ]
  261. for red in red_flags:
  262. red = os.path.join(build_dir, red)
  263. if os.path.exists(red):
  264. raise FatalError("Refusing to automatically delete files in directory containing '%s'. Delete files manually if you're sure." % red)
  265. # OK, delete everything in the build directory...
  266. for f in os.listdir(build_dir): # TODO: once we are Python 3 only, this can be os.scandir()
  267. f = os.path.join(build_dir, f)
  268. if os.path.isdir(f):
  269. shutil.rmtree(f)
  270. else:
  271. os.remove(f)
  272. def print_closing_message(args):
  273. # print a closing message of some kind
  274. #
  275. if "flash" in str(args.actions):
  276. print("Done")
  277. return
  278. # Otherwise, if we built any binaries print a message about
  279. # how to flash them
  280. def print_flashing_message(title, key):
  281. print("\n%s build complete. To flash, run this command:" % title)
  282. with open(os.path.join(args.build_dir, "flasher_args.json")) as f:
  283. flasher_args = json.load(f)
  284. def flasher_path(f):
  285. return os.path.relpath(os.path.join(args.build_dir, f))
  286. if key != "project":
  287. cmd = ""
  288. if key == "bootloader":
  289. cmd = " ".join(flasher_args["write_flash_args"]) + " "
  290. cmd += flasher_args[key]["offset"] + " "
  291. cmd += flasher_path(flasher_args[key]["file"])
  292. else:
  293. cmd = " ".join(flasher_args["write_flash_args"]) + " "
  294. for o,f in flasher_args["flash_files"].items():
  295. cmd += o + " " + flasher_path(f) + " "
  296. print("%s -p %s -b %s write_flash %s" % (
  297. os.path.relpath("%s/components/esptool_py/esptool/esptool.py" % os.environ["IDF_PATH"]),
  298. args.port or "(PORT)",
  299. args.baud,
  300. cmd.strip()))
  301. print("or run 'idf.py %s'" % (key + "-flash" if key != "project" else "flash",))
  302. if "all" in args.actions or "build" in args.actions:
  303. print_flashing_message("Project", "project")
  304. else:
  305. if "app" in args.actions:
  306. print_flashing_message("App", "app")
  307. if "partition_table" in args.actions:
  308. print_flashing_message("Partition Table", "partition_table")
  309. if "bootloader" in args.actions:
  310. print_flashing_message("Bootloader", "bootloader")
  311. ACTIONS = {
  312. # action name : ( function (or alias), dependencies, order-only dependencies )
  313. "all" : ( build_target, [], [ "reconfigure", "menuconfig", "clean", "fullclean" ] ),
  314. "build": ( "all", [], [] ), # build is same as 'all' target
  315. "clean": ( clean, [], [ "fullclean" ] ),
  316. "fullclean": ( fullclean, [], [] ),
  317. "reconfigure": ( reconfigure, [], [ "menuconfig" ] ),
  318. "menuconfig": ( build_target, [], [] ),
  319. "size": ( build_target, [ "app" ], [] ),
  320. "size-components": ( build_target, [ "app" ], [] ),
  321. "size-files": ( build_target, [ "app" ], [] ),
  322. "bootloader": ( build_target, [], [] ),
  323. "bootloader-clean": ( build_target, [], [] ),
  324. "bootloader-flash": ( flash, [ "bootloader" ], [ "erase_flash"] ),
  325. "app": ( build_target, [], [ "clean", "fullclean", "reconfigure" ] ),
  326. "app-flash": ( flash, [ "app" ], [ "erase_flash"]),
  327. "partition_table": ( build_target, [], [ "reconfigure" ] ),
  328. "partition_table-flash": ( flash, [ "partition_table" ], [ "erase_flash" ]),
  329. "flash": ( flash, [ "all" ], [ "erase_flash" ] ),
  330. "erase_flash": ( erase_flash, [], []),
  331. "monitor": ( monitor, [], [ "flash", "partition_table-flash", "bootloader-flash", "app-flash" ]),
  332. }
  333. def get_commandline_options():
  334. """ Return all the command line options up to but not including the action """
  335. result = []
  336. for a in sys.argv:
  337. if a in ACTIONS.keys():
  338. break
  339. else:
  340. result.append(a)
  341. return result
  342. def main():
  343. if sys.version_info[0] != 2 or sys.version_info[1] != 7:
  344. raise FatalError("ESP-IDF currently only supports Python 2.7, and this is Python %d.%d.%d. Search for 'Setting the Python Interpreter' in the ESP-IDF docs for some tips to handle this." % sys.version_info[:3])
  345. parser = argparse.ArgumentParser(description='ESP-IDF build management tool')
  346. parser.add_argument('-p', '--port', help="Serial port",
  347. default=os.environ.get('ESPPORT', None))
  348. parser.add_argument('-b', '--baud', help="Baud rate",
  349. default=os.environ.get('ESPBAUD', 460800))
  350. parser.add_argument('-C', '--project-dir', help="Project directory", default=os.getcwd())
  351. parser.add_argument('-B', '--build-dir', help="Build directory", default=None)
  352. parser.add_argument('-G', '--generator', help="Cmake generator", choices=GENERATOR_CMDS.keys())
  353. parser.add_argument('-n', '--no-warnings', help="Disable Cmake warnings", action="store_true")
  354. parser.add_argument('-v', '--verbose', help="Verbose build output", action="store_true")
  355. 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")
  356. parser.add_argument('actions', help="Actions (build targets or other operations)", nargs='+',
  357. choices=ACTIONS.keys())
  358. args = parser.parse_args()
  359. check_environment()
  360. # Advanced parameter checks
  361. if args.build_dir is not None and os.path.realpath(args.project_dir) == os.path.realpath(args.build_dir):
  362. 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.")
  363. if args.build_dir is None:
  364. args.build_dir = os.path.join(args.project_dir, "build")
  365. args.build_dir = os.path.realpath(args.build_dir)
  366. completed_actions = set()
  367. def execute_action(action, remaining_actions):
  368. ( function, dependencies, order_dependencies ) = ACTIONS[action]
  369. # very simple dependency management, build a set of completed actions and make sure
  370. # all dependencies are in it
  371. for dep in dependencies:
  372. if not dep in completed_actions:
  373. execute_action(dep, remaining_actions)
  374. for dep in order_dependencies:
  375. if dep in remaining_actions and not dep in completed_actions:
  376. execute_action(dep, remaining_actions)
  377. if action in completed_actions:
  378. pass # we've already done this, don't do it twice...
  379. elif function in ACTIONS: # alias of another action
  380. execute_action(function, remaining_actions)
  381. else:
  382. function(action, args)
  383. completed_actions.add(action)
  384. actions = list(args.actions)
  385. while len(actions) > 0:
  386. execute_action(actions[0], actions[1:])
  387. actions.pop(0)
  388. print_closing_message(args)
  389. if __name__ == "__main__":
  390. try:
  391. main()
  392. except FatalError as e:
  393. print(e)
  394. sys.exit(2)