manager.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. """Manager to read and modify frontend config data in JSON files."""
  2. # Copyright (c) Jupyter Development Team.
  3. # Distributed under the terms of the Modified BSD License.
  4. import os.path
  5. import typing as t
  6. from jupyter_core.paths import jupyter_config_dir, jupyter_config_path
  7. from traitlets import Instance, List, Unicode, default, observe
  8. from traitlets.config import LoggingConfigurable
  9. from jupyter_server.config_manager import BaseJSONConfigManager, recursive_update
  10. class ConfigManager(LoggingConfigurable):
  11. """Config Manager used for storing frontend config"""
  12. config_dir_name = Unicode("serverconfig", help="""Name of the config directory.""").tag(
  13. config=True
  14. )
  15. # Public API
  16. def get(self, section_name):
  17. """Get the config from all config sections."""
  18. config: dict[str, t.Any] = {}
  19. # step through back to front, to ensure front of the list is top priority
  20. for p in self.read_config_path[::-1]:
  21. cm = BaseJSONConfigManager(config_dir=p)
  22. recursive_update(config, cm.get(section_name))
  23. return config
  24. def set(self, section_name, data):
  25. """Set the config only to the user's config."""
  26. return self.write_config_manager.set(section_name, data)
  27. def update(self, section_name, new_data):
  28. """Update the config only to the user's config."""
  29. return self.write_config_manager.update(section_name, new_data)
  30. # Private API
  31. read_config_path = List(Unicode())
  32. @default("read_config_path")
  33. def _default_read_config_path(self):
  34. return [os.path.join(p, self.config_dir_name) for p in jupyter_config_path()]
  35. write_config_dir = Unicode()
  36. @default("write_config_dir")
  37. def _default_write_config_dir(self):
  38. return os.path.join(jupyter_config_dir(), self.config_dir_name)
  39. write_config_manager = Instance(BaseJSONConfigManager)
  40. @default("write_config_manager")
  41. def _default_write_config_manager(self):
  42. return BaseJSONConfigManager(config_dir=self.write_config_dir)
  43. @observe("write_config_dir")
  44. def _update_write_config_dir(self, change):
  45. self.write_config_manager = BaseJSONConfigManager(config_dir=self.write_config_dir)