core_ext.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  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_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. args.define_cache_entry.append("IDF_TARGET=" + idf_target)
  120. sdkconfig_path = os.path.join(args.project_dir, 'sdkconfig')
  121. sdkconfig_old = sdkconfig_path + ".old"
  122. if os.path.exists(sdkconfig_old):
  123. os.remove(sdkconfig_old)
  124. if os.path.exists(sdkconfig_path):
  125. os.rename(sdkconfig_path, sdkconfig_old)
  126. print("Set Target to: %s, new sdkconfig created. Existing sdkconfig renamed to sdkconfig.old." % idf_target)
  127. ensure_build_directory(args, ctx.info_name, True)
  128. def reconfigure(action, ctx, args):
  129. ensure_build_directory(args, ctx.info_name, True)
  130. def validate_root_options(ctx, args, tasks):
  131. args.project_dir = realpath(args.project_dir)
  132. if args.build_dir is not None and args.project_dir == realpath(args.build_dir):
  133. raise FatalError(
  134. "Setting the build directory to the project directory is not supported. Suggest dropping "
  135. "--build-dir option, the default is a 'build' subdirectory inside the project directory.")
  136. if args.build_dir is None:
  137. args.build_dir = os.path.join(args.project_dir, "build")
  138. args.build_dir = realpath(args.build_dir)
  139. def idf_version_callback(ctx, param, value):
  140. if not value or ctx.resilient_parsing:
  141. return
  142. version = idf_version()
  143. if not version:
  144. raise FatalError("ESP-IDF version cannot be determined")
  145. print("ESP-IDF %s" % version)
  146. sys.exit(0)
  147. def list_targets_callback(ctx, param, value):
  148. if not value or ctx.resilient_parsing:
  149. return
  150. for target in SUPPORTED_TARGETS:
  151. print(target)
  152. sys.exit(0)
  153. root_options = {
  154. "global_options": [
  155. {
  156. "names": ["--version"],
  157. "help": "Show IDF version and exit.",
  158. "is_flag": True,
  159. "expose_value": False,
  160. "callback": idf_version_callback
  161. },
  162. {
  163. "names": ["--list-targets"],
  164. "help": "Print list of supported targets and exit.",
  165. "is_flag": True,
  166. "expose_value": False,
  167. "callback": list_targets_callback
  168. },
  169. {
  170. "names": ["-C", "--project-dir"],
  171. "help": "Project directory.",
  172. "type": click.Path(),
  173. "default": os.getcwd(),
  174. },
  175. {
  176. "names": ["-B", "--build-dir"],
  177. "help": "Build directory.",
  178. "type": click.Path(),
  179. "default": None,
  180. },
  181. {
  182. "names": ["-w/-n", "--cmake-warn-uninitialized/--no-warnings"],
  183. "help": ("Enable CMake uninitialized variable warnings for CMake files inside the project directory. "
  184. "(--no-warnings is now the default, and doesn't need to be specified.)"),
  185. "envvar": "IDF_CMAKE_WARN_UNINITIALIZED",
  186. "is_flag": True,
  187. "default": False,
  188. },
  189. {
  190. "names": ["-v", "--verbose"],
  191. "help": "Verbose build output.",
  192. "is_flag": True,
  193. "is_eager": True,
  194. "default": False,
  195. "callback": verbose_callback
  196. },
  197. {
  198. "names": ["--ccache/--no-ccache"],
  199. "help": (
  200. "Use ccache in build. Disabled by default, unless "
  201. "IDF_CCACHE_ENABLE environment variable is set to a non-zero value."),
  202. "is_flag": True,
  203. "default": os.getenv("IDF_CCACHE_ENABLE") not in [None, "", "0"],
  204. },
  205. {
  206. "names": ["-G", "--generator"],
  207. "help": "CMake generator.",
  208. "type": click.Choice(GENERATORS.keys()),
  209. },
  210. {
  211. "names": ["--dry-run"],
  212. "help": "Only process arguments, but don't execute actions.",
  213. "is_flag": True,
  214. "hidden": True,
  215. "default": False
  216. },
  217. ],
  218. "global_action_callbacks": [validate_root_options],
  219. }
  220. build_actions = {
  221. "actions": {
  222. "all": {
  223. "aliases": ["build"],
  224. "callback": build_target,
  225. "short_help": "Build the project.",
  226. "help": (
  227. "Build the project. This can involve multiple steps:\n\n"
  228. "1. Create the build directory if needed. "
  229. "The sub-directory 'build' is used to hold build output, "
  230. "although this can be changed with the -B option.\n\n"
  231. "2. Run CMake as necessary to configure the project "
  232. "and generate build files for the main build tool.\n\n"
  233. "3. Run the main build tool (Ninja or GNU Make). "
  234. "By default, the build tool is automatically detected "
  235. "but it can be explicitly set by passing the -G option to idf.py.\n\n"),
  236. "options": global_options,
  237. "order_dependencies": [
  238. "reconfigure",
  239. "menuconfig",
  240. "clean",
  241. "fullclean",
  242. ],
  243. },
  244. "menuconfig": {
  245. "callback": menuconfig,
  246. "help": 'Run "menuconfig" project configuration tool.',
  247. "options": global_options + [
  248. {
  249. "names": ["--style", "--color-scheme", "style"],
  250. "help": (
  251. "Menuconfig style.\n"
  252. "Is it possible to customize the menuconfig style by either setting the MENUCONFIG_STYLE "
  253. "environment variable or through this option. The built-in styles include:\n\n"
  254. "- default - a yellowish theme,\n\n"
  255. "- monochrome - a black and white theme, or\n"
  256. "- aquatic - a blue theme.\n\n"
  257. "The default value is \"aquatic\". It is possible to customize these themes further "
  258. "as it is described in the Color schemes section of the kconfiglib documentation."),
  259. "default": os.environ.get('MENUCONFIG_STYLE', 'aquatic'),
  260. }
  261. ],
  262. },
  263. "confserver": {
  264. "callback": build_target,
  265. "help": "Run JSON configuration server.",
  266. "options": global_options,
  267. },
  268. "size": {
  269. "callback": build_target,
  270. "help": "Print basic size information about the app.",
  271. "options": global_options,
  272. "dependencies": ["app"],
  273. },
  274. "size-components": {
  275. "callback": build_target,
  276. "help": "Print per-component size information.",
  277. "options": global_options,
  278. "dependencies": ["app"],
  279. },
  280. "size-files": {
  281. "callback": build_target,
  282. "help": "Print per-source-file size information.",
  283. "options": global_options,
  284. "dependencies": ["app"],
  285. },
  286. "bootloader": {
  287. "callback": build_target,
  288. "help": "Build only bootloader.",
  289. "options": global_options,
  290. },
  291. "app": {
  292. "callback": build_target,
  293. "help": "Build only the app.",
  294. "order_dependencies": ["clean", "fullclean", "reconfigure"],
  295. "options": global_options,
  296. },
  297. "efuse_common_table": {
  298. "callback": build_target,
  299. "help": "Generate C-source for IDF's eFuse fields.",
  300. "order_dependencies": ["reconfigure"],
  301. "options": global_options,
  302. },
  303. "efuse_custom_table": {
  304. "callback": build_target,
  305. "help": "Generate C-source for user's eFuse fields.",
  306. "order_dependencies": ["reconfigure"],
  307. "options": global_options,
  308. },
  309. "show_efuse_table": {
  310. "callback": build_target,
  311. "help": "Print eFuse table.",
  312. "order_dependencies": ["reconfigure"],
  313. "options": global_options,
  314. },
  315. "partition_table": {
  316. "callback": build_target,
  317. "help": "Build only partition table.",
  318. "order_dependencies": ["reconfigure"],
  319. "options": global_options,
  320. },
  321. "erase_otadata": {
  322. "callback": build_target,
  323. "help": "Erase otadata partition.",
  324. "options": global_options,
  325. },
  326. "read_otadata": {
  327. "callback": build_target,
  328. "help": "Read otadata partition.",
  329. "options": global_options,
  330. },
  331. "fallback": {
  332. "callback": fallback_target,
  333. "help": "Handle for targets not known for idf.py.",
  334. "hidden": True
  335. }
  336. }
  337. }
  338. clean_actions = {
  339. "actions": {
  340. "reconfigure": {
  341. "callback": reconfigure,
  342. "short_help": "Re-run CMake.",
  343. "help": (
  344. "Re-run CMake even if it doesn't seem to need re-running. "
  345. "This isn't necessary during normal usage, "
  346. "but can be useful after adding/removing files from the source tree, "
  347. "or when modifying CMake cache variables. "
  348. "For example, \"idf.py -DNAME='VALUE' reconfigure\" "
  349. 'can be used to set variable "NAME" in CMake cache to value "VALUE".'),
  350. "options": global_options,
  351. "order_dependencies": ["menuconfig", "fullclean"],
  352. },
  353. "set-target": {
  354. "callback": set_target,
  355. "short_help": "Set the chip target to build.",
  356. "help": (
  357. "Set the chip target to build. This will remove the "
  358. "existing sdkconfig file and corresponding CMakeCache and "
  359. "create new ones according to the new target.\nFor example, "
  360. "\"idf.py set-target esp32\" will select esp32 as the new chip "
  361. "target."),
  362. "arguments": [
  363. {
  364. "names": ["idf-target"],
  365. "nargs": 1,
  366. "type": TargetChoice(SUPPORTED_TARGETS),
  367. },
  368. ],
  369. "dependencies": ["fullclean"],
  370. },
  371. "clean": {
  372. "callback": clean,
  373. "short_help": "Delete build output files from the build directory.",
  374. "help": (
  375. "Delete build output files from the build directory, "
  376. "forcing a 'full rebuild' the next time "
  377. "the project is built. Cleaning doesn't delete "
  378. "CMake configuration output and some other files"),
  379. "order_dependencies": ["fullclean"],
  380. },
  381. "fullclean": {
  382. "callback": fullclean,
  383. "short_help": "Delete the entire build directory contents.",
  384. "help": (
  385. "Delete the entire build directory contents. "
  386. "This includes all CMake configuration output."
  387. "The next time the project is built, "
  388. "CMake will configure it from scratch. "
  389. "Note that this option recursively deletes all files "
  390. "in the build directory, so use with care."
  391. "Project configuration is not deleted.")
  392. },
  393. "python-clean": {
  394. "callback": python_clean,
  395. "short_help": "Delete generated Python byte code from the IDF directory",
  396. "help": (
  397. "Delete generated Python byte code from the IDF directory "
  398. "which may cause issues when switching between IDF and Python versions. "
  399. "It is advised to run this target after switching versions.")
  400. },
  401. }
  402. }
  403. return merge_action_lists(root_options, build_actions, clean_actions)