labextensions.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. # coding: utf-8
  2. """Jupyter LabExtension Entry Points."""
  3. # Copyright (c) Jupyter Development Team.
  4. # Distributed under the terms of the Modified BSD License.
  5. import os
  6. import sys
  7. import traceback
  8. from copy import copy
  9. from jupyter_core.application import JupyterApp, base_flags, base_aliases
  10. from traitlets import Bool, Instance, Unicode
  11. from .commands import (
  12. install_extension, uninstall_extension, list_extensions,
  13. enable_extension, disable_extension, check_extension,
  14. link_package, unlink_package, build, get_app_version, HERE,
  15. update_extension, AppOptions,
  16. )
  17. from .coreconfig import CoreConfig
  18. from .debuglog import DebugLogFileMixin
  19. flags = dict(base_flags)
  20. flags['no-build'] = (
  21. {'BaseExtensionApp': {'should_build': False}},
  22. "Defer building the app after the action."
  23. )
  24. flags['clean'] = (
  25. {'BaseExtensionApp': {'should_clean': True}},
  26. "Cleanup intermediate files after the action."
  27. )
  28. check_flags = copy(flags)
  29. check_flags['installed'] = (
  30. {'CheckLabExtensionsApp': {'should_check_installed_only': True}},
  31. "Check only if the extension is installed."
  32. )
  33. update_flags = copy(flags)
  34. update_flags['all'] = (
  35. {'UpdateLabExtensionApp': {'all': True}},
  36. "Update all extensions"
  37. )
  38. uninstall_flags = copy(flags)
  39. uninstall_flags['all'] = (
  40. {'UninstallLabExtensionApp': {'all': True}},
  41. "Uninstall all extensions"
  42. )
  43. aliases = dict(base_aliases)
  44. aliases['app-dir'] = 'BaseExtensionApp.app_dir'
  45. aliases['dev-build'] = 'BaseExtensionApp.dev_build'
  46. aliases['minimize'] = 'BaseExtensionApp.minimize'
  47. aliases['debug-log-path'] = 'DebugLogFileMixin.debug_log_path'
  48. install_aliases = copy(aliases)
  49. install_aliases['pin-version-as'] = 'InstallLabExtensionApp.pin'
  50. VERSION = get_app_version()
  51. class BaseExtensionApp(JupyterApp, DebugLogFileMixin):
  52. version = VERSION
  53. flags = flags
  54. aliases = aliases
  55. # Not configurable!
  56. core_config = Instance(CoreConfig, allow_none=True)
  57. app_dir = Unicode('', config=True,
  58. help="The app directory to target")
  59. should_build = Bool(True, config=True,
  60. help="Whether to build the app after the action")
  61. dev_build = Bool(None, allow_none=True, config=True,
  62. help="Whether to build in dev mode. Defaults to True (dev mode) if there are any locally linked extensions, else defaults to False (prod mode).")
  63. minimize = Bool(True, config=True,
  64. help="Whether to use a minifier during the Webpack build (defaults to True). Only affects production builds.")
  65. should_clean = Bool(False, config=True,
  66. help="Whether temporary files should be cleaned up after building jupyterlab")
  67. def start(self):
  68. if self.app_dir and self.app_dir.startswith(HERE):
  69. raise ValueError('Cannot run lab extension commands in core app')
  70. with self.debug_logging():
  71. ans = self.run_task()
  72. if ans and self.should_build:
  73. parts = ['build']
  74. parts.append('none' if self.dev_build is None else
  75. 'dev' if self.dev_build else
  76. 'prod')
  77. if self.minimize:
  78. parts.append('minimize')
  79. command = ':'.join(parts)
  80. app_options = AppOptions(app_dir=self.app_dir, logger=self.log,
  81. core_config=self.core_config)
  82. build(clean_staging=self.should_clean,
  83. command=command, app_options=app_options)
  84. def run_task(self):
  85. pass
  86. def _log_format_default(self):
  87. """A default format for messages"""
  88. return "%(message)s"
  89. class InstallLabExtensionApp(BaseExtensionApp):
  90. description = """Install labextension(s)
  91. Usage
  92. jupyter labextension install [--pin-version-as <alias,...>] <package...>
  93. This installs JupyterLab extensions similar to yarn add or npm install.
  94. Pass a list of comma seperate names to the --pin-version-as flag
  95. to use as alises for the packages providers. This is useful to
  96. install multiple versions of the same extension.
  97. These can be uninstalled with the alias you provided
  98. to the flag, similar to the "alias" feature of yarn add.
  99. """
  100. aliases = install_aliases
  101. pin = Unicode('', config=True,
  102. help="Pin this version with a certain alias")
  103. def run_task(self):
  104. pinned_versions = self.pin.split(',')
  105. self.extra_args = self.extra_args or [os.getcwd()]
  106. return any([
  107. install_extension(
  108. arg,
  109. # Pass in pinned alias if we have it
  110. pin=pinned_versions[i] if i < len(pinned_versions) else None,
  111. app_options=AppOptions(
  112. app_dir=self.app_dir,
  113. logger=self.log,
  114. core_config=self.core_config,
  115. )
  116. )
  117. for i, arg in enumerate(self.extra_args)
  118. ])
  119. class UpdateLabExtensionApp(BaseExtensionApp):
  120. description = "Update labextension(s)"
  121. flags = update_flags
  122. all = Bool(False, config=True,
  123. help="Whether to update all extensions")
  124. def run_task(self):
  125. if not self.all and not self.extra_args:
  126. self.log.warn('Specify an extension to update, or use --all to update all extensions')
  127. return False
  128. app_options = AppOptions(app_dir=self.app_dir, logger=self.log,
  129. core_config=self.core_config)
  130. if self.all:
  131. return update_extension(all_=True, app_options=app_options)
  132. return any([
  133. update_extension(name=arg, app_options=app_options)
  134. for arg in self.extra_args
  135. ])
  136. class LinkLabExtensionApp(BaseExtensionApp):
  137. description = """
  138. Link local npm packages that are not lab extensions.
  139. Links a package to the JupyterLab build process. A linked
  140. package is manually re-installed from its source location when
  141. `jupyter lab build` is run.
  142. """
  143. should_build = Bool(True, config=True,
  144. help="Whether to build the app after the action")
  145. def run_task(self):
  146. self.extra_args = self.extra_args or [os.getcwd()]
  147. options = AppOptions(
  148. app_dir=self.app_dir, logger=self.log,
  149. core_config=self.core_config)
  150. return any([
  151. link_package(
  152. arg,
  153. app_options=options)
  154. for arg in self.extra_args
  155. ])
  156. class UnlinkLabExtensionApp(BaseExtensionApp):
  157. description = "Unlink packages by name or path"
  158. def run_task(self):
  159. self.extra_args = self.extra_args or [os.getcwd()]
  160. options = AppOptions(
  161. app_dir=self.app_dir, logger=self.log,
  162. core_config=self.core_config)
  163. return any([
  164. unlink_package(
  165. arg,
  166. app_options=options)
  167. for arg in self.extra_args
  168. ])
  169. class UninstallLabExtensionApp(BaseExtensionApp):
  170. description = "Uninstall labextension(s) by name"
  171. flags = uninstall_flags
  172. all = Bool(False, config=True,
  173. help="Whether to uninstall all extensions")
  174. def run_task(self):
  175. self.extra_args = self.extra_args or [os.getcwd()]
  176. options = AppOptions(
  177. app_dir=self.app_dir, logger=self.log,
  178. core_config=self.core_config)
  179. return any([
  180. uninstall_extension(
  181. arg, all_=self.all,
  182. app_options=options)
  183. for arg in self.extra_args
  184. ])
  185. class ListLabExtensionsApp(BaseExtensionApp):
  186. description = "List the installed labextensions"
  187. def run_task(self):
  188. list_extensions(app_options=AppOptions(
  189. app_dir=self.app_dir, logger=self.log, core_config=self.core_config))
  190. class EnableLabExtensionsApp(BaseExtensionApp):
  191. description = "Enable labextension(s) by name"
  192. def run_task(self):
  193. app_options = AppOptions(
  194. app_dir=self.app_dir, logger=self.log, core_config=self.core_config)
  195. [enable_extension(arg, app_options=app_options) for arg in self.extra_args]
  196. class DisableLabExtensionsApp(BaseExtensionApp):
  197. description = "Disable labextension(s) by name"
  198. def run_task(self):
  199. app_options = AppOptions(
  200. app_dir=self.app_dir, logger=self.log, core_config=self.core_config)
  201. [disable_extension(arg, app_options=app_options) for arg in self.extra_args]
  202. class CheckLabExtensionsApp(BaseExtensionApp):
  203. description = "Check labextension(s) by name"
  204. flags = check_flags
  205. should_check_installed_only = Bool(False, config=True,
  206. help="Whether it should check only if the extensions is installed")
  207. def run_task(self):
  208. app_options = AppOptions(
  209. app_dir=self.app_dir, logger=self.log, core_config=self.core_config)
  210. all_enabled = all(
  211. check_extension(
  212. arg,
  213. installed=self.should_check_installed_only,
  214. app_options=app_options)
  215. for arg in self.extra_args)
  216. if not all_enabled:
  217. self.exit(1)
  218. _examples = """
  219. jupyter labextension list # list all configured labextensions
  220. jupyter labextension install <extension name> # install a labextension
  221. jupyter labextension uninstall <extension name> # uninstall a labextension
  222. """
  223. class LabExtensionApp(JupyterApp):
  224. """Base jupyter labextension command entry point"""
  225. name = "jupyter labextension"
  226. version = VERSION
  227. description = "Work with JupyterLab extensions"
  228. examples = _examples
  229. subcommands = dict(
  230. install=(InstallLabExtensionApp, "Install labextension(s)"),
  231. update=(UpdateLabExtensionApp, "Update labextension(s)"),
  232. uninstall=(UninstallLabExtensionApp, "Uninstall labextension(s)"),
  233. list=(ListLabExtensionsApp, "List labextensions"),
  234. link=(LinkLabExtensionApp, "Link labextension(s)"),
  235. unlink=(UnlinkLabExtensionApp, "Unlink labextension(s)"),
  236. enable=(EnableLabExtensionsApp, "Enable labextension(s)"),
  237. disable=(DisableLabExtensionsApp, "Disable labextension(s)"),
  238. check=(CheckLabExtensionsApp, "Check labextension(s)"),
  239. )
  240. def start(self):
  241. """Perform the App's functions as configured"""
  242. super(LabExtensionApp, self).start()
  243. # The above should have called a subcommand and raised NoStart; if we
  244. # get here, it didn't, so we should self.log.info a message.
  245. subcmds = ", ".join(sorted(self.subcommands))
  246. self.exit("Please supply at least one subcommand: %s" % subcmds)
  247. main = LabExtensionApp.launch_instance
  248. if __name__ == '__main__':
  249. sys.exit(main())