You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1132 lines
40 KiB

4 years ago
  1. # coding: utf-8
  2. """Utilities for installing Javascript extensions for the notebook"""
  3. # Copyright (c) Jupyter Development Team.
  4. # Distributed under the terms of the Modified BSD License.
  5. from __future__ import print_function
  6. import os
  7. import shutil
  8. import sys
  9. import tarfile
  10. import zipfile
  11. from os.path import basename, join as pjoin, normpath
  12. try:
  13. from urllib.parse import urlparse # Py3
  14. from urllib.request import urlretrieve
  15. except ImportError:
  16. from urlparse import urlparse
  17. from urllib import urlretrieve
  18. from jupyter_core.paths import (
  19. jupyter_data_dir, jupyter_config_path, jupyter_path,
  20. SYSTEM_JUPYTER_PATH, ENV_JUPYTER_PATH,
  21. )
  22. from jupyter_core.utils import ensure_dir_exists
  23. from ipython_genutils.py3compat import string_types, cast_unicode_py2
  24. from ipython_genutils.tempdir import TemporaryDirectory
  25. from ._version import __version__
  26. from .config_manager import BaseJSONConfigManager
  27. from traitlets.utils.importstring import import_item
  28. DEPRECATED_ARGUMENT = object()
  29. NBCONFIG_SECTIONS = ['common', 'notebook', 'tree', 'edit', 'terminal']
  30. #------------------------------------------------------------------------------
  31. # Public API
  32. #------------------------------------------------------------------------------
  33. def check_nbextension(files, user=False, prefix=None, nbextensions_dir=None, sys_prefix=False):
  34. """Check whether nbextension files have been installed
  35. Returns True if all files are found, False if any are missing.
  36. Parameters
  37. ----------
  38. files : list(paths)
  39. a list of relative paths within nbextensions.
  40. user : bool [default: False]
  41. Whether to check the user's .jupyter/nbextensions directory.
  42. Otherwise check a system-wide install (e.g. /usr/local/share/jupyter/nbextensions).
  43. prefix : str [optional]
  44. Specify install prefix, if it should differ from default (e.g. /usr/local).
  45. Will check prefix/share/jupyter/nbextensions
  46. nbextensions_dir : str [optional]
  47. Specify absolute path of nbextensions directory explicitly.
  48. sys_prefix : bool [default: False]
  49. Install into the sys.prefix, i.e. environment
  50. """
  51. nbext = _get_nbextension_dir(user=user, sys_prefix=sys_prefix, prefix=prefix, nbextensions_dir=nbextensions_dir)
  52. # make sure nbextensions dir exists
  53. if not os.path.exists(nbext):
  54. return False
  55. if isinstance(files, string_types):
  56. # one file given, turn it into a list
  57. files = [files]
  58. return all(os.path.exists(pjoin(nbext, f)) for f in files)
  59. def install_nbextension(path, overwrite=False, symlink=False,
  60. user=False, prefix=None, nbextensions_dir=None,
  61. destination=None, verbose=DEPRECATED_ARGUMENT,
  62. logger=None, sys_prefix=False
  63. ):
  64. """Install a Javascript extension for the notebook
  65. Stages files and/or directories into the nbextensions directory.
  66. By default, this compares modification time, and only stages files that need updating.
  67. If `overwrite` is specified, matching files are purged before proceeding.
  68. Parameters
  69. ----------
  70. path : path to file, directory, zip or tarball archive, or URL to install
  71. By default, the file will be installed with its base name, so '/path/to/foo'
  72. will install to 'nbextensions/foo'. See the destination argument below to change this.
  73. Archives (zip or tarballs) will be extracted into the nbextensions directory.
  74. overwrite : bool [default: False]
  75. If True, always install the files, regardless of what may already be installed.
  76. symlink : bool [default: False]
  77. If True, create a symlink in nbextensions, rather than copying files.
  78. Not allowed with URLs or archives. Windows support for symlinks requires
  79. Vista or above, Python 3, and a permission bit which only admin users
  80. have by default, so don't rely on it.
  81. user : bool [default: False]
  82. Whether to install to the user's nbextensions directory.
  83. Otherwise do a system-wide install (e.g. /usr/local/share/jupyter/nbextensions).
  84. prefix : str [optional]
  85. Specify install prefix, if it should differ from default (e.g. /usr/local).
  86. Will install to ``<prefix>/share/jupyter/nbextensions``
  87. nbextensions_dir : str [optional]
  88. Specify absolute path of nbextensions directory explicitly.
  89. destination : str [optional]
  90. name the nbextension is installed to. For example, if destination is 'foo', then
  91. the source file will be installed to 'nbextensions/foo', regardless of the source name.
  92. This cannot be specified if an archive is given as the source.
  93. logger : Jupyter logger [optional]
  94. Logger instance to use
  95. """
  96. if verbose != DEPRECATED_ARGUMENT:
  97. import warnings
  98. warnings.warn("`install_nbextension`'s `verbose` parameter is deprecated, it will have no effects and will be removed in Notebook 5.0", DeprecationWarning)
  99. # the actual path to which we eventually installed
  100. full_dest = None
  101. nbext = _get_nbextension_dir(user=user, sys_prefix=sys_prefix, prefix=prefix, nbextensions_dir=nbextensions_dir)
  102. # make sure nbextensions dir exists
  103. ensure_dir_exists(nbext)
  104. # forcing symlink parameter to False if os.symlink does not exist (e.g., on Windows machines running python 2)
  105. if not hasattr(os, 'symlink'):
  106. symlink = False
  107. if isinstance(path, (list, tuple)):
  108. raise TypeError("path must be a string pointing to a single extension to install; call this function multiple times to install multiple extensions")
  109. path = cast_unicode_py2(path)
  110. if path.startswith(('https://', 'http://')):
  111. if symlink:
  112. raise ValueError("Cannot symlink from URLs")
  113. # Given a URL, download it
  114. with TemporaryDirectory() as td:
  115. filename = urlparse(path).path.split('/')[-1]
  116. local_path = os.path.join(td, filename)
  117. if logger:
  118. logger.info("Downloading: %s -> %s" % (path, local_path))
  119. urlretrieve(path, local_path)
  120. # now install from the local copy
  121. full_dest = install_nbextension(local_path, overwrite=overwrite, symlink=symlink,
  122. nbextensions_dir=nbext, destination=destination, logger=logger)
  123. elif path.endswith('.zip') or _safe_is_tarfile(path):
  124. if symlink:
  125. raise ValueError("Cannot symlink from archives")
  126. if destination:
  127. raise ValueError("Cannot give destination for archives")
  128. if logger:
  129. logger.info("Extracting: %s -> %s" % (path, nbext))
  130. if path.endswith('.zip'):
  131. archive = zipfile.ZipFile(path)
  132. elif _safe_is_tarfile(path):
  133. archive = tarfile.open(path)
  134. archive.extractall(nbext)
  135. archive.close()
  136. # TODO: what to do here
  137. full_dest = None
  138. else:
  139. if not destination:
  140. destination = basename(normpath(path))
  141. destination = cast_unicode_py2(destination)
  142. full_dest = normpath(pjoin(nbext, destination))
  143. if overwrite and os.path.lexists(full_dest):
  144. if logger:
  145. logger.info("Removing: %s" % full_dest)
  146. if os.path.isdir(full_dest) and not os.path.islink(full_dest):
  147. shutil.rmtree(full_dest)
  148. else:
  149. os.remove(full_dest)
  150. if symlink:
  151. path = os.path.abspath(path)
  152. if not os.path.exists(full_dest):
  153. if logger:
  154. logger.info("Symlinking: %s -> %s" % (full_dest, path))
  155. os.symlink(path, full_dest)
  156. elif os.path.isdir(path):
  157. path = pjoin(os.path.abspath(path), '') # end in path separator
  158. for parent, dirs, files in os.walk(path):
  159. dest_dir = pjoin(full_dest, parent[len(path):])
  160. if not os.path.exists(dest_dir):
  161. if logger:
  162. logger.info("Making directory: %s" % dest_dir)
  163. os.makedirs(dest_dir)
  164. for file_name in files:
  165. src = pjoin(parent, file_name)
  166. dest_file = pjoin(dest_dir, file_name)
  167. _maybe_copy(src, dest_file, logger=logger)
  168. else:
  169. src = path
  170. _maybe_copy(src, full_dest, logger=logger)
  171. return full_dest
  172. def install_nbextension_python(module, overwrite=False, symlink=False,
  173. user=False, sys_prefix=False, prefix=None, nbextensions_dir=None, logger=None):
  174. """Install an nbextension bundled in a Python package.
  175. Returns a list of installed/updated directories.
  176. See install_nbextension for parameter information."""
  177. m, nbexts = _get_nbextension_metadata(module)
  178. base_path = os.path.split(m.__file__)[0]
  179. full_dests = []
  180. for nbext in nbexts:
  181. src = os.path.join(base_path, nbext['src'])
  182. dest = nbext['dest']
  183. if logger:
  184. logger.info("Installing %s -> %s" % (src, dest))
  185. full_dest = install_nbextension(
  186. src, overwrite=overwrite, symlink=symlink,
  187. user=user, sys_prefix=sys_prefix, prefix=prefix, nbextensions_dir=nbextensions_dir,
  188. destination=dest, logger=logger
  189. )
  190. validate_nbextension_python(nbext, full_dest, logger)
  191. full_dests.append(full_dest)
  192. return full_dests
  193. def uninstall_nbextension(dest, require=None, user=False, sys_prefix=False, prefix=None,
  194. nbextensions_dir=None, logger=None):
  195. """Uninstall a Javascript extension of the notebook
  196. Removes staged files and/or directories in the nbextensions directory and
  197. removes the extension from the frontend config.
  198. Parameters
  199. ----------
  200. dest : str
  201. path to file, directory, zip or tarball archive, or URL to install
  202. name the nbextension is installed to. For example, if destination is 'foo', then
  203. the source file will be installed to 'nbextensions/foo', regardless of the source name.
  204. This cannot be specified if an archive is given as the source.
  205. require : str [optional]
  206. require.js path used to load the extension.
  207. If specified, frontend config loading extension will be removed.
  208. user : bool [default: False]
  209. Whether to install to the user's nbextensions directory.
  210. Otherwise do a system-wide install (e.g. /usr/local/share/jupyter/nbextensions).
  211. prefix : str [optional]
  212. Specify install prefix, if it should differ from default (e.g. /usr/local).
  213. Will install to ``<prefix>/share/jupyter/nbextensions``
  214. nbextensions_dir : str [optional]
  215. Specify absolute path of nbextensions directory explicitly.
  216. logger : Jupyter logger [optional]
  217. Logger instance to use
  218. """
  219. nbext = _get_nbextension_dir(user=user, sys_prefix=sys_prefix, prefix=prefix, nbextensions_dir=nbextensions_dir)
  220. dest = cast_unicode_py2(dest)
  221. full_dest = pjoin(nbext, dest)
  222. if os.path.lexists(full_dest):
  223. if logger:
  224. logger.info("Removing: %s" % full_dest)
  225. if os.path.isdir(full_dest) and not os.path.islink(full_dest):
  226. shutil.rmtree(full_dest)
  227. else:
  228. os.remove(full_dest)
  229. # Look through all of the config sections making sure that the nbextension
  230. # doesn't exist.
  231. config_dir = os.path.join(_get_config_dir(user=user, sys_prefix=sys_prefix), 'nbconfig')
  232. cm = BaseJSONConfigManager(config_dir=config_dir)
  233. if require:
  234. for section in NBCONFIG_SECTIONS:
  235. cm.update(section, {"load_extensions": {require: None}})
  236. def _find_uninstall_nbextension(filename, logger=None):
  237. """Remove nbextension files from the first location they are found.
  238. Returns True if files were removed, False otherwise.
  239. """
  240. filename = cast_unicode_py2(filename)
  241. for nbext in jupyter_path('nbextensions'):
  242. path = pjoin(nbext, filename)
  243. if os.path.lexists(path):
  244. if logger:
  245. logger.info("Removing: %s" % path)
  246. if os.path.isdir(path) and not os.path.islink(path):
  247. shutil.rmtree(path)
  248. else:
  249. os.remove(path)
  250. return True
  251. return False
  252. def uninstall_nbextension_python(module,
  253. user=False, sys_prefix=False, prefix=None, nbextensions_dir=None,
  254. logger=None):
  255. """Uninstall an nbextension bundled in a Python package.
  256. See parameters of `install_nbextension_python`
  257. """
  258. m, nbexts = _get_nbextension_metadata(module)
  259. for nbext in nbexts:
  260. dest = nbext['dest']
  261. require = nbext['require']
  262. if logger:
  263. logger.info("Uninstalling {} {}".format(dest, require))
  264. uninstall_nbextension(dest, require, user=user, sys_prefix=sys_prefix,
  265. prefix=prefix, nbextensions_dir=nbextensions_dir, logger=logger)
  266. def _set_nbextension_state(section, require, state,
  267. user=True, sys_prefix=False, logger=None):
  268. """Set whether the section's frontend should require the named nbextension
  269. Returns True if the final state is the one requested.
  270. Parameters
  271. ----------
  272. section : string
  273. The section of the server to change, one of NBCONFIG_SECTIONS
  274. require : string
  275. An importable AMD module inside the nbextensions static path
  276. state : bool
  277. The state in which to leave the extension
  278. user : bool [default: True]
  279. Whether to update the user's .jupyter/nbextensions directory
  280. sys_prefix : bool [default: False]
  281. Whether to update the sys.prefix, i.e. environment. Will override
  282. `user`.
  283. logger : Jupyter logger [optional]
  284. Logger instance to use
  285. """
  286. user = False if sys_prefix else user
  287. config_dir = os.path.join(
  288. _get_config_dir(user=user, sys_prefix=sys_prefix), 'nbconfig')
  289. cm = BaseJSONConfigManager(config_dir=config_dir)
  290. if logger:
  291. logger.info("{} {} extension {}...".format(
  292. "Enabling" if state else "Disabling",
  293. section,
  294. require
  295. ))
  296. cm.update(section, {"load_extensions": {require: state}})
  297. validate_nbextension(require, logger=logger)
  298. return cm.get(section).get(require) == state
  299. def _set_nbextension_state_python(state, module, user, sys_prefix,
  300. logger=None):
  301. """Enable or disable some nbextensions stored in a Python package
  302. Returns a list of whether the state was achieved (i.e. changed, or was
  303. already right)
  304. Parameters
  305. ----------
  306. state : Bool
  307. Whether the extensions should be enabled
  308. module : str
  309. Importable Python module exposing the
  310. magic-named `_jupyter_nbextension_paths` function
  311. user : bool
  312. Whether to enable in the user's nbextensions directory.
  313. sys_prefix : bool
  314. Enable/disable in the sys.prefix, i.e. environment
  315. logger : Jupyter logger [optional]
  316. Logger instance to use
  317. """
  318. m, nbexts = _get_nbextension_metadata(module)
  319. return [_set_nbextension_state(section=nbext["section"],
  320. require=nbext["require"],
  321. state=state,
  322. user=user, sys_prefix=sys_prefix,
  323. logger=logger)
  324. for nbext in nbexts]
  325. def enable_nbextension(section, require, user=True, sys_prefix=False,
  326. logger=None):
  327. """Enable a named nbextension
  328. Returns True if the final state is the one requested.
  329. Parameters
  330. ----------
  331. section : string
  332. The section of the server to change, one of NBCONFIG_SECTIONS
  333. require : string
  334. An importable AMD module inside the nbextensions static path
  335. user : bool [default: True]
  336. Whether to enable in the user's nbextensions directory.
  337. sys_prefix : bool [default: False]
  338. Whether to enable in the sys.prefix, i.e. environment. Will override
  339. `user`
  340. logger : Jupyter logger [optional]
  341. Logger instance to use
  342. """
  343. return _set_nbextension_state(section=section, require=require,
  344. state=True,
  345. user=user, sys_prefix=sys_prefix,
  346. logger=logger)
  347. def disable_nbextension(section, require, user=True, sys_prefix=False,
  348. logger=None):
  349. """Disable a named nbextension
  350. Returns True if the final state is the one requested.
  351. Parameters
  352. ----------
  353. section : string
  354. The section of the server to change, one of NBCONFIG_SECTIONS
  355. require : string
  356. An importable AMD module inside the nbextensions static path
  357. user : bool [default: True]
  358. Whether to enable in the user's nbextensions directory.
  359. sys_prefix : bool [default: False]
  360. Whether to enable in the sys.prefix, i.e. environment. Will override
  361. `user`.
  362. logger : Jupyter logger [optional]
  363. Logger instance to use
  364. """
  365. return _set_nbextension_state(section=section, require=require,
  366. state=False,
  367. user=user, sys_prefix=sys_prefix,
  368. logger=logger)
  369. def _find_disable_nbextension(section, require, logger=None):
  370. """Disable an nbextension from the first config location where it is enabled.
  371. Returns True if it changed any config, False otherwise.
  372. """
  373. for config_dir in jupyter_config_path():
  374. cm = BaseJSONConfigManager(
  375. config_dir=os.path.join(config_dir, 'nbconfig'))
  376. d = cm.get(section)
  377. if d.get('load_extensions', {}).get(require, None):
  378. if logger:
  379. logger.info("Disabling %s extension in %s", require, config_dir)
  380. cm.update(section, {'load_extensions': {require: None}})
  381. return True
  382. return False
  383. def enable_nbextension_python(module, user=True, sys_prefix=False,
  384. logger=None):
  385. """Enable some nbextensions associated with a Python module.
  386. Returns a list of whether the state was achieved (i.e. changed, or was
  387. already right)
  388. Parameters
  389. ----------
  390. module : str
  391. Importable Python module exposing the
  392. magic-named `_jupyter_nbextension_paths` function
  393. user : bool [default: True]
  394. Whether to enable in the user's nbextensions directory.
  395. sys_prefix : bool [default: False]
  396. Whether to enable in the sys.prefix, i.e. environment. Will override
  397. `user`
  398. logger : Jupyter logger [optional]
  399. Logger instance to use
  400. """
  401. return _set_nbextension_state_python(True, module, user, sys_prefix,
  402. logger=logger)
  403. def disable_nbextension_python(module, user=True, sys_prefix=False,
  404. logger=None):
  405. """Disable some nbextensions associated with a Python module.
  406. Returns True if the final state is the one requested.
  407. Parameters
  408. ----------
  409. module : str
  410. Importable Python module exposing the
  411. magic-named `_jupyter_nbextension_paths` function
  412. user : bool [default: True]
  413. Whether to enable in the user's nbextensions directory.
  414. sys_prefix : bool [default: False]
  415. Whether to enable in the sys.prefix, i.e. environment
  416. logger : Jupyter logger [optional]
  417. Logger instance to use
  418. """
  419. return _set_nbextension_state_python(False, module, user, sys_prefix,
  420. logger=logger)
  421. def validate_nbextension(require, logger=None):
  422. """Validate a named nbextension.
  423. Looks across all of the nbextension directories.
  424. Returns a list of warnings.
  425. require : str
  426. require.js path used to load the extension
  427. logger : Jupyter logger [optional]
  428. Logger instance to use
  429. """
  430. warnings = []
  431. infos = []
  432. js_exists = False
  433. for exts in jupyter_path('nbextensions'):
  434. # Does the Javascript entrypoint actually exist on disk?
  435. js = u"{}.js".format(os.path.join(exts, *require.split("/")))
  436. js_exists = os.path.exists(js)
  437. if js_exists:
  438. break
  439. require_tmpl = u" - require? {} {}"
  440. if js_exists:
  441. infos.append(require_tmpl.format(GREEN_OK, require))
  442. else:
  443. warnings.append(require_tmpl.format(RED_X, require))
  444. if logger:
  445. if warnings:
  446. logger.warning(u" - Validating: problems found:")
  447. for msg in warnings:
  448. logger.warning(msg)
  449. for msg in infos:
  450. logger.info(msg)
  451. else:
  452. logger.info(u" - Validating: {}".format(GREEN_OK))
  453. return warnings
  454. def validate_nbextension_python(spec, full_dest, logger=None):
  455. """Assess the health of an installed nbextension
  456. Returns a list of warnings.
  457. Parameters
  458. ----------
  459. spec : dict
  460. A single entry of _jupyter_nbextension_paths():
  461. [{
  462. 'section': 'notebook',
  463. 'src': 'mockextension',
  464. 'dest': '_mockdestination',
  465. 'require': '_mockdestination/index'
  466. }]
  467. full_dest : str
  468. The on-disk location of the installed nbextension: this should end
  469. with `nbextensions/<dest>`
  470. logger : Jupyter logger [optional]
  471. Logger instance to use
  472. """
  473. infos = []
  474. warnings = []
  475. section = spec.get("section", None)
  476. if section in NBCONFIG_SECTIONS:
  477. infos.append(u" {} section: {}".format(GREEN_OK, section))
  478. else:
  479. warnings.append(u" {} section: {}".format(RED_X, section))
  480. require = spec.get("require", None)
  481. if require is not None:
  482. require_path = os.path.join(
  483. full_dest[0:-len(spec["dest"])],
  484. u"{}.js".format(require))
  485. if os.path.exists(require_path):
  486. infos.append(u" {} require: {}".format(GREEN_OK, require_path))
  487. else:
  488. warnings.append(u" {} require: {}".format(RED_X, require_path))
  489. if logger:
  490. if warnings:
  491. logger.warning("- Validating: problems found:")
  492. for msg in warnings:
  493. logger.warning(msg)
  494. for msg in infos:
  495. logger.info(msg)
  496. logger.warning(u"Full spec: {}".format(spec))
  497. else:
  498. logger.info(u"- Validating: {}".format(GREEN_OK))
  499. return warnings
  500. #----------------------------------------------------------------------
  501. # Applications
  502. #----------------------------------------------------------------------
  503. from .extensions import (
  504. BaseExtensionApp, _get_config_dir, GREEN_ENABLED, RED_DISABLED, GREEN_OK, RED_X,
  505. ArgumentConflict, _base_aliases, _base_flags,
  506. )
  507. from traitlets import Bool, Unicode
  508. flags = {}
  509. flags.update(_base_flags)
  510. flags.update({
  511. "overwrite" : ({
  512. "InstallNBExtensionApp" : {
  513. "overwrite" : True,
  514. }}, "Force overwrite of existing files"
  515. ),
  516. "symlink" : ({
  517. "InstallNBExtensionApp" : {
  518. "symlink" : True,
  519. }}, "Create symlink instead of copying files"
  520. ),
  521. })
  522. flags['s'] = flags['symlink']
  523. aliases = {}
  524. aliases.update(_base_aliases)
  525. aliases.update({
  526. "prefix" : "InstallNBExtensionApp.prefix",
  527. "nbextensions" : "InstallNBExtensionApp.nbextensions_dir",
  528. "destination" : "InstallNBExtensionApp.destination",
  529. })
  530. class InstallNBExtensionApp(BaseExtensionApp):
  531. """Entry point for installing notebook extensions"""
  532. description = """Install Jupyter notebook extensions
  533. Usage
  534. jupyter nbextension install path|url [--user|--sys-prefix]
  535. This copies a file or a folder into the Jupyter nbextensions directory.
  536. If a URL is given, it will be downloaded.
  537. If an archive is given, it will be extracted into nbextensions.
  538. If the requested files are already up to date, no action is taken
  539. unless --overwrite is specified.
  540. """
  541. examples = """
  542. jupyter nbextension install /path/to/myextension
  543. """
  544. aliases = aliases
  545. flags = flags
  546. overwrite = Bool(False, config=True, help="Force overwrite of existing files")
  547. symlink = Bool(False, config=True, help="Create symlinks instead of copying files")
  548. prefix = Unicode('', config=True, help="Installation prefix")
  549. nbextensions_dir = Unicode('', config=True,
  550. help="Full path to nbextensions dir (probably use prefix or user)")
  551. destination = Unicode('', config=True, help="Destination for the copy or symlink")
  552. def _config_file_name_default(self):
  553. """The default config file name."""
  554. return 'jupyter_notebook_config'
  555. def install_extensions(self):
  556. """Perform the installation of nbextension(s)"""
  557. if len(self.extra_args)>1:
  558. raise ValueError("Only one nbextension allowed at a time. "
  559. "Call multiple times to install multiple extensions.")
  560. if self.python:
  561. install = install_nbextension_python
  562. kwargs = {}
  563. else:
  564. install = install_nbextension
  565. kwargs = {'destination': self.destination}
  566. full_dests = install(self.extra_args[0],
  567. overwrite=self.overwrite,
  568. symlink=self.symlink,
  569. user=self.user,
  570. sys_prefix=self.sys_prefix,
  571. prefix=self.prefix,
  572. nbextensions_dir=self.nbextensions_dir,
  573. logger=self.log,
  574. **kwargs
  575. )
  576. if full_dests:
  577. self.log.info(
  578. u"\nTo initialize this nbextension in the browser every time"
  579. " the notebook (or other app) loads:\n\n"
  580. " jupyter nbextension enable {}{}{}{}\n".format(
  581. self.extra_args[0] if self.python else "<the entry point>",
  582. " --user" if self.user else "",
  583. " --py" if self.python else "",
  584. " --sys-prefix" if self.sys_prefix else ""
  585. )
  586. )
  587. def start(self):
  588. """Perform the App's function as configured"""
  589. if not self.extra_args:
  590. sys.exit('Please specify an nbextension to install')
  591. else:
  592. try:
  593. self.install_extensions()
  594. except ArgumentConflict as e:
  595. sys.exit(str(e))
  596. class UninstallNBExtensionApp(BaseExtensionApp):
  597. """Entry point for uninstalling notebook extensions"""
  598. version = __version__
  599. description = """Uninstall Jupyter notebook extensions
  600. Usage
  601. jupyter nbextension uninstall path/url path/url/entrypoint
  602. jupyter nbextension uninstall --py pythonPackageName
  603. This uninstalls an nbextension. By default, it uninstalls from the
  604. first directory on the search path where it finds the extension, but you can
  605. uninstall from a specific location using the --user, --sys-prefix or
  606. --system flags, or the --prefix option.
  607. If you specify the --require option, the named extension will be disabled,
  608. e.g.::
  609. jupyter nbextension uninstall myext --require myext/main
  610. If you use the --py or --python flag, the name should be a Python module.
  611. It will uninstall nbextensions listed in that module, but not the module
  612. itself (which you should uninstall using a package manager such as pip).
  613. """
  614. examples = """
  615. jupyter nbextension uninstall dest/dir dest/dir/extensionjs
  616. jupyter nbextension uninstall --py extensionPyPackage
  617. """
  618. aliases = {
  619. "prefix" : "UninstallNBExtensionApp.prefix",
  620. "nbextensions" : "UninstallNBExtensionApp.nbextensions_dir",
  621. "require": "UninstallNBExtensionApp.require",
  622. }
  623. flags = BaseExtensionApp.flags.copy()
  624. flags['system'] = ({'UninstallNBExtensionApp': {'system': True}},
  625. "Uninstall specifically from systemwide installation directory")
  626. prefix = Unicode('', config=True,
  627. help="Installation prefix. Overrides --user, --sys-prefix and --system"
  628. )
  629. nbextensions_dir = Unicode('', config=True,
  630. help="Full path to nbextensions dir (probably use prefix or user)"
  631. )
  632. require = Unicode('', config=True, help="require.js module to disable loading")
  633. system = Bool(False, config=True,
  634. help="Uninstall specifically from systemwide installation directory"
  635. )
  636. def _config_file_name_default(self):
  637. """The default config file name."""
  638. return 'jupyter_notebook_config'
  639. def uninstall_extension(self):
  640. """Uninstall an nbextension from a specific location"""
  641. kwargs = {
  642. 'user': self.user,
  643. 'sys_prefix': self.sys_prefix,
  644. 'prefix': self.prefix,
  645. 'nbextensions_dir': self.nbextensions_dir,
  646. 'logger': self.log
  647. }
  648. if self.python:
  649. uninstall_nbextension_python(self.extra_args[0], **kwargs)
  650. else:
  651. if self.require:
  652. kwargs['require'] = self.require
  653. uninstall_nbextension(self.extra_args[0], **kwargs)
  654. def find_uninstall_extension(self):
  655. """Uninstall an nbextension from an unspecified location"""
  656. name = self.extra_args[0]
  657. if self.python:
  658. _, nbexts = _get_nbextension_metadata(name)
  659. changed = False
  660. for nbext in nbexts:
  661. if _find_uninstall_nbextension(nbext['dest'], logger=self.log):
  662. changed = True
  663. # Also disable it in config.
  664. for section in NBCONFIG_SECTIONS:
  665. _find_disable_nbextension(section, nbext['require'],
  666. logger=self.log)
  667. else:
  668. changed = _find_uninstall_nbextension(name, logger=self.log)
  669. if not changed:
  670. print("No installed extension %r found." % name)
  671. if self.require:
  672. for section in NBCONFIG_SECTIONS:
  673. _find_disable_nbextension(section, self.require,
  674. logger=self.log)
  675. def start(self):
  676. if not self.extra_args:
  677. sys.exit('Please specify an nbextension to uninstall')
  678. elif len(self.extra_args) > 1:
  679. sys.exit("Only one nbextension allowed at a time. "
  680. "Call multiple times to uninstall multiple extensions.")
  681. elif (self.user or self.sys_prefix or self.system or self.prefix
  682. or self.nbextensions_dir):
  683. # The user has specified a location from which to uninstall.
  684. try:
  685. self.uninstall_extension()
  686. except ArgumentConflict as e:
  687. sys.exit(str(e))
  688. else:
  689. # Uninstall wherever it is.
  690. self.find_uninstall_extension()
  691. class ToggleNBExtensionApp(BaseExtensionApp):
  692. """A base class for apps that enable/disable extensions"""
  693. name = "jupyter nbextension enable/disable"
  694. version = __version__
  695. description = "Enable/disable an nbextension in configuration."
  696. section = Unicode('notebook', config=True,
  697. help="""Which config section to add the extension to, 'common' will affect all pages."""
  698. )
  699. user = Bool(True, config=True, help="Apply the configuration only for the current user (default)")
  700. aliases = {'section': 'ToggleNBExtensionApp.section'}
  701. _toggle_value = None
  702. def _config_file_name_default(self):
  703. """The default config file name."""
  704. return 'jupyter_notebook_config'
  705. def toggle_nbextension_python(self, module):
  706. """Toggle some extensions in an importable Python module.
  707. Returns a list of booleans indicating whether the state was changed as
  708. requested.
  709. Parameters
  710. ----------
  711. module : str
  712. Importable Python module exposing the
  713. magic-named `_jupyter_nbextension_paths` function
  714. """
  715. toggle = (enable_nbextension_python if self._toggle_value
  716. else disable_nbextension_python)
  717. return toggle(module,
  718. user=self.user,
  719. sys_prefix=self.sys_prefix,
  720. logger=self.log)
  721. def toggle_nbextension(self, require):
  722. """Toggle some a named nbextension by require-able AMD module.
  723. Returns whether the state was changed as requested.
  724. Parameters
  725. ----------
  726. require : str
  727. require.js path used to load the nbextension
  728. """
  729. toggle = (enable_nbextension if self._toggle_value
  730. else disable_nbextension)
  731. return toggle(self.section, require,
  732. user=self.user, sys_prefix=self.sys_prefix,
  733. logger=self.log)
  734. def start(self):
  735. if not self.extra_args:
  736. sys.exit('Please specify an nbextension/package to enable or disable')
  737. elif len(self.extra_args) > 1:
  738. sys.exit('Please specify one nbextension/package at a time')
  739. if self.python:
  740. self.toggle_nbextension_python(self.extra_args[0])
  741. else:
  742. self.toggle_nbextension(self.extra_args[0])
  743. class EnableNBExtensionApp(ToggleNBExtensionApp):
  744. """An App that enables nbextensions"""
  745. name = "jupyter nbextension enable"
  746. description = """
  747. Enable an nbextension in frontend configuration.
  748. Usage
  749. jupyter nbextension enable [--system|--sys-prefix]
  750. """
  751. _toggle_value = True
  752. class DisableNBExtensionApp(ToggleNBExtensionApp):
  753. """An App that disables nbextensions"""
  754. name = "jupyter nbextension disable"
  755. description = """
  756. Disable an nbextension in frontend configuration.
  757. Usage
  758. jupyter nbextension disable [--system|--sys-prefix]
  759. """
  760. _toggle_value = None
  761. class ListNBExtensionsApp(BaseExtensionApp):
  762. """An App that lists and validates nbextensions"""
  763. name = "jupyter nbextension list"
  764. version = __version__
  765. description = "List all nbextensions known by the configuration system"
  766. def list_nbextensions(self):
  767. """List all the nbextensions"""
  768. config_dirs = [os.path.join(p, 'nbconfig') for p in jupyter_config_path()]
  769. print("Known nbextensions:")
  770. for config_dir in config_dirs:
  771. head = u' config dir: {}'.format(config_dir)
  772. head_shown = False
  773. cm = BaseJSONConfigManager(parent=self, config_dir=config_dir)
  774. for section in NBCONFIG_SECTIONS:
  775. data = cm.get(section)
  776. if 'load_extensions' in data:
  777. if not head_shown:
  778. # only show heading if there is an nbextension here
  779. print(head)
  780. head_shown = True
  781. print(u' {} section'.format(section))
  782. for require, enabled in data['load_extensions'].items():
  783. print(u' {} {}'.format(
  784. require,
  785. GREEN_ENABLED if enabled else RED_DISABLED))
  786. if enabled:
  787. validate_nbextension(require, logger=self.log)
  788. def start(self):
  789. """Perform the App's functions as configured"""
  790. self.list_nbextensions()
  791. _examples = """
  792. jupyter nbextension list # list all configured nbextensions
  793. jupyter nbextension install --py <packagename> # install an nbextension from a Python package
  794. jupyter nbextension enable --py <packagename> # enable all nbextensions in a Python package
  795. jupyter nbextension disable --py <packagename> # disable all nbextensions in a Python package
  796. jupyter nbextension uninstall --py <packagename> # uninstall an nbextension in a Python package
  797. """
  798. class NBExtensionApp(BaseExtensionApp):
  799. """Base jupyter nbextension command entry point"""
  800. name = "jupyter nbextension"
  801. version = __version__
  802. description = "Work with Jupyter notebook extensions"
  803. examples = _examples
  804. subcommands = dict(
  805. install=(InstallNBExtensionApp,"Install an nbextension"),
  806. enable=(EnableNBExtensionApp, "Enable an nbextension"),
  807. disable=(DisableNBExtensionApp, "Disable an nbextension"),
  808. uninstall=(UninstallNBExtensionApp, "Uninstall an nbextension"),
  809. list=(ListNBExtensionsApp, "List nbextensions")
  810. )
  811. def start(self):
  812. """Perform the App's functions as configured"""
  813. super(NBExtensionApp, self).start()
  814. # The above should have called a subcommand and raised NoStart; if we
  815. # get here, it didn't, so we should self.log.info a message.
  816. subcmds = ", ".join(sorted(self.subcommands))
  817. sys.exit("Please supply at least one subcommand: %s" % subcmds)
  818. main = NBExtensionApp.launch_instance
  819. #------------------------------------------------------------------------------
  820. # Private API
  821. #------------------------------------------------------------------------------
  822. def _should_copy(src, dest, logger=None):
  823. """Should a file be copied, if it doesn't exist, or is newer?
  824. Returns whether the file needs to be updated.
  825. Parameters
  826. ----------
  827. src : string
  828. A path that should exist from which to copy a file
  829. src : string
  830. A path that might exist to which to copy a file
  831. logger : Jupyter logger [optional]
  832. Logger instance to use
  833. """
  834. if not os.path.exists(dest):
  835. return True
  836. if os.stat(src).st_mtime - os.stat(dest).st_mtime > 1e-6:
  837. # we add a fudge factor to work around a bug in python 2.x
  838. # that was fixed in python 3.x: https://bugs.python.org/issue12904
  839. if logger:
  840. logger.warn("Out of date: %s" % dest)
  841. return True
  842. if logger:
  843. logger.info("Up to date: %s" % dest)
  844. return False
  845. def _maybe_copy(src, dest, logger=None):
  846. """Copy a file if it needs updating.
  847. Parameters
  848. ----------
  849. src : string
  850. A path that should exist from which to copy a file
  851. src : string
  852. A path that might exist to which to copy a file
  853. logger : Jupyter logger [optional]
  854. Logger instance to use
  855. """
  856. if _should_copy(src, dest, logger=logger):
  857. if logger:
  858. logger.info("Copying: %s -> %s" % (src, dest))
  859. shutil.copy2(src, dest)
  860. def _safe_is_tarfile(path):
  861. """Safe version of is_tarfile, return False on IOError.
  862. Returns whether the file exists and is a tarfile.
  863. Parameters
  864. ----------
  865. path : string
  866. A path that might not exist and or be a tarfile
  867. """
  868. try:
  869. return tarfile.is_tarfile(path)
  870. except IOError:
  871. return False
  872. def _get_nbextension_dir(user=False, sys_prefix=False, prefix=None, nbextensions_dir=None):
  873. """Return the nbextension directory specified
  874. Parameters
  875. ----------
  876. user : bool [default: False]
  877. Get the user's .jupyter/nbextensions directory
  878. sys_prefix : bool [default: False]
  879. Get sys.prefix, i.e. ~/.envs/my-env/share/jupyter/nbextensions
  880. prefix : str [optional]
  881. Get custom prefix
  882. nbextensions_dir : str [optional]
  883. Get what you put in
  884. """
  885. conflicting = [
  886. ('user', user),
  887. ('prefix', prefix),
  888. ('nbextensions_dir', nbextensions_dir),
  889. ('sys_prefix', sys_prefix),
  890. ]
  891. conflicting_set = ['{}={!r}'.format(n, v) for n, v in conflicting if v]
  892. if len(conflicting_set) > 1:
  893. raise ArgumentConflict(
  894. "cannot specify more than one of user, sys_prefix, prefix, or nbextensions_dir, but got: {}"
  895. .format(', '.join(conflicting_set)))
  896. if user:
  897. nbext = pjoin(jupyter_data_dir(), u'nbextensions')
  898. elif sys_prefix:
  899. nbext = pjoin(ENV_JUPYTER_PATH[0], u'nbextensions')
  900. elif prefix:
  901. nbext = pjoin(prefix, 'share', 'jupyter', 'nbextensions')
  902. elif nbextensions_dir:
  903. nbext = nbextensions_dir
  904. else:
  905. nbext = pjoin(SYSTEM_JUPYTER_PATH[0], 'nbextensions')
  906. return nbext
  907. def _get_nbextension_metadata(module):
  908. """Get the list of nbextension paths associated with a Python module.
  909. Returns a tuple of (the module, [{
  910. 'section': 'notebook',
  911. 'src': 'mockextension',
  912. 'dest': '_mockdestination',
  913. 'require': '_mockdestination/index'
  914. }])
  915. Parameters
  916. ----------
  917. module : str
  918. Importable Python module exposing the
  919. magic-named `_jupyter_nbextension_paths` function
  920. """
  921. m = import_item(module)
  922. if not hasattr(m, '_jupyter_nbextension_paths'):
  923. raise KeyError('The Python module {} is not a valid nbextension, '
  924. 'it is missing the `_jupyter_nbextension_paths()` method.'.format(module))
  925. nbexts = m._jupyter_nbextension_paths()
  926. return m, nbexts
  927. if __name__ == '__main__':
  928. main()