labextensions.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598
  1. """Jupyter LabExtension Entry Points."""
  2. # Copyright (c) Jupyter Development Team.
  3. # Distributed under the terms of the Modified BSD License.
  4. import os
  5. import sys
  6. from copy import copy
  7. from jupyter_core.application import JupyterApp, base_aliases, base_flags
  8. from traitlets import Bool, Instance, List, Unicode, default
  9. from jupyterlab.coreconfig import CoreConfig
  10. from jupyterlab.debuglog import DebugLogFileMixin
  11. from .commands import (
  12. HERE,
  13. AppOptions,
  14. build,
  15. check_extension,
  16. disable_extension,
  17. enable_extension,
  18. get_app_version,
  19. install_extension,
  20. link_package,
  21. list_extensions,
  22. lock_extension,
  23. uninstall_extension,
  24. unlink_package,
  25. unlock_extension,
  26. update_extension,
  27. )
  28. from .federated_labextensions import build_labextension, develop_labextension_py, watch_labextension
  29. from .labapp import LabApp
  30. flags = dict(base_flags)
  31. flags["no-build"] = (
  32. {"BaseExtensionApp": {"should_build": False}},
  33. "Defer building the app after the action.",
  34. )
  35. flags["dev-build"] = (
  36. {"BaseExtensionApp": {"dev_build": True}},
  37. "Build in development mode.",
  38. )
  39. flags["no-minimize"] = (
  40. {"BaseExtensionApp": {"minimize": False}},
  41. "Do not minimize a production build.",
  42. )
  43. flags["clean"] = (
  44. {"BaseExtensionApp": {"should_clean": True}},
  45. "Cleanup intermediate files after the action.",
  46. )
  47. flags["splice-source"] = (
  48. {"BaseExtensionApp": {"splice_source": True}},
  49. "Splice source packages into app directory.",
  50. )
  51. check_flags = copy(flags)
  52. check_flags["installed"] = (
  53. {"CheckLabExtensionsApp": {"should_check_installed_only": True}},
  54. "Check only if the extension is installed.",
  55. )
  56. develop_flags = copy(flags)
  57. develop_flags["overwrite"] = (
  58. {"DevelopLabExtensionApp": {"overwrite": True}},
  59. "Overwrite files",
  60. )
  61. update_flags = copy(flags)
  62. update_flags["all"] = (
  63. {"UpdateLabExtensionApp": {"all": True}},
  64. "Update all extensions",
  65. )
  66. uninstall_flags = copy(flags)
  67. uninstall_flags["all"] = (
  68. {"UninstallLabExtensionApp": {"all": True}},
  69. "Uninstall all extensions",
  70. )
  71. list_flags = copy(flags)
  72. list_flags["verbose"] = (
  73. {"ListLabExtensionsApp": {"verbose": True}},
  74. "Increase verbosity level",
  75. )
  76. aliases = dict(base_aliases)
  77. aliases["app-dir"] = "BaseExtensionApp.app_dir"
  78. aliases["dev-build"] = "BaseExtensionApp.dev_build"
  79. aliases["minimize"] = "BaseExtensionApp.minimize"
  80. aliases["debug-log-path"] = "DebugLogFileMixin.debug_log_path"
  81. install_aliases = copy(aliases)
  82. install_aliases["pin-version-as"] = "InstallLabExtensionApp.pin"
  83. enable_aliases = copy(aliases)
  84. enable_aliases["level"] = "EnableLabExtensionsApp.level"
  85. disable_aliases = copy(aliases)
  86. disable_aliases["level"] = "DisableLabExtensionsApp.level"
  87. lock_aliases = copy(aliases)
  88. lock_aliases["level"] = "LockLabExtensionsApp.level"
  89. unlock_aliases = copy(aliases)
  90. unlock_aliases["level"] = "UnlockLabExtensionsApp.level"
  91. VERSION = get_app_version()
  92. LABEXTENSION_COMMAND_WARNING = "Users should manage prebuilt extensions with package managers like pip and conda, and extension authors are encouraged to distribute their extensions as prebuilt packages"
  93. class BaseExtensionApp(JupyterApp, DebugLogFileMixin):
  94. version = VERSION
  95. flags = flags
  96. aliases = aliases
  97. name = "lab"
  98. # Not configurable!
  99. core_config = Instance(CoreConfig, allow_none=True)
  100. app_dir = Unicode("", config=True, help="The app directory to target")
  101. should_build = Bool(True, config=True, help="Whether to build the app after the action")
  102. dev_build = Bool(
  103. None,
  104. allow_none=True,
  105. config=True,
  106. help="Whether to build in dev mode. Defaults to True (dev mode) if there are any locally linked extensions, else defaults to False (production mode).",
  107. )
  108. minimize = Bool(
  109. True,
  110. config=True,
  111. help="Whether to minimize a production build (defaults to True).",
  112. )
  113. should_clean = Bool(
  114. False,
  115. config=True,
  116. help="Whether temporary files should be cleaned up after building jupyterlab",
  117. )
  118. splice_source = Bool(False, config=True, help="Splice source packages into app directory.")
  119. labextensions_path = List(
  120. Unicode(),
  121. help="The standard paths to look in for prebuilt JupyterLab extensions",
  122. )
  123. @default("labextensions_path")
  124. def _default_labextensions_path(self):
  125. lab = LabApp()
  126. lab.load_config_file()
  127. return lab.labextensions_path + lab.extra_labextensions_path
  128. @default("splice_source")
  129. def _default_splice_source(self):
  130. version = get_app_version(AppOptions(app_dir=self.app_dir))
  131. return version.endswith("-spliced")
  132. def start(self):
  133. if self.app_dir and self.app_dir.startswith(HERE):
  134. msg = "Cannot run lab extension commands in core app"
  135. raise ValueError(msg)
  136. with self.debug_logging():
  137. ans = self.run_task()
  138. if ans and self.should_build:
  139. production = None if self.dev_build is None else not self.dev_build
  140. app_options = AppOptions(
  141. app_dir=self.app_dir,
  142. logger=self.log,
  143. core_config=self.core_config,
  144. splice_source=self.splice_source,
  145. )
  146. build(
  147. clean_staging=self.should_clean,
  148. production=production,
  149. minimize=self.minimize,
  150. app_options=app_options,
  151. )
  152. def run_task(self):
  153. pass
  154. def deprecation_warning(self, msg):
  155. return self.log.warning(
  156. f"\033[33m(Deprecated) {msg}\n\n{LABEXTENSION_COMMAND_WARNING} \033[0m"
  157. )
  158. def _log_format_default(self):
  159. """A default format for messages"""
  160. return "%(message)s"
  161. class InstallLabExtensionApp(BaseExtensionApp):
  162. description = """Install labextension(s)
  163. Usage
  164. jupyter labextension install [--pin-version-as <alias,...>] <package...>
  165. This installs JupyterLab extensions similar to yarn add or npm install.
  166. Pass a list of comma separate names to the --pin-version-as flag
  167. to use as aliases for the packages providers. This is useful to
  168. install multiple versions of the same extension.
  169. These can be uninstalled with the alias you provided
  170. to the flag, similar to the "alias" feature of yarn add.
  171. """
  172. aliases = install_aliases
  173. pin = Unicode("", config=True, help="Pin this version with a certain alias")
  174. def run_task(self):
  175. self.deprecation_warning(
  176. "Installing extensions with the jupyter labextension install command is now deprecated and will be removed in a future major version of JupyterLab."
  177. )
  178. pinned_versions = self.pin.split(",")
  179. self.extra_args = self.extra_args or [os.getcwd()]
  180. return any(
  181. install_extension(
  182. arg,
  183. # Pass in pinned alias if we have it
  184. pin=pinned_versions[i] if i < len(pinned_versions) else None,
  185. app_options=AppOptions(
  186. app_dir=self.app_dir,
  187. logger=self.log,
  188. core_config=self.core_config,
  189. labextensions_path=self.labextensions_path,
  190. ),
  191. )
  192. for i, arg in enumerate(self.extra_args)
  193. )
  194. class DevelopLabExtensionApp(BaseExtensionApp):
  195. description = "(developer) Develop labextension"
  196. flags = develop_flags
  197. user = Bool(False, config=True, help="Whether to do a user install")
  198. sys_prefix = Bool(True, config=True, help="Use the sys.prefix as the prefix")
  199. overwrite = Bool(False, config=True, help="Whether to overwrite files")
  200. symlink = Bool(True, config=False, help="Whether to use a symlink")
  201. labextensions_dir = Unicode(
  202. "",
  203. config=True,
  204. help="Full path to labextensions dir (probably use prefix or user)",
  205. )
  206. def run_task(self):
  207. """Add config for this labextension"""
  208. self.extra_args = self.extra_args or [os.getcwd()]
  209. for arg in self.extra_args:
  210. develop_labextension_py(
  211. arg,
  212. user=self.user,
  213. sys_prefix=self.sys_prefix,
  214. labextensions_dir=self.labextensions_dir,
  215. logger=self.log,
  216. overwrite=self.overwrite,
  217. symlink=self.symlink,
  218. )
  219. class BuildLabExtensionApp(BaseExtensionApp):
  220. description = "(developer) Build labextension"
  221. static_url = Unicode("", config=True, help="Sets the url for static assets when building")
  222. development = Bool(False, config=True, help="Build in development mode")
  223. source_map = Bool(False, config=True, help="Generate source maps")
  224. core_path = Unicode(
  225. os.path.join(HERE, "staging"),
  226. config=True,
  227. help="Directory containing core application package.json file",
  228. )
  229. aliases = {
  230. "static-url": "BuildLabExtensionApp.static_url",
  231. "development": "BuildLabExtensionApp.development",
  232. "source-map": "BuildLabExtensionApp.source_map",
  233. "core-path": "BuildLabExtensionApp.core_path",
  234. }
  235. def run_task(self):
  236. self.extra_args = self.extra_args or [os.getcwd()]
  237. build_labextension(
  238. self.extra_args[0],
  239. logger=self.log,
  240. development=self.development,
  241. static_url=self.static_url or None,
  242. source_map=self.source_map,
  243. core_path=self.core_path or None,
  244. )
  245. class WatchLabExtensionApp(BaseExtensionApp):
  246. description = "(developer) Watch labextension"
  247. development = Bool(True, config=True, help="Build in development mode")
  248. source_map = Bool(False, config=True, help="Generate source maps")
  249. core_path = Unicode(
  250. os.path.join(HERE, "staging"),
  251. config=True,
  252. help="Directory containing core application package.json file",
  253. )
  254. aliases = {
  255. "core-path": "WatchLabExtensionApp.core_path",
  256. "development": "WatchLabExtensionApp.development",
  257. "source-map": "WatchLabExtensionApp.source_map",
  258. }
  259. def run_task(self):
  260. self.extra_args = self.extra_args or [os.getcwd()]
  261. labextensions_path = self.labextensions_path
  262. watch_labextension(
  263. self.extra_args[0],
  264. labextensions_path,
  265. logger=self.log,
  266. development=self.development,
  267. source_map=self.source_map,
  268. core_path=self.core_path or None,
  269. )
  270. class UpdateLabExtensionApp(BaseExtensionApp):
  271. description = "Update labextension(s)"
  272. flags = update_flags
  273. all = Bool(False, config=True, help="Whether to update all extensions")
  274. def run_task(self):
  275. self.deprecation_warning(
  276. "Updating extensions with the jupyter labextension update command is now deprecated and will be removed in a future major version of JupyterLab."
  277. )
  278. if not self.all and not self.extra_args:
  279. self.log.warning(
  280. "Specify an extension to update, or use --all to update all extensions"
  281. )
  282. return False
  283. app_options = AppOptions(
  284. app_dir=self.app_dir,
  285. logger=self.log,
  286. core_config=self.core_config,
  287. labextensions_path=self.labextensions_path,
  288. )
  289. if self.all:
  290. return update_extension(all_=True, app_options=app_options)
  291. return any(update_extension(name=arg, app_options=app_options) for arg in self.extra_args)
  292. class LinkLabExtensionApp(BaseExtensionApp):
  293. description = """
  294. Link local npm packages that are not lab extensions.
  295. Links a package to the JupyterLab build process. A linked
  296. package is manually re-installed from its source location when
  297. `jupyter lab build` is run.
  298. """
  299. should_build = Bool(True, config=True, help="Whether to build the app after the action")
  300. def run_task(self):
  301. self.extra_args = self.extra_args or [os.getcwd()]
  302. options = AppOptions(
  303. app_dir=self.app_dir,
  304. logger=self.log,
  305. labextensions_path=self.labextensions_path,
  306. core_config=self.core_config,
  307. )
  308. return any(link_package(arg, app_options=options) for arg in self.extra_args)
  309. class UnlinkLabExtensionApp(BaseExtensionApp):
  310. description = "Unlink packages by name or path"
  311. def run_task(self):
  312. self.extra_args = self.extra_args or [os.getcwd()]
  313. options = AppOptions(
  314. app_dir=self.app_dir,
  315. logger=self.log,
  316. labextensions_path=self.labextensions_path,
  317. core_config=self.core_config,
  318. )
  319. return any(unlink_package(arg, app_options=options) for arg in self.extra_args)
  320. class UninstallLabExtensionApp(BaseExtensionApp):
  321. description = "Uninstall labextension(s) by name"
  322. flags = uninstall_flags
  323. all = Bool(False, config=True, help="Whether to uninstall all extensions")
  324. def run_task(self):
  325. self.deprecation_warning(
  326. "Uninstalling extensions with the jupyter labextension uninstall command is now deprecated and will be removed in a future major version of JupyterLab."
  327. )
  328. self.extra_args = self.extra_args or [os.getcwd()]
  329. options = AppOptions(
  330. app_dir=self.app_dir,
  331. logger=self.log,
  332. labextensions_path=self.labextensions_path,
  333. core_config=self.core_config,
  334. )
  335. return any(
  336. uninstall_extension(arg, all_=self.all, app_options=options) for arg in self.extra_args
  337. )
  338. class ListLabExtensionsApp(BaseExtensionApp):
  339. description = "List the installed labextensions"
  340. verbose = Bool(False, help="Increase verbosity level.").tag(config=True)
  341. flags = list_flags
  342. def run_task(self):
  343. list_extensions(
  344. app_options=AppOptions(
  345. app_dir=self.app_dir,
  346. logger=self.log,
  347. core_config=self.core_config,
  348. labextensions_path=self.labextensions_path,
  349. verbose=self.verbose,
  350. )
  351. )
  352. class EnableLabExtensionsApp(BaseExtensionApp):
  353. description = "Enable labextension(s) by name"
  354. aliases = enable_aliases
  355. level = Unicode("sys_prefix", help="Level at which to enable: sys_prefix, user, system").tag(
  356. config=True
  357. )
  358. def run_task(self):
  359. app_options = AppOptions(
  360. app_dir=self.app_dir,
  361. logger=self.log,
  362. core_config=self.core_config,
  363. labextensions_path=self.labextensions_path,
  364. )
  365. [
  366. enable_extension(arg, app_options=app_options, level=self.level)
  367. for arg in self.extra_args
  368. ]
  369. class DisableLabExtensionsApp(BaseExtensionApp):
  370. description = "Disable labextension(s) by name"
  371. aliases = disable_aliases
  372. level = Unicode("sys_prefix", help="Level at which to disable: sys_prefix, user, system").tag(
  373. config=True
  374. )
  375. def run_task(self):
  376. app_options = AppOptions(
  377. app_dir=self.app_dir,
  378. logger=self.log,
  379. core_config=self.core_config,
  380. labextensions_path=self.labextensions_path,
  381. )
  382. [
  383. disable_extension(arg, app_options=app_options, level=self.level)
  384. for arg in self.extra_args
  385. ]
  386. self.log.info(
  387. "Starting with JupyterLab 4.1 individual plugins can be re-enabled"
  388. " in the user interface. While all plugins which were previously"
  389. " disabled have been locked, you need to explicitly lock any newly"
  390. " disabled plugins by using `jupyter labextension lock` command."
  391. )
  392. class LockLabExtensionsApp(BaseExtensionApp):
  393. description = "Lock labextension(s) by name"
  394. aliases = lock_aliases
  395. level = Unicode("sys_prefix", help="Level at which to lock: sys_prefix, user, system").tag(
  396. config=True
  397. )
  398. def run_task(self):
  399. app_options = AppOptions(
  400. app_dir=self.app_dir,
  401. logger=self.log,
  402. core_config=self.core_config,
  403. labextensions_path=self.labextensions_path,
  404. )
  405. [lock_extension(arg, app_options=app_options, level=self.level) for arg in self.extra_args]
  406. class UnlockLabExtensionsApp(BaseExtensionApp):
  407. description = "Unlock labextension(s) by name"
  408. aliases = unlock_aliases
  409. level = Unicode("sys_prefix", help="Level at which to unlock: sys_prefix, user, system").tag(
  410. config=True
  411. )
  412. def run_task(self):
  413. app_options = AppOptions(
  414. app_dir=self.app_dir,
  415. logger=self.log,
  416. core_config=self.core_config,
  417. labextensions_path=self.labextensions_path,
  418. )
  419. [
  420. unlock_extension(arg, app_options=app_options, level=self.level)
  421. for arg in self.extra_args
  422. ]
  423. class CheckLabExtensionsApp(BaseExtensionApp):
  424. description = "Check labextension(s) by name"
  425. flags = check_flags
  426. should_check_installed_only = Bool(
  427. False,
  428. config=True,
  429. help="Whether it should check only if the extensions is installed",
  430. )
  431. def run_task(self):
  432. app_options = AppOptions(
  433. app_dir=self.app_dir,
  434. logger=self.log,
  435. core_config=self.core_config,
  436. labextensions_path=self.labextensions_path,
  437. )
  438. all_enabled = all(
  439. check_extension(
  440. arg, installed=self.should_check_installed_only, app_options=app_options
  441. )
  442. for arg in self.extra_args
  443. )
  444. if not all_enabled:
  445. self.exit(1)
  446. _EXAMPLES = """
  447. jupyter labextension list # list all configured labextensions
  448. jupyter labextension install <extension name> # install a labextension
  449. jupyter labextension uninstall <extension name> # uninstall a labextension
  450. jupyter labextension develop # (developer) develop a prebuilt labextension
  451. jupyter labextension build # (developer) build a prebuilt labextension
  452. jupyter labextension watch # (developer) watch a prebuilt labextension
  453. """
  454. class LabExtensionApp(JupyterApp):
  455. """Base jupyter labextension command entry point"""
  456. name = "jupyter labextension"
  457. version = VERSION
  458. description = "Work with JupyterLab extensions"
  459. examples = _EXAMPLES
  460. subcommands = {
  461. "install": (InstallLabExtensionApp, "Install labextension(s)"),
  462. "update": (UpdateLabExtensionApp, "Update labextension(s)"),
  463. "uninstall": (UninstallLabExtensionApp, "Uninstall labextension(s)"),
  464. "list": (ListLabExtensionsApp, "List labextensions"),
  465. "link": (LinkLabExtensionApp, "Link labextension(s)"),
  466. "unlink": (UnlinkLabExtensionApp, "Unlink labextension(s)"),
  467. "enable": (EnableLabExtensionsApp, "Enable labextension(s)"),
  468. "disable": (DisableLabExtensionsApp, "Disable labextension(s)"),
  469. "lock": (LockLabExtensionsApp, "Lock labextension(s)"),
  470. "unlock": (UnlockLabExtensionsApp, "Unlock labextension(s)"),
  471. "check": (CheckLabExtensionsApp, "Check labextension(s)"),
  472. "develop": (DevelopLabExtensionApp, "(developer) Develop labextension(s)"),
  473. "build": (BuildLabExtensionApp, "(developer) Build labextension"),
  474. "watch": (WatchLabExtensionApp, "(developer) Watch labextension"),
  475. }
  476. def start(self):
  477. """Perform the App's functions as configured"""
  478. super().start()
  479. # The above should have called a subcommand and raised NoStart; if we
  480. # get here, it didn't, so we should self.log.info a message.
  481. subcmds = ", ".join(sorted(self.subcommands))
  482. self.exit(f"Please supply at least one subcommand: {subcmds}")
  483. main = LabExtensionApp.launch_instance
  484. if __name__ == "__main__":
  485. sys.exit(main())