Skip to content

Commit

Permalink
Simplify LabConfig
Browse files Browse the repository at this point in the history
and increase the coverage
  • Loading branch information
mwouts committed Nov 25, 2023
1 parent 1feace3 commit 48f0077
Show file tree
Hide file tree
Showing 4 changed files with 53 additions and 69 deletions.
9 changes: 2 additions & 7 deletions src/jupytext_config/jupytext_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,17 +23,12 @@ def main(self, args):
"""
return 0 if all goes well
"""
print(
f"{self.__class__.__name__}: redefine main() to implement this subcommand"
)
return 1
raise NotImplementedError() # pragma: no cover


class ListDefaultViewer(SubCommand):
def __init__(self):
super().__init__(
"list-default-viewer", "Display current settings in labconfig/"
)
super().__init__("list-default-viewer", "Display current settings in labconfig")

def main(self, args):
LabConfig(settings_file=args.settings_file).read().list_default_viewer()
Expand Down
76 changes: 22 additions & 54 deletions src/jupytext_config/labconfig.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,8 @@
notebook will cause jupyterlab to open it in an editor, i.e. as a text file
"""

import copy
import json
import logging

# import pprint
from pathlib import Path

DEFAULT_SETTINGS_FILE = (
Expand All @@ -28,38 +25,36 @@ class LabConfig:
"r",
]

def __init__(self, logger=None, settings_file=DEFAULT_SETTINGS_FILE):
def __init__(self, *, settings_file, logger=None):
self.settings_file = Path(settings_file)
self.logger = logger or logging.getLogger(__name__)
self.config = {}
# the state before any changes
self._prior_config = {}
self.settings_file = Path(settings_file)

def read(self):
"""
read the labconfig settings file
"""
try:
if self.settings_file.exists():
with self.settings_file.open() as fid:
self.config = json.load(fid)
except OSError as exc:
self.logger.error(f"Could not read {self.settings_file}", exc)
return False
# store for further comparison
self._prior_config = copy.deepcopy(self.config)
if self.settings_file.exists():
with self.settings_file.open() as fid:
self.config = json.load(fid)
else:
self.logger.info(f"Could not read from {self.settings_file} (not found)")

return self

def get_viewers(self):
return self.config.setdefault(
"@jupyterlab/docmanager-extension:plugin", {}
).setdefault("defaultViewers", {})

def list_default_viewer(self):
"""
list the current labconfig settings
"""
self.logger.debug(
f"Current @jupyterlab/docmanager-extension:plugin in {self.settings_file}"
)
docmanager = self.config.get("@jupyterlab/docmanager-extension:plugin", {})
viewers = docmanager.get("defaultViewers", {})
for key, value in viewers.items():
for key, value in self.get_viewers().items():
print(f"{key}: {value}")

def set_default_viewers(self, doctypes=None):
Expand All @@ -70,18 +65,7 @@ def set_default_viewers(self, doctypes=None):
return self

def set_default_viewer(self, doctype):
if "@jupyterlab/docmanager-extension:plugin" not in self.config:
self.config["@jupyterlab/docmanager-extension:plugin"] = {}
if (
"defaultViewers"
not in self.config["@jupyterlab/docmanager-extension:plugin"]
):
self.config["@jupyterlab/docmanager-extension:plugin"][
"defaultViewers"
] = {}
viewers = self.config["@jupyterlab/docmanager-extension:plugin"][
"defaultViewers"
]
viewers = self.get_viewers()
if doctype not in viewers:
viewers[doctype] = "Jupytext Notebook"

Expand All @@ -93,30 +77,14 @@ def unset_default_viewers(self, doctypes=None):
return self

def unset_default_viewer(self, doctype):
viewers = self.config.get("@jupyterlab/docmanager-extension:plugin", {}).get(
"defaultViewers", {}
)
if doctype not in viewers:
return
del viewers[doctype]
viewers = self.get_viewers()
if doctype in viewers:
del viewers[doctype]

def write(self) -> bool:
def write(self):
"""
write the labconfig settings file
"""
# compare - avoid changing the file if nothing changed
if self.config == self._prior_config:
self.logger.info(f"Nothing to do for {self.settings_file}")
return True

# save
try:
self.settings_file.parent.mkdir(parents=True, exist_ok=True)
with self.settings_file.open("w") as fid:
json.dump(self.config, fid, indent=2)
# useful in case of successive write's
self._prior_config = copy.deepcopy(self.config)
return True
except OSError as exc:
self.logger.error(f"Could not write {self.settings_file}", exc)
return False
self.settings_file.parent.mkdir(parents=True, exist_ok=True)
with self.settings_file.open("w") as fid:
json.dump(self.config, fid, indent=2)
12 changes: 12 additions & 0 deletions tests/integration/jupytext_config/test_jupytext_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,15 @@ def test_jupytext_config_cli(tmp_path):
assert "markdown" in system(
"jupytext-config", "--settings-file", settings_file, "list-default-viewer"
)
system(
"jupytext-config",
"--settings-file",
str(settings_file),
"unset-default-viewer",
"markdown",
)
list_viewers = system(
"jupytext-config", "--settings-file", settings_file, "list-default-viewer"
)
assert "python" in list_viewers
assert "markdown" not in list_viewers
25 changes: 17 additions & 8 deletions tests/unit/test_labconfig.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@


@pytest.fixture()
def sample_lab_config():
def sample_viewer_config():
return {
"@jupyterlab/docmanager-extension:plugin": {
"defaultViewers": {
Expand All @@ -22,25 +22,34 @@ def sample_lab_config():
}


@pytest.fixture()
def sample_empty_viewer_config():
return {"@jupyterlab/docmanager-extension:plugin": {"defaultViewers": {}}}


@pytest.fixture()
def settings_file(tmp_path):
return tmp_path / "default_setting_overrides.json"


def test_read_config(settings_file, sample_lab_config):
(settings_file).write_text(json.dumps(sample_lab_config))
def test_read_config(settings_file, sample_viewer_config):
(settings_file).write_text(json.dumps(sample_viewer_config))
labconfig = LabConfig(settings_file=settings_file).read()
assert labconfig.config == sample_lab_config
assert labconfig.config == sample_viewer_config


def test_set_default_viewers(settings_file, sample_lab_config):
def test_set_unset_default_viewers(
settings_file, sample_viewer_config, sample_empty_viewer_config
):
labconfig = LabConfig(settings_file=settings_file)
labconfig.set_default_viewers()
assert labconfig.config == sample_lab_config
assert labconfig.config == sample_viewer_config
labconfig.unset_default_viewers()
assert labconfig.config == sample_empty_viewer_config


def test_write_config(settings_file, sample_lab_config):
def test_write_config(settings_file, sample_viewer_config):
labconfig = LabConfig(settings_file=settings_file)
labconfig.set_default_viewers()
labconfig.write()
assert json.loads(settings_file.read_text()) == sample_lab_config
assert json.loads(settings_file.read_text()) == sample_viewer_config

0 comments on commit 48f0077

Please sign in to comment.