core_ext.py 18 KB

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