core_ext.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. import fnmatch
  2. import os
  3. import shutil
  4. import subprocess
  5. import sys
  6. import click
  7. from idf_py_actions.constants import GENERATORS, SUPPORTED_TARGETS
  8. from idf_py_actions.errors import FatalError
  9. from idf_py_actions.global_options import global_options
  10. from idf_py_actions.tools import ensure_build_directory, idf_version, merge_action_lists, realpath, run_tool
  11. def action_extensions(base_actions, project_path):
  12. def run_target(target_name, args):
  13. generator_cmd = GENERATORS[args.generator]["command"]
  14. if args.verbose:
  15. generator_cmd += [GENERATORS[args.generator]["verbose_flag"]]
  16. run_tool(generator_cmd[0], generator_cmd + [target_name], args.build_dir)
  17. def build_target(target_name, ctx, args):
  18. """
  19. Execute the target build system to build target 'target_name'
  20. Calls ensure_build_directory() which will run cmake to generate a build
  21. directory (with the specified generator) as needed.
  22. """
  23. ensure_build_directory(args, ctx.info_name)
  24. run_target(target_name, args)
  25. def menuconfig(target_name, ctx, args, style):
  26. """
  27. Menuconfig target is build_target extended with the style argument for setting the value for the environment
  28. variable.
  29. """
  30. if sys.version_info[0] < 3:
  31. # The subprocess lib cannot accept environment variables as "unicode".
  32. # This encoding step is required only in Python 2.
  33. style = style.encode(sys.getfilesystemencoding() or 'utf-8')
  34. os.environ['MENUCONFIG_STYLE'] = style
  35. build_target(target_name, ctx, args)
  36. def fallback_target(target_name, ctx, args):
  37. """
  38. Execute targets that are not explicitly known to idf.py
  39. """
  40. ensure_build_directory(args, ctx.info_name)
  41. try:
  42. subprocess.check_output(GENERATORS[args.generator]["dry_run"] + [target_name], cwd=args.build_dir)
  43. except Exception:
  44. raise FatalError(
  45. 'command "%s" is not known to idf.py and is not a %s target' % (target_name, args.generator))
  46. run_target(target_name, args)
  47. def verbose_callback(ctx, param, value):
  48. if not value or ctx.resilient_parsing:
  49. return
  50. for line in ctx.command.verbose_output:
  51. print(line)
  52. return value
  53. def clean(action, ctx, args):
  54. if not os.path.isdir(args.build_dir):
  55. print("Build directory '%s' not found. Nothing to clean." % args.build_dir)
  56. return
  57. build_target("clean", ctx, args)
  58. def _delete_windows_symlinks(directory):
  59. """
  60. It deletes symlinks recursively on Windows. It is useful for Python 2 which doesn't detect symlinks on Windows.
  61. """
  62. deleted_paths = []
  63. if os.name == "nt":
  64. import ctypes
  65. for root, dirnames, _filenames in os.walk(directory):
  66. for d in dirnames:
  67. full_path = os.path.join(root, d)
  68. try:
  69. full_path = full_path.decode("utf-8")
  70. except Exception:
  71. pass
  72. if ctypes.windll.kernel32.GetFileAttributesW(full_path) & 0x0400:
  73. os.rmdir(full_path)
  74. deleted_paths.append(full_path)
  75. return deleted_paths
  76. def fullclean(action, ctx, args):
  77. build_dir = args.build_dir
  78. if not os.path.isdir(build_dir):
  79. print("Build directory '%s' not found. Nothing to clean." % build_dir)
  80. return
  81. if len(os.listdir(build_dir)) == 0:
  82. print("Build directory '%s' is empty. Nothing to clean." % build_dir)
  83. return
  84. if not os.path.exists(os.path.join(build_dir, "CMakeCache.txt")):
  85. raise FatalError(
  86. "Directory '%s' doesn't seem to be a CMake build directory. Refusing to automatically "
  87. "delete files in this directory. Delete the directory manually to 'clean' it." % build_dir)
  88. red_flags = ["CMakeLists.txt", ".git", ".svn"]
  89. for red in red_flags:
  90. red = os.path.join(build_dir, red)
  91. if os.path.exists(red):
  92. raise FatalError(
  93. "Refusing to automatically delete files in directory containing '%s'. Delete files manually if you're sure."
  94. % red)
  95. # OK, delete everything in the build directory...
  96. # Note: Python 2.7 doesn't detect symlinks on Windows (it is supported form 3.2). Tools promising to not
  97. # follow symlinks will actually follow them. Deleting the build directory with symlinks deletes also items
  98. # outside of this directory.
  99. deleted_symlinks = _delete_windows_symlinks(build_dir)
  100. if args.verbose and len(deleted_symlinks) > 1:
  101. print("The following symlinks were identified and removed:\n%s" % "\n".join(deleted_symlinks))
  102. for f in os.listdir(build_dir): # TODO: once we are Python 3 only, this can be os.scandir()
  103. f = os.path.join(build_dir, f)
  104. if args.verbose:
  105. print("Removing: %s" % f)
  106. if os.path.isdir(f):
  107. shutil.rmtree(f)
  108. else:
  109. os.remove(f)
  110. def python_clean(action, ctx, args):
  111. for root, dirnames, filenames in os.walk(os.environ["IDF_PATH"]):
  112. for d in dirnames:
  113. if d == "__pycache__":
  114. dir_to_delete = os.path.join(root, d)
  115. if args.verbose:
  116. print("Removing: %s" % dir_to_delete)
  117. shutil.rmtree(dir_to_delete)
  118. for filename in fnmatch.filter(filenames, '*.py[co]'):
  119. file_to_delete = os.path.join(root, filename)
  120. if args.verbose:
  121. print("Removing: %s" % file_to_delete)
  122. os.remove(file_to_delete)
  123. def set_target(action, ctx, args, idf_target):
  124. args.define_cache_entry.append("IDF_TARGET=" + idf_target)
  125. sdkconfig_path = os.path.join(args.project_dir, 'sdkconfig')
  126. sdkconfig_old = sdkconfig_path + ".old"
  127. if os.path.exists(sdkconfig_old):
  128. os.remove(sdkconfig_old)
  129. if os.path.exists(sdkconfig_path):
  130. os.rename(sdkconfig_path, sdkconfig_old)
  131. print("Set Target to: %s, new sdkconfig created. Existing sdkconfig renamed to sdkconfig.old." % idf_target)
  132. ensure_build_directory(args, ctx.info_name, True)
  133. def reconfigure(action, ctx, args):
  134. ensure_build_directory(args, ctx.info_name, True)
  135. def validate_root_options(ctx, args, tasks):
  136. args.project_dir = realpath(args.project_dir)
  137. if args.build_dir is not None and args.project_dir == realpath(args.build_dir):
  138. raise FatalError(
  139. "Setting the build directory to the project directory is not supported. Suggest dropping "
  140. "--build-dir option, the default is a 'build' subdirectory inside the project directory.")
  141. if args.build_dir is None:
  142. args.build_dir = os.path.join(args.project_dir, "build")
  143. args.build_dir = realpath(args.build_dir)
  144. def idf_version_callback(ctx, param, value):
  145. if not value or ctx.resilient_parsing:
  146. return
  147. version = idf_version()
  148. if not version:
  149. raise FatalError("ESP-IDF version cannot be determined")
  150. print("ESP-IDF %s" % version)
  151. sys.exit(0)
  152. def list_targets_callback(ctx, param, value):
  153. if not value or ctx.resilient_parsing:
  154. return
  155. for target in SUPPORTED_TARGETS:
  156. print(target)
  157. sys.exit(0)
  158. root_options = {
  159. "global_options": [
  160. {
  161. "names": ["--version"],
  162. "help": "Show IDF version and exit.",
  163. "is_flag": True,
  164. "expose_value": False,
  165. "callback": idf_version_callback
  166. },
  167. {
  168. "names": ["--list-targets"],
  169. "help": "Print list of supported targets and exit.",
  170. "is_flag": True,
  171. "expose_value": False,
  172. "callback": list_targets_callback
  173. },
  174. {
  175. "names": ["-C", "--project-dir"],
  176. "help": "Project directory.",
  177. "type": click.Path(),
  178. "default": os.getcwd(),
  179. },
  180. {
  181. "names": ["-B", "--build-dir"],
  182. "help": "Build directory.",
  183. "type": click.Path(),
  184. "default": None,
  185. },
  186. {
  187. "names": ["-n", "--no-warnings"],
  188. "help": "Disable Cmake warnings.",
  189. "is_flag": True,
  190. "default": False,
  191. },
  192. {
  193. "names": ["-v", "--verbose"],
  194. "help": "Verbose build output.",
  195. "is_flag": True,
  196. "is_eager": True,
  197. "default": False,
  198. "callback": verbose_callback
  199. },
  200. {
  201. "names": ["--ccache/--no-ccache"],
  202. "help": (
  203. "Use ccache in build. Disabled by default, unless "
  204. "IDF_CCACHE_ENABLE environment variable is set to a non-zero value."),
  205. "is_flag": True,
  206. "default": os.getenv("IDF_CCACHE_ENABLE") not in [None, "", "0"],
  207. },
  208. {
  209. "names": ["-G", "--generator"],
  210. "help": "CMake generator.",
  211. "type": click.Choice(GENERATORS.keys()),
  212. },
  213. {
  214. "names": ["--dry-run"],
  215. "help": "Only process arguments, but don't execute actions.",
  216. "is_flag": True,
  217. "hidden": True,
  218. "default": False
  219. },
  220. ],
  221. "global_action_callbacks": [validate_root_options],
  222. }
  223. build_actions = {
  224. "actions": {
  225. "all": {
  226. "aliases": ["build"],
  227. "callback": build_target,
  228. "short_help": "Build the project.",
  229. "help": (
  230. "Build the project. This can involve multiple steps:\n\n"
  231. "1. Create the build directory if needed. "
  232. "The sub-directory 'build' is used to hold build output, "
  233. "although this can be changed with the -B option.\n\n"
  234. "2. Run CMake as necessary to configure the project "
  235. "and generate build files for the main build tool.\n\n"
  236. "3. Run the main build tool (Ninja or GNU Make). "
  237. "By default, the build tool is automatically detected "
  238. "but it can be explicitly set by passing the -G option to idf.py.\n\n"),
  239. "options": global_options,
  240. "order_dependencies": [
  241. "reconfigure",
  242. "menuconfig",
  243. "clean",
  244. "fullclean",
  245. ],
  246. },
  247. "menuconfig": {
  248. "callback": menuconfig,
  249. "help": 'Run "menuconfig" project configuration tool.',
  250. "options": global_options + [
  251. {
  252. "names": ["--style", "--color-scheme", "style"],
  253. "help": (
  254. "Menuconfig style.\n"
  255. "Is it possible to customize the menuconfig style by either setting the MENUCONFIG_STYLE "
  256. "environment variable or through this option. The built-in styles include:\n\n"
  257. "- default - a yellowish theme,\n\n"
  258. "- monochrome - a black and white theme, or\n"
  259. "- aquatic - a blue theme.\n\n"
  260. "The default value is \"aquatic\". It is possible to customize these themes further "
  261. "as it is described in the Color schemes section of the kconfiglib documentation."),
  262. "default": os.environ.get('MENUCONFIG_STYLE', 'aquatic'),
  263. }
  264. ],
  265. },
  266. "confserver": {
  267. "callback": build_target,
  268. "help": "Run JSON configuration server.",
  269. "options": global_options,
  270. },
  271. "size": {
  272. "callback": build_target,
  273. "help": "Print basic size information about the app.",
  274. "options": global_options,
  275. "dependencies": ["app"],
  276. },
  277. "size-components": {
  278. "callback": build_target,
  279. "help": "Print per-component size information.",
  280. "options": global_options,
  281. "dependencies": ["app"],
  282. },
  283. "size-files": {
  284. "callback": build_target,
  285. "help": "Print per-source-file size information.",
  286. "options": global_options,
  287. "dependencies": ["app"],
  288. },
  289. "bootloader": {
  290. "callback": build_target,
  291. "help": "Build only bootloader.",
  292. "options": global_options,
  293. },
  294. "app": {
  295. "callback": build_target,
  296. "help": "Build only the app.",
  297. "order_dependencies": ["clean", "fullclean", "reconfigure"],
  298. "options": global_options,
  299. },
  300. "efuse_common_table": {
  301. "callback": build_target,
  302. "help": "Genereate C-source for IDF's eFuse fields.",
  303. "order_dependencies": ["reconfigure"],
  304. "options": global_options,
  305. },
  306. "efuse_custom_table": {
  307. "callback": build_target,
  308. "help": "Genereate C-source for user's eFuse fields.",
  309. "order_dependencies": ["reconfigure"],
  310. "options": global_options,
  311. },
  312. "show_efuse_table": {
  313. "callback": build_target,
  314. "help": "Print eFuse table.",
  315. "order_dependencies": ["reconfigure"],
  316. "options": global_options,
  317. },
  318. "partition_table": {
  319. "callback": build_target,
  320. "help": "Build only partition table.",
  321. "order_dependencies": ["reconfigure"],
  322. "options": global_options,
  323. },
  324. "erase_otadata": {
  325. "callback": build_target,
  326. "help": "Erase otadata partition.",
  327. "options": global_options,
  328. },
  329. "read_otadata": {
  330. "callback": build_target,
  331. "help": "Read otadata partition.",
  332. "options": global_options,
  333. },
  334. "fallback": {
  335. "callback": fallback_target,
  336. "help": "Handle for targets not known for idf.py.",
  337. "hidden": True
  338. }
  339. }
  340. }
  341. clean_actions = {
  342. "actions": {
  343. "reconfigure": {
  344. "callback": reconfigure,
  345. "short_help": "Re-run CMake.",
  346. "help": (
  347. "Re-run CMake even if it doesn't seem to need re-running. "
  348. "This isn't necessary during normal usage, "
  349. "but can be useful after adding/removing files from the source tree, "
  350. "or when modifying CMake cache variables. "
  351. "For example, \"idf.py -DNAME='VALUE' reconfigure\" "
  352. 'can be used to set variable "NAME" in CMake cache to value "VALUE".'),
  353. "options": global_options,
  354. "order_dependencies": ["menuconfig", "fullclean"],
  355. },
  356. "set-target": {
  357. "callback": set_target,
  358. "short_help": "Set the chip target to build.",
  359. "help": (
  360. "Set the chip target to build. This will remove the "
  361. "existing sdkconfig file and corresponding CMakeCache and "
  362. "create new ones according to the new target.\nFor example, "
  363. "\"idf.py set-target esp32\" will select esp32 as the new chip "
  364. "target."),
  365. "arguments": [
  366. {
  367. "names": ["idf-target"],
  368. "nargs": 1,
  369. "type": click.Choice(SUPPORTED_TARGETS),
  370. },
  371. ],
  372. "dependencies": ["fullclean"],
  373. },
  374. "clean": {
  375. "callback": clean,
  376. "short_help": "Delete build output files from the build directory.",
  377. "help": (
  378. "Delete build output files from the build directory, "
  379. "forcing a 'full rebuild' the next time "
  380. "the project is built. Cleaning doesn't delete "
  381. "CMake configuration output and some other files"),
  382. "order_dependencies": ["fullclean"],
  383. },
  384. "fullclean": {
  385. "callback": fullclean,
  386. "short_help": "Delete the entire build directory contents.",
  387. "help": (
  388. "Delete the entire build directory contents. "
  389. "This includes all CMake configuration output."
  390. "The next time the project is built, "
  391. "CMake will configure it from scratch. "
  392. "Note that this option recursively deletes all files "
  393. "in the build directory, so use with care."
  394. "Project configuration is not deleted.")
  395. },
  396. "python-clean": {
  397. "callback": python_clean,
  398. "short_help": "Delete generated Python byte code from the IDF directory",
  399. "help": (
  400. "Delete generated Python byte code from the IDF directory "
  401. "which may cause issues when switching between IDF and Python versions. "
  402. "It is advised to run this target after switching versions.")
  403. },
  404. }
  405. }
  406. return merge_action_lists(root_options, build_actions, clean_actions)