manager.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. """Manager to read and modify config data in JSON files.
  2. """
  3. # Copyright (c) IPython Development Team.
  4. # Distributed under the terms of the Modified BSD License.
  5. from __future__ import annotations
  6. import errno
  7. import json
  8. import os
  9. from typing import Any
  10. from traitlets.config import LoggingConfigurable
  11. from traitlets.traitlets import Unicode
  12. def recursive_update(target: dict[Any, Any], new: dict[Any, Any]) -> None:
  13. """Recursively update one dictionary using another.
  14. None values will delete their keys.
  15. """
  16. for k, v in new.items():
  17. if isinstance(v, dict):
  18. if k not in target:
  19. target[k] = {}
  20. recursive_update(target[k], v)
  21. if not target[k]:
  22. # Prune empty subdicts
  23. del target[k]
  24. elif v is None:
  25. target.pop(k, None)
  26. else:
  27. target[k] = v
  28. class BaseJSONConfigManager(LoggingConfigurable):
  29. """General JSON config manager
  30. Deals with persisting/storing config in a json file
  31. """
  32. config_dir = Unicode(".")
  33. def ensure_config_dir_exists(self) -> None:
  34. try:
  35. os.makedirs(self.config_dir, 0o755)
  36. except OSError as e:
  37. if e.errno != errno.EEXIST:
  38. raise
  39. def file_name(self, section_name: str) -> str:
  40. return os.path.join(self.config_dir, section_name + ".json")
  41. def get(self, section_name: str) -> Any:
  42. """Retrieve the config data for the specified section.
  43. Returns the data as a dictionary, or an empty dictionary if the file
  44. doesn't exist.
  45. """
  46. filename = self.file_name(section_name)
  47. if os.path.isfile(filename):
  48. with open(filename, encoding="utf-8") as f:
  49. return json.load(f)
  50. else:
  51. return {}
  52. def set(self, section_name: str, data: Any) -> None:
  53. """Store the given config data."""
  54. filename = self.file_name(section_name)
  55. self.ensure_config_dir_exists()
  56. with open(filename, "w", encoding="utf-8") as f:
  57. json.dump(data, f, indent=2)
  58. def update(self, section_name: str, new_data: Any) -> Any:
  59. """Modify the config section by recursively updating it with new_data.
  60. Returns the modified config data as a dictionary.
  61. """
  62. data = self.get(section_name)
  63. recursive_update(data, new_data)
  64. self.set(section_name, data)
  65. return data