core_ext.py 18 KB

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