federated_labextensions.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. """Utilities for installing Javascript extensions for the notebook"""
  2. # Copyright (c) Jupyter Development Team.
  3. # Distributed under the terms of the Modified BSD License.
  4. import importlib
  5. import json
  6. import os
  7. import os.path as osp
  8. import platform
  9. import shutil
  10. import subprocess
  11. import sys
  12. from pathlib import Path
  13. try:
  14. from importlib.metadata import PackageNotFoundError, version
  15. except ImportError:
  16. from importlib_metadata import PackageNotFoundError, version
  17. from os.path import basename, normpath
  18. from os.path import join as pjoin
  19. from jupyter_core.paths import ENV_JUPYTER_PATH, SYSTEM_JUPYTER_PATH, jupyter_data_dir
  20. from jupyter_core.utils import ensure_dir_exists
  21. from jupyter_server.extension.serverextension import ArgumentConflict
  22. from jupyterlab_server.config import get_federated_extensions
  23. try:
  24. from tomllib import load # Python 3.11+
  25. except ImportError:
  26. from tomli import load
  27. from .commands import _test_overlap
  28. DEPRECATED_ARGUMENT = object()
  29. HERE = osp.abspath(osp.dirname(__file__))
  30. # ------------------------------------------------------------------------------
  31. # Public API
  32. # ------------------------------------------------------------------------------
  33. def develop_labextension( # noqa
  34. path,
  35. symlink=True,
  36. overwrite=False,
  37. user=False,
  38. labextensions_dir=None,
  39. destination=None,
  40. logger=None,
  41. sys_prefix=False,
  42. ):
  43. """Install a prebuilt extension for JupyterLab
  44. Stages files and/or directories into the labextensions directory.
  45. By default, this compares modification time, and only stages files that need updating.
  46. If `overwrite` is specified, matching files are purged before proceeding.
  47. Parameters
  48. ----------
  49. path : path to file, directory, zip or tarball archive, or URL to install
  50. By default, the file will be installed with its base name, so '/path/to/foo'
  51. will install to 'labextensions/foo'. See the destination argument below to change this.
  52. Archives (zip or tarballs) will be extracted into the labextensions directory.
  53. user : bool [default: False]
  54. Whether to install to the user's labextensions directory.
  55. Otherwise do a system-wide install (e.g. /usr/local/share/jupyter/labextensions).
  56. overwrite : bool [default: False]
  57. If True, always install the files, regardless of what may already be installed.
  58. symlink : bool [default: True]
  59. If True, create a symlink in labextensions, rather than copying files.
  60. Windows support for symlinks requires a permission bit which only admin users
  61. have by default, so don't rely on it.
  62. labextensions_dir : str [optional]
  63. Specify absolute path of labextensions directory explicitly.
  64. destination : str [optional]
  65. name the labextension is installed to. For example, if destination is 'foo', then
  66. the source file will be installed to 'labextensions/foo', regardless of the source name.
  67. logger : Jupyter logger [optional]
  68. Logger instance to use
  69. """
  70. # the actual path to which we eventually installed
  71. full_dest = None
  72. labext = _get_labextension_dir(
  73. user=user, sys_prefix=sys_prefix, labextensions_dir=labextensions_dir
  74. )
  75. # make sure labextensions dir exists
  76. ensure_dir_exists(labext)
  77. if isinstance(path, (list, tuple)):
  78. msg = "path must be a string pointing to a single extension to install; call this function multiple times to install multiple extensions"
  79. raise TypeError(msg)
  80. if not destination:
  81. destination = basename(normpath(path))
  82. full_dest = normpath(pjoin(labext, destination))
  83. if overwrite and os.path.lexists(full_dest):
  84. if logger:
  85. logger.info(f"Removing: {full_dest}")
  86. if os.path.isdir(full_dest) and not os.path.islink(full_dest):
  87. shutil.rmtree(full_dest)
  88. else:
  89. os.remove(full_dest)
  90. # Make sure the parent directory exists
  91. os.makedirs(os.path.dirname(full_dest), exist_ok=True)
  92. if symlink:
  93. path = os.path.abspath(path)
  94. if not os.path.exists(full_dest):
  95. if logger:
  96. logger.info(f"Symlinking: {full_dest} -> {path}")
  97. try:
  98. os.symlink(path, full_dest)
  99. except OSError as e:
  100. if platform.platform().startswith("Windows"):
  101. msg = (
  102. "Symlinks can be activated on Windows 10 for Python version 3.8 or higher"
  103. " by activating the 'Developer Mode'. That may not be allowed by your administrators.\n"
  104. "See https://docs.microsoft.com/en-us/windows/apps/get-started/enable-your-device-for-development"
  105. )
  106. raise OSError(msg) from e
  107. raise
  108. elif not os.path.islink(full_dest):
  109. msg = f"{full_dest} exists and is not a symlink"
  110. raise ValueError(msg)
  111. elif os.path.isdir(path):
  112. path = pjoin(os.path.abspath(path), "") # end in path separator
  113. for parent, _, files in os.walk(path):
  114. dest_dir = pjoin(full_dest, parent[len(path) :])
  115. if not os.path.exists(dest_dir):
  116. if logger:
  117. logger.info(f"Making directory: {dest_dir}")
  118. os.makedirs(dest_dir)
  119. for file_name in files:
  120. src = pjoin(parent, file_name)
  121. dest_file = pjoin(dest_dir, file_name)
  122. _maybe_copy(src, dest_file, logger=logger)
  123. else:
  124. src = path
  125. _maybe_copy(src, full_dest, logger=logger)
  126. return full_dest
  127. def develop_labextension_py(
  128. module,
  129. user=False,
  130. sys_prefix=False,
  131. overwrite=True,
  132. symlink=True,
  133. labextensions_dir=None,
  134. logger=None,
  135. ):
  136. """Develop a labextension bundled in a Python package.
  137. Returns a list of installed/updated directories.
  138. See develop_labextension for parameter information."""
  139. m, labexts = _get_labextension_metadata(module)
  140. base_path = os.path.split(m.__file__)[0]
  141. full_dests = []
  142. for labext in labexts:
  143. src = os.path.join(base_path, labext["src"])
  144. dest = labext["dest"]
  145. if logger:
  146. logger.info(f"Installing {src} -> {dest}")
  147. if not os.path.exists(src):
  148. build_labextension(base_path, logger=logger)
  149. full_dest = develop_labextension(
  150. src,
  151. overwrite=overwrite,
  152. symlink=symlink,
  153. user=user,
  154. sys_prefix=sys_prefix,
  155. labextensions_dir=labextensions_dir,
  156. destination=dest,
  157. logger=logger,
  158. )
  159. full_dests.append(full_dest)
  160. return full_dests
  161. def build_labextension(
  162. path, logger=None, development=False, static_url=None, source_map=False, core_path=None
  163. ):
  164. """Build a labextension in the given path"""
  165. core_path = osp.join(HERE, "staging") if core_path is None else str(Path(core_path).resolve())
  166. ext_path = str(Path(path).resolve())
  167. if logger:
  168. logger.info(f"Building extension in {path}")
  169. builder = _ensure_builder(ext_path, core_path)
  170. arguments = ["node", builder, "--core-path", core_path, ext_path]
  171. if static_url is not None:
  172. arguments.extend(["--static-url", static_url])
  173. if development:
  174. arguments.append("--development")
  175. if source_map:
  176. arguments.append("--source-map")
  177. subprocess.check_call(arguments, cwd=ext_path) # noqa S603
  178. def watch_labextension(
  179. path, labextensions_path, logger=None, development=False, source_map=False, core_path=None
  180. ):
  181. """Watch a labextension in a given path"""
  182. core_path = osp.join(HERE, "staging") if core_path is None else str(Path(core_path).resolve())
  183. ext_path = str(Path(path).resolve())
  184. if logger:
  185. logger.info(f"Building extension in {path}")
  186. # Check to see if we need to create a symlink
  187. federated_extensions = get_federated_extensions(labextensions_path)
  188. with open(pjoin(ext_path, "package.json")) as fid:
  189. ext_data = json.load(fid)
  190. if ext_data["name"] not in federated_extensions:
  191. develop_labextension_py(ext_path, sys_prefix=True)
  192. else:
  193. full_dest = pjoin(federated_extensions[ext_data["name"]]["ext_dir"], ext_data["name"])
  194. output_dir = pjoin(ext_path, ext_data["jupyterlab"].get("outputDir", "static"))
  195. if not osp.islink(full_dest):
  196. shutil.rmtree(full_dest)
  197. os.symlink(output_dir, full_dest)
  198. builder = _ensure_builder(ext_path, core_path)
  199. arguments = ["node", builder, "--core-path", core_path, "--watch", ext_path]
  200. if development:
  201. arguments.append("--development")
  202. if source_map:
  203. arguments.append("--source-map")
  204. subprocess.check_call(arguments, cwd=ext_path) # noqa S603
  205. # ------------------------------------------------------------------------------
  206. # Private API
  207. # ------------------------------------------------------------------------------
  208. def _ensure_builder(ext_path, core_path):
  209. """Ensure that we can build the extension and return the builder script path"""
  210. # Test for compatible dependency on @jupyterlab/builder
  211. with open(osp.join(core_path, "package.json")) as fid:
  212. core_data = json.load(fid)
  213. with open(osp.join(ext_path, "package.json")) as fid:
  214. ext_data = json.load(fid)
  215. dep_version1 = core_data["devDependencies"]["@jupyterlab/builder"]
  216. dep_version2 = ext_data.get("devDependencies", {}).get("@jupyterlab/builder")
  217. dep_version2 = dep_version2 or ext_data.get("dependencies", {}).get("@jupyterlab/builder")
  218. if dep_version2 is None:
  219. msg = f"Extensions require a devDependency on @jupyterlab/builder@{dep_version1}"
  220. raise ValueError(msg)
  221. # if we have installed from disk (version is a path), assume we know what
  222. # we are doing and do not check versions.
  223. if "/" in dep_version2:
  224. with open(osp.join(ext_path, dep_version2, "package.json")) as fid:
  225. dep_version2 = json.load(fid).get("version")
  226. if not osp.exists(osp.join(ext_path, "node_modules")):
  227. subprocess.check_call(["jlpm"], cwd=ext_path) # noqa S603 S607
  228. # Find @jupyterlab/builder using node module resolution
  229. # We cannot use a script because the script path is a shell script on Windows
  230. target = ext_path
  231. while not osp.exists(osp.join(target, "node_modules", "@jupyterlab", "builder")):
  232. if osp.dirname(target) == target:
  233. msg = "Could not find @jupyterlab/builder"
  234. raise ValueError(msg)
  235. target = osp.dirname(target)
  236. overlap = _test_overlap(
  237. dep_version1, dep_version2, drop_prerelease1=True, drop_prerelease2=True
  238. )
  239. if not overlap:
  240. with open(
  241. osp.join(target, "node_modules", "@jupyterlab", "builder", "package.json")
  242. ) as fid:
  243. dep_version2 = json.load(fid).get("version")
  244. overlap = _test_overlap(
  245. dep_version1, dep_version2, drop_prerelease1=True, drop_prerelease2=True
  246. )
  247. if not overlap:
  248. msg = f"Extensions require a devDependency on @jupyterlab/builder@{dep_version1}, you have a dependency on {dep_version2}"
  249. raise ValueError(msg)
  250. return osp.join(
  251. target, "node_modules", "@jupyterlab", "builder", "lib", "build-labextension.js"
  252. )
  253. def _should_copy(src, dest, logger=None):
  254. """Should a file be copied, if it doesn't exist, or is newer?
  255. Returns whether the file needs to be updated.
  256. Parameters
  257. ----------
  258. src : string
  259. A path that should exist from which to copy a file
  260. src : string
  261. A path that might exist to which to copy a file
  262. logger : Jupyter logger [optional]
  263. Logger instance to use
  264. """
  265. if not os.path.exists(dest):
  266. return True
  267. if os.stat(src).st_mtime - os.stat(dest).st_mtime > 1e-6: # noqa
  268. # we add a fudge factor to work around a bug in python 2.x
  269. # that was fixed in python 3.x: https://bugs.python.org/issue12904
  270. if logger:
  271. logger.warning(f"Out of date: {dest}")
  272. return True
  273. if logger:
  274. logger.info(f"Up to date: {dest}")
  275. return False
  276. def _maybe_copy(src, dest, logger=None):
  277. """Copy a file if it needs updating.
  278. Parameters
  279. ----------
  280. src : string
  281. A path that should exist from which to copy a file
  282. src : string
  283. A path that might exist to which to copy a file
  284. logger : Jupyter logger [optional]
  285. Logger instance to use
  286. """
  287. if _should_copy(src, dest, logger=logger):
  288. if logger:
  289. logger.info(f"Copying: {src} -> {dest}")
  290. shutil.copy2(src, dest)
  291. def _get_labextension_dir(user=False, sys_prefix=False, prefix=None, labextensions_dir=None):
  292. """Return the labextension directory specified
  293. Parameters
  294. ----------
  295. user : bool [default: False]
  296. Get the user's .jupyter/labextensions directory
  297. sys_prefix : bool [default: False]
  298. Get sys.prefix, i.e. ~/.envs/my-env/share/jupyter/labextensions
  299. prefix : str [optional]
  300. Get custom prefix
  301. labextensions_dir : str [optional]
  302. Get what you put in
  303. """
  304. conflicting = [
  305. ("user", user),
  306. ("prefix", prefix),
  307. ("labextensions_dir", labextensions_dir),
  308. ("sys_prefix", sys_prefix),
  309. ]
  310. conflicting_set = [f"{n}={v!r}" for n, v in conflicting if v]
  311. if len(conflicting_set) > 1:
  312. msg = "cannot specify more than one of user, sys_prefix, prefix, or labextensions_dir, but got: {}".format(
  313. ", ".join(conflicting_set)
  314. )
  315. raise ArgumentConflict(msg)
  316. if user:
  317. labext = pjoin(jupyter_data_dir(), "labextensions")
  318. elif sys_prefix:
  319. labext = pjoin(ENV_JUPYTER_PATH[0], "labextensions")
  320. elif prefix:
  321. labext = pjoin(prefix, "share", "jupyter", "labextensions")
  322. elif labextensions_dir:
  323. labext = labextensions_dir
  324. else:
  325. labext = pjoin(SYSTEM_JUPYTER_PATH[0], "labextensions")
  326. return labext
  327. def _get_labextension_metadata(module): # noqa
  328. """Get the list of labextension paths associated with a Python module.
  329. Returns a tuple of (the module path, [{
  330. 'src': 'mockextension',
  331. 'dest': '_mockdestination'
  332. }])
  333. Parameters
  334. ----------
  335. module : str
  336. Importable Python module exposing the
  337. magic-named `_jupyter_labextension_paths` function
  338. """
  339. mod_path = osp.abspath(module)
  340. if not osp.exists(mod_path):
  341. msg = f"The path `{mod_path}` does not exist."
  342. raise FileNotFoundError(msg)
  343. errors = []
  344. # Check if the path is a valid labextension
  345. try:
  346. m = importlib.import_module(module)
  347. if hasattr(m, "_jupyter_labextension_paths"):
  348. return m, m._jupyter_labextension_paths()
  349. except Exception as exc:
  350. errors.append(exc)
  351. # Try to get the package name
  352. package = None
  353. # Try getting the package name from pyproject.toml
  354. if os.path.exists(os.path.join(mod_path, "pyproject.toml")):
  355. with open(os.path.join(mod_path, "pyproject.toml"), "rb") as fid:
  356. data = load(fid)
  357. package = data.get("project", {}).get("name")
  358. # Try getting the package name from setup.py
  359. if not package:
  360. try:
  361. package = (
  362. subprocess.check_output( # noqa S603
  363. [sys.executable, "setup.py", "--name"],
  364. cwd=mod_path,
  365. )
  366. .decode("utf8")
  367. .strip()
  368. )
  369. except subprocess.CalledProcessError:
  370. msg = (
  371. f"The Python package `{module}` is not a valid package, "
  372. "it is missing the `setup.py` file."
  373. )
  374. raise FileNotFoundError(msg) from None
  375. # Make sure the package is installed
  376. try:
  377. version(package)
  378. except PackageNotFoundError:
  379. subprocess.check_call([sys.executable, "-m", "pip", "install", "-e", mod_path]) # noqa S603
  380. sys.path.insert(0, mod_path)
  381. from setuptools import find_namespace_packages, find_packages
  382. package_candidates = [
  383. package.replace("-", "_"), # Module with the same name as package
  384. ]
  385. package_candidates.extend(find_packages(mod_path)) # Packages in the module path
  386. package_candidates.extend(
  387. find_namespace_packages(mod_path)
  388. ) # Namespace packages in the module path
  389. for package in package_candidates:
  390. try:
  391. m = importlib.import_module(package)
  392. if hasattr(m, "_jupyter_labextension_paths"):
  393. return m, m._jupyter_labextension_paths()
  394. except Exception as exc:
  395. errors.append(exc)
  396. msg = f"There is no labextension at {module}. Errors encountered: {errors}"
  397. raise ModuleNotFoundError(msg)