Skip to content

Commit

Permalink
Develop command working (#11)
Browse files Browse the repository at this point in the history
* first commit

* Automatic application of license header

* federated_extensions dependencies

* develop

* Automatic application of license header

* develop working

* Automatic application of license header

* Update jupyter_builder/base_extension_app.py

Co-authored-by: Frédéric Collonval <fcollonval@gmail.com>

* Update jupyter_builder/base_extension_app.py

Co-authored-by: Frédéric Collonval <fcollonval@gmail.com>

* Update jupyter_builder/base_extension_app.py

Co-authored-by: Frédéric Collonval <fcollonval@gmail.com>

* Update jupyter_builder/commands.py

Co-authored-by: Frédéric Collonval <fcollonval@gmail.com>

* Update jupyter_builder/federated_extensions_requirements.py

Co-authored-by: Frédéric Collonval <fcollonval@gmail.com>

* Update jupyter_builder/commands.py

Co-authored-by: Frédéric Collonval <fcollonval@gmail.com>

* Update jupyter_builder/base_extension_app.py

Co-authored-by: Frédéric Collonval <fcollonval@gmail.com>

* Update jupyter_builder/base_extension_app.py

Co-authored-by: Frédéric Collonval <fcollonval@gmail.com>

* Update jupyter_builder/base_extension_app.py

Co-authored-by: Frédéric Collonval <fcollonval@gmail.com>

* Update jupyter_builder/base_extension_app.py

Co-authored-by: Frédéric Collonval <fcollonval@gmail.com>

* Update jupyter_builder/base_extension_app.py

Co-authored-by: Frédéric Collonval <fcollonval@gmail.com>

* Update jupyter_builder/base_extension_app.py

Co-authored-by: Frédéric Collonval <fcollonval@gmail.com>

* Update jupyter_builder/base_extension_app.py

Co-authored-by: Frédéric Collonval <fcollonval@gmail.com>

* Update jupyter_builder/base_extension_app.py

Co-authored-by: Frédéric Collonval <fcollonval@gmail.com>

* Update jupyter_builder/base_extension_app.py

Co-authored-by: Frédéric Collonval <fcollonval@gmail.com>

* tests

* test_tpl

* test_lint

---------

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
Co-authored-by: Frédéric Collonval <fcollonval@gmail.com>
  • Loading branch information
3 people authored Jun 11, 2024
1 parent ac7c1e0 commit 727dc28
Show file tree
Hide file tree
Showing 15 changed files with 1,349 additions and 2 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -159,3 +159,5 @@ cython_debug/
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
junit.xml

tests/dummy/
64 changes: 64 additions & 0 deletions jupyter_builder/base_extension_app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
"""Jupyter LabExtension Entry Points."""

# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.

import os
from copy import copy

from jupyter_core.application import JupyterApp, base_aliases, base_flags
from jupyter_core.paths import jupyter_path
from traitlets import List, Unicode, default

from .debug_log_file_mixin import DebugLogFileMixin

HERE = os.path.dirname(os.path.abspath(__file__))


# from .federated_labextensions import build_labextension, develop_labextension_py, watch_labextension

flags = dict(base_flags)

develop_flags = copy(flags)
develop_flags["overwrite"] = (
{"DevelopLabExtensionApp": {"overwrite": True}},
"Overwrite files",
)

aliases = dict(base_aliases)
aliases["debug-log-path"] = "DebugLogFileMixin.debug_log_path"

# VERSION = get_app_version()
VERSION = 1


class BaseExtensionApp(JupyterApp, DebugLogFileMixin):
version = VERSION
flags = flags
aliases = aliases
name = "lab"

labextensions_path = List(
Unicode(),
help="The standard paths to look in for prebuilt JupyterLab extensions",
)

# @default("labextensions_path")
# def _default_labextensions_path(self):
# lab = LabApp()
# lab.load_config_file()
# return lab.extra_labextensions_path + lab.labextensions_path
@default("labextensions_path")
def _default_labextensions_path(self) -> list[str]:
return jupyter_path("labextensions")

def start(self):
with self.debug_logging():
self.run_task()

def run_task(self):
pass

def _log_format_default(self):
"""A default format for messages"""
return "%(message)s"
115 changes: 115 additions & 0 deletions jupyter_builder/commands.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
"""JupyterLab command handler"""

# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.

import itertools

from .jupyterlab_semver import Range, gt, gte, lt, lte


def _test_overlap(spec1, spec2, drop_prerelease1=False, drop_prerelease2=False):
"""Test whether two version specs overlap.
Returns `None` if we cannot determine compatibility,
otherwise whether there is an overlap
"""
cmp = _compare_ranges(
spec1, spec2, drop_prerelease1=drop_prerelease1, drop_prerelease2=drop_prerelease2
)
if cmp is None:
return
return cmp == 0


def _compare_ranges(spec1, spec2, drop_prerelease1=False, drop_prerelease2=False): # noqa
"""Test whether two version specs overlap.
Returns `None` if we cannot determine compatibility,
otherwise return 0 if there is an overlap, 1 if
spec1 is lower/older than spec2, and -1 if spec1
is higher/newer than spec2.
"""
# Test for overlapping semver ranges.
r1 = Range(spec1, True)
r2 = Range(spec2, True)

# If either range is empty, we cannot verify.
if not r1.range or not r2.range:
return

# Set return_value to a sentinel value
return_value = False

# r1.set may be a list of ranges if the range involved an ||, so we need to test for overlaps between each pair.
for r1set, r2set in itertools.product(r1.set, r2.set):
x1 = r1set[0].semver
x2 = r1set[-1].semver
y1 = r2set[0].semver
y2 = r2set[-1].semver

if x1.prerelease and drop_prerelease1:
x1 = x1.inc("patch")

if y1.prerelease and drop_prerelease2:
y1 = y1.inc("patch")

o1 = r1set[0].operator
o2 = r2set[0].operator

# We do not handle (<) specifiers.
if o1.startswith("<") or o2.startswith("<"):
continue

# Handle single value specifiers.
lx = lte if x1 == x2 else lt
ly = lte if y1 == y2 else lt
gx = gte if x1 == x2 else gt
gy = gte if x1 == x2 else gt

# Handle unbounded (>) specifiers.
def noop(x, y, z):
return True

if x1 == x2 and o1.startswith(">"):
lx = noop
if y1 == y2 and o2.startswith(">"):
ly = noop

# Check for overlap.
if (
gte(x1, y1, True)
and ly(x1, y2, True)
or gy(x2, y1, True)
and ly(x2, y2, True)
or gte(y1, x1, True)
and lx(y1, x2, True)
or gx(y2, x1, True)
and lx(y2, x2, True)
):
# if we ever find an overlap, we can return immediately
return 0

if gte(y1, x2, True):
if return_value is False:
# We can possibly return 1
return_value = 1
elif return_value == -1:
# conflicting information, so we must return None
return_value = None
continue

if gte(x1, y2, True):
if return_value is False:
return_value = -1
elif return_value == 1:
# conflicting information, so we must return None
return_value = None
continue

msg = "Unexpected case comparing version ranges"
raise AssertionError(msg)

if return_value is False:
return_value = None
return return_value
64 changes: 64 additions & 0 deletions jupyter_builder/debug_log_file_mixin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.

import contextlib
import logging
import os
import sys
import tempfile
import traceback
import warnings

from traitlets import Unicode
from traitlets.config import Configurable


class DebugLogFileMixin(Configurable):
debug_log_path = Unicode("", config=True, help="Path to use for the debug log file")

@contextlib.contextmanager
def debug_logging(self):
log_path = self.debug_log_path
if os.path.isdir(log_path):
log_path = os.path.join(log_path, "jupyterlab-debug.log")
if not log_path:
handle, log_path = tempfile.mkstemp(prefix="jupyterlab-debug-", suffix=".log")
os.close(handle)
log = self.log

# Transfer current log level to the handlers:
for h in log.handlers:
h.setLevel(self.log_level)
log.setLevel("DEBUG")

# Create our debug-level file handler:
_debug_handler = logging.FileHandler(log_path, "w", "utf8", delay=True)
_log_formatter = self._log_formatter_cls(fmt=self.log_format, datefmt=self.log_datefmt)
_debug_handler.setFormatter(_log_formatter)
_debug_handler.setLevel("DEBUG")

log.addHandler(_debug_handler)

try:
yield
except Exception as ex:
_, _, exc_traceback = sys.exc_info()
msg = traceback.format_exception(ex.__class__, ex, exc_traceback)
for line in msg:
self.log.debug(line)
if isinstance(ex, SystemExit):
warnings.warn(f"An error occurred. See the log file for details: {log_path}")
raise
warnings.warn("An error occurred.")
warnings.warn(msg[-1].strip())
warnings.warn(f"See the log file for details: {log_path}")
self.exit(1)
else:
log.removeHandler(_debug_handler)
_debug_handler.flush()
_debug_handler.close()
try:
os.remove(log_path)
except FileNotFoundError:
pass
log.removeHandler(_debug_handler)
2 changes: 2 additions & 0 deletions jupyter_builder/extension_commands/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
55 changes: 55 additions & 0 deletions jupyter_builder/extension_commands/build.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.

import os

from traitlets import Bool, Unicode

from ..base_extension_app import BaseExtensionApp
from ..federated_extensions import build_labextension

HERE = os.path.dirname(os.path.abspath(__file__))


class BuildLabExtensionApp(BaseExtensionApp):
description = "(developer) Build labextension"

static_url = Unicode("", config=True, help="Sets the url for static assets when building")

development = Bool(False, config=True, help="Build in development mode")

source_map = Bool(False, config=True, help="Generate source maps")

core_path = Unicode(
os.path.join(HERE, "staging"),
config=True,
help="Directory containing core application package.json file",
)

aliases = {
"static-url": "BuildLabExtensionApp.static_url",
"development": "BuildLabExtensionApp.development",
"source-map": "BuildLabExtensionApp.source_map",
"core-path": "BuildLabExtensionApp.core_path",
}

def run_task(self):
self.extra_args = self.extra_args or [os.getcwd()]
build_labextension(
self.extra_args[0],
logger=self.log,
development=self.development,
static_url=self.static_url or None,
source_map=self.source_map,
core_path=self.core_path or None,
)


def main():
app = BuildLabExtensionApp()
app.initialize()
app.start()


if __name__ == "__main__":
main()
58 changes: 58 additions & 0 deletions jupyter_builder/extension_commands/develop.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.

import os
from copy import copy

from jupyter_core.application import base_flags
from traitlets import Bool, Unicode

from ..base_extension_app import BaseExtensionApp
from ..federated_extensions import develop_labextension_py

flags = dict(base_flags)
develop_flags = copy(flags)
develop_flags["overwrite"] = (
{"DevelopLabExtensionApp": {"overwrite": True}},
"Overwrite files",
)


class DevelopLabExtensionApp(BaseExtensionApp):
description = "(developer) Develop labextension"

flags = develop_flags
user = Bool(False, config=True, help="Whether to do a user install")
sys_prefix = Bool(True, config=True, help="Use the sys.prefix as the prefix")
overwrite = Bool(False, config=True, help="Whether to overwrite files") # flags
symlink = Bool(True, config=False, help="Whether to use a symlink")

labextensions_dir = Unicode(
"",
config=True,
help="Full path to labextensions dir (probably use prefix or user)",
)

def run_task(self):
"""Add config for this labextension"""
self.extra_args = self.extra_args or [os.getcwd()]
for arg in self.extra_args:
develop_labextension_py(
arg,
user=self.user,
sys_prefix=self.sys_prefix,
labextensions_dir=self.labextensions_dir,
logger=self.log,
overwrite=self.overwrite,
symlink=self.symlink,
)


def main():
app = DevelopLabExtensionApp()
app.initialize()
app.start()


if __name__ == "__main__":
main()
Loading

0 comments on commit 727dc28

Please sign in to comment.