core_ext.py 19 KB

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