labextensions.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  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. from glob import glob
  6. import json
  7. import os
  8. import shutil
  9. import sys
  10. import traceback
  11. from copy import copy
  12. from jupyter_core.application import JupyterApp, base_flags, base_aliases
  13. from jupyter_core.paths import jupyter_path
  14. from jupyterlab.coreconfig import CoreConfig
  15. from jupyterlab.debuglog import DebugLogFileMixin
  16. from traitlets import Bool, Instance, List, Unicode, default
  17. from .commands import (
  18. install_extension, uninstall_extension, list_extensions,
  19. enable_extension, disable_extension, check_extension,
  20. link_package, unlink_package, build, get_app_version, HERE,
  21. update_extension, AppOptions,
  22. )
  23. from .federated_labextensions import develop_labextension_py, build_labextension, watch_labextension
  24. from .labapp import LabApp
  25. flags = dict(base_flags)
  26. flags['no-build'] = (
  27. {'BaseExtensionApp': {'should_build': False}},
  28. "Defer building the app after the action."
  29. )
  30. flags['dev-build'] = (
  31. {'BaseExtensionApp': {'dev_build': True}},
  32. "Build in development mode."
  33. )
  34. flags['no-minimize'] = (
  35. {'BaseExtensionApp': {'minimize': False}},
  36. "Do not minimize a production build."
  37. )
  38. flags['clean'] = (
  39. {'BaseExtensionApp': {'should_clean': True}},
  40. "Cleanup intermediate files after the action."
  41. )
  42. check_flags = copy(flags)
  43. check_flags['installed'] = (
  44. {'CheckLabExtensionsApp': {'should_check_installed_only': True}},
  45. "Check only if the extension is installed."
  46. )
  47. develop_flags = copy(flags)
  48. develop_flags['overwrite'] = (
  49. {'DevelopLabExtensionApp': {'overwrite': True}},
  50. "Overwrite files"
  51. )
  52. update_flags = copy(flags)
  53. update_flags['all'] = (
  54. {'UpdateLabExtensionApp': {'all': True}},
  55. "Update all extensions"
  56. )
  57. uninstall_flags = copy(flags)
  58. uninstall_flags['all'] = (
  59. {'UninstallLabExtensionApp': {'all': True}},
  60. "Uninstall all extensions"
  61. )
  62. aliases = dict(base_aliases)
  63. aliases['app-dir'] = 'BaseExtensionApp.app_dir'
  64. aliases['dev-build'] = 'BaseExtensionApp.dev_build'
  65. aliases['minimize'] = 'BaseExtensionApp.minimize'
  66. aliases['debug-log-path'] = 'DebugLogFileMixin.debug_log_path'
  67. install_aliases = copy(aliases)
  68. install_aliases['pin-version-as'] = 'InstallLabExtensionApp.pin'
  69. VERSION = get_app_version()
  70. class BaseExtensionApp(JupyterApp, DebugLogFileMixin):
  71. version = VERSION
  72. flags = flags
  73. aliases = aliases
  74. name = "lab"
  75. # Not configurable!
  76. core_config = Instance(CoreConfig, allow_none=True)
  77. app_dir = Unicode('', config=True,
  78. help="The app directory to target")
  79. should_build = Bool(True, config=True,
  80. help="Whether to build the app after the action")
  81. dev_build = Bool(None, allow_none=True, config=True,
  82. 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).")
  83. minimize = Bool(True, config=True,
  84. help="Whether to minimize a production build (defaults to True).")
  85. should_clean = Bool(False, config=True,
  86. help="Whether temporary files should be cleaned up after building jupyterlab")
  87. labextensions_path = List(Unicode(), help='The standard paths to look in for federated JupyterLab extensions')
  88. @default('labextensions_path')
  89. def _default_labextensions_path(self):
  90. lab = LabApp()
  91. lab.load_config_file()
  92. return lab.extra_labextensions_path + lab.labextensions_path
  93. def start(self):
  94. if self.app_dir and self.app_dir.startswith(HERE):
  95. raise ValueError('Cannot run lab extension commands in core app')
  96. with self.debug_logging():
  97. ans = self.run_task()
  98. if ans and self.should_build:
  99. production = None if self.dev_build is None else not self.dev_build
  100. app_options = AppOptions(app_dir=self.app_dir, logger=self.log,
  101. core_config=self.core_config)
  102. build(clean_staging=self.should_clean,
  103. production = production, minimize = self.minimize, app_options=app_options)
  104. def run_task(self):
  105. pass
  106. def _log_format_default(self):
  107. """A default format for messages"""
  108. return "%(message)s"
  109. class InstallLabExtensionApp(BaseExtensionApp):
  110. description = """Install labextension(s)
  111. Usage
  112. jupyter labextension install [--pin-version-as <alias,...>] <package...>
  113. This installs JupyterLab extensions similar to yarn add or npm install.
  114. Pass a list of comma seperate names to the --pin-version-as flag
  115. to use as alises for the packages providers. This is useful to
  116. install multiple versions of the same extension.
  117. These can be uninstalled with the alias you provided
  118. to the flag, similar to the "alias" feature of yarn add.
  119. """
  120. aliases = install_aliases
  121. pin = Unicode('', config=True,
  122. help="Pin this version with a certain alias")
  123. def run_task(self):
  124. pinned_versions = self.pin.split(',')
  125. self.extra_args = self.extra_args or [os.getcwd()]
  126. return any([
  127. install_extension(
  128. arg,
  129. # Pass in pinned alias if we have it
  130. pin=pinned_versions[i] if i < len(pinned_versions) else None,
  131. app_options=AppOptions(
  132. app_dir=self.app_dir,
  133. logger=self.log,
  134. core_config=self.core_config,
  135. labextensions_path=self.labextensions_path
  136. )
  137. )
  138. for i, arg in enumerate(self.extra_args)
  139. ])
  140. class DevelopLabExtensionApp(BaseExtensionApp):
  141. desciption = "Develop labextension"
  142. flags = develop_flags
  143. user = Bool(False, config=True, help="Whether to do a user install")
  144. sys_prefix = Bool(True, config=True, help="Use the sys.prefix as the prefix")
  145. overwrite = Bool(False, config=True, help="Whether to overwrite files")
  146. symlink = Bool(True, config=False, help="Whether to use a symlink")
  147. labextensions_dir = Unicode('', config=True,
  148. help="Full path to labextensions dir (probably use prefix or user)")
  149. def run_task(self):
  150. "Add config for this labextension"
  151. self.extra_args = self.extra_args or [os.getcwd()]
  152. for arg in self.extra_args:
  153. develop_labextension_py(arg, user=self.user, sys_prefix=self.sys_prefix, labextensions_dir=self.labextensions_dir, logger=self.log, overwrite=self.overwrite,
  154. symlink=self.symlink)
  155. class BuildLabExtensionApp(BaseExtensionApp):
  156. description = "Build labextension"
  157. static_url = Unicode('', config=True,
  158. help="Sets the url for static assets when building")
  159. development = Bool(False, config=True,
  160. help="Build in development mode")
  161. source_map = Bool(False, config=True,
  162. help="Generage source maps")
  163. aliases = {
  164. 'static-url': 'BuildLabExtensionApp.static_url',
  165. 'development': 'BuildLabExtensionApp.development',
  166. 'source-map': 'BuildLabExtensionApp.source_map'
  167. }
  168. def run_task(self):
  169. self.extra_args = self.extra_args or [os.getcwd()]
  170. build_labextension(self.extra_args[0], logger=self.log, development=self.development, static_url=self.static_url or None, source_map = self.source_map)
  171. class WatchLabExtensionApp(BaseExtensionApp):
  172. description = "Watch labextension"
  173. development = Bool(True, config=True,
  174. help="Build in development mode")
  175. source_map = Bool(False, config=True,
  176. help="Generage source maps")
  177. aliases = {
  178. 'development': 'BuildLabExtensionApp.development',
  179. 'source-map': 'BuildLabExtensionApp.source_map'
  180. }
  181. def run_task(self):
  182. self.extra_args = self.extra_args or [os.getcwd()]
  183. labextensions_path = self.labextensions_path
  184. watch_labextension(self.extra_args[0], labextensions_path, logger=self.log, development=self.development, source_map=self.source_map)
  185. class UpdateLabExtensionApp(BaseExtensionApp):
  186. description = "Update labextension(s)"
  187. flags = update_flags
  188. all = Bool(False, config=True,
  189. help="Whether to update all extensions")
  190. def run_task(self):
  191. if not self.all and not self.extra_args:
  192. self.log.warn('Specify an extension to update, or use --all to update all extensions')
  193. return False
  194. app_options = AppOptions(app_dir=self.app_dir, logger=self.log,
  195. core_config=self.core_config, labextensions_path=self.labextensions_path)
  196. if self.all:
  197. return update_extension(all_=True, app_options=app_options)
  198. return any([
  199. update_extension(name=arg, app_options=app_options)
  200. for arg in self.extra_args
  201. ])
  202. class LinkLabExtensionApp(BaseExtensionApp):
  203. description = """
  204. Link local npm packages that are not lab extensions.
  205. Links a package to the JupyterLab build process. A linked
  206. package is manually re-installed from its source location when
  207. `jupyter lab build` is run.
  208. """
  209. should_build = Bool(True, config=True,
  210. help="Whether to build the app after the action")
  211. def run_task(self):
  212. self.extra_args = self.extra_args or [os.getcwd()]
  213. options = AppOptions(
  214. app_dir=self.app_dir, logger=self.log,
  215. labextensions_path=self.labextensions_path,
  216. core_config=self.core_config)
  217. return any([
  218. link_package(
  219. arg,
  220. app_options=options)
  221. for arg in self.extra_args
  222. ])
  223. class UnlinkLabExtensionApp(BaseExtensionApp):
  224. description = "Unlink packages by name or path"
  225. def run_task(self):
  226. self.extra_args = self.extra_args or [os.getcwd()]
  227. options = AppOptions(
  228. app_dir=self.app_dir, logger=self.log,
  229. labextensions_path=self.labextensions_path,
  230. core_config=self.core_config)
  231. return any([
  232. unlink_package(
  233. arg,
  234. app_options=options)
  235. for arg in self.extra_args
  236. ])
  237. class UninstallLabExtensionApp(BaseExtensionApp):
  238. description = "Uninstall labextension(s) by name"
  239. flags = uninstall_flags
  240. all = Bool(False, config=True,
  241. help="Whether to uninstall all extensions")
  242. def run_task(self):
  243. self.extra_args = self.extra_args or [os.getcwd()]
  244. options = AppOptions(
  245. app_dir=self.app_dir, logger=self.log,
  246. labextensions_path=self.labextensions_path,
  247. core_config=self.core_config)
  248. return any([
  249. uninstall_extension(
  250. arg, all_=self.all,
  251. app_options=options)
  252. for arg in self.extra_args
  253. ])
  254. class ListLabExtensionsApp(BaseExtensionApp):
  255. description = "List the installed labextensions"
  256. def run_task(self):
  257. list_extensions(app_options=AppOptions(
  258. app_dir=self.app_dir, logger=self.log, core_config=self.core_config,
  259. labextensions_path=self.labextensions_path))
  260. class EnableLabExtensionsApp(BaseExtensionApp):
  261. description = "Enable labextension(s) by name"
  262. def run_task(self):
  263. app_options = AppOptions(
  264. app_dir=self.app_dir, logger=self.log, core_config=self.core_config,
  265. labextensions_path=self.labextensions_path)
  266. [enable_extension(arg, app_options=app_options) for arg in self.extra_args]
  267. class DisableLabExtensionsApp(BaseExtensionApp):
  268. description = "Disable labextension(s) by name"
  269. def run_task(self):
  270. app_options = AppOptions(
  271. app_dir=self.app_dir, logger=self.log, core_config=self.core_config,
  272. labextensions_path=self.labextensions_path)
  273. [disable_extension(arg, app_options=app_options) for arg in self.extra_args]
  274. class CheckLabExtensionsApp(BaseExtensionApp):
  275. description = "Check labextension(s) by name"
  276. flags = check_flags
  277. should_check_installed_only = Bool(False, config=True,
  278. help="Whether it should check only if the extensions is installed")
  279. def run_task(self):
  280. app_options = AppOptions(
  281. app_dir=self.app_dir, logger=self.log, core_config=self.core_config,
  282. labextensions_path=self.labextensions_path)
  283. all_enabled = all(
  284. check_extension(
  285. arg,
  286. installed=self.should_check_installed_only,
  287. app_options=app_options)
  288. for arg in self.extra_args)
  289. if not all_enabled:
  290. self.exit(1)
  291. _examples = """
  292. jupyter labextension list # list all configured labextensions
  293. jupyter labextension develop # develop a federated labextension
  294. jupyter labextension build # build a federated labextension
  295. jupyter labextension watch # watch a federated labextension
  296. jupyter labextension install <extension name> # install a labextension
  297. jupyter labextension uninstall <extension name> # uninstall a labextension
  298. """
  299. class LabExtensionApp(JupyterApp):
  300. """Base jupyter labextension command entry point"""
  301. name = "jupyter labextension"
  302. version = VERSION
  303. description = "Work with JupyterLab extensions"
  304. examples = _examples
  305. subcommands = dict(
  306. install=(InstallLabExtensionApp, "Install labextension(s)"),
  307. develop=(DevelopLabExtensionApp, "Develop labextension(s)"),
  308. build=(BuildLabExtensionApp, "Build labextension"),
  309. watch=(WatchLabExtensionApp, "Watch labextension"),
  310. update=(UpdateLabExtensionApp, "Update labextension(s)"),
  311. uninstall=(UninstallLabExtensionApp, "Uninstall labextension(s)"),
  312. list=(ListLabExtensionsApp, "List labextensions"),
  313. link=(LinkLabExtensionApp, "Link labextension(s)"),
  314. unlink=(UnlinkLabExtensionApp, "Unlink labextension(s)"),
  315. enable=(EnableLabExtensionsApp, "Enable labextension(s)"),
  316. disable=(DisableLabExtensionsApp, "Disable labextension(s)"),
  317. check=(CheckLabExtensionsApp, "Check labextension(s)"),
  318. )
  319. def start(self):
  320. """Perform the App's functions as configured"""
  321. super(LabExtensionApp, self).start()
  322. # The above should have called a subcommand and raised NoStart; if we
  323. # get here, it didn't, so we should self.log.info a message.
  324. subcmds = ", ".join(sorted(self.subcommands))
  325. self.exit("Please supply at least one subcommand: %s" % subcmds)
  326. main = LabExtensionApp.launch_instance
  327. if __name__ == '__main__':
  328. sys.exit(main())