-
Notifications
You must be signed in to change notification settings - Fork 52
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Refactor the configuration parsing (#513)
* Refactor the configuration parsing As a part of #10774, this introduces a process to save the configuration in local, system and global configuration. The precedence of the level are as: - system - global - local Local configuration overrides global and so on. This borrows the logic of how configuration is managed in DVC. * Return toml document by default * Update some fixes * Fix init
- Loading branch information
1 parent
c6ca542
commit f29e034
Showing
5 changed files
with
155 additions
and
62 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,62 +1,131 @@ | ||
import os | ||
from collections.abc import Mapping | ||
from typing import TYPE_CHECKING, Optional | ||
from contextlib import contextmanager | ||
from typing import Optional, Union | ||
|
||
from tomlkit import load | ||
from tomlkit import TOMLDocument, dump, load | ||
|
||
if TYPE_CHECKING: | ||
from tomlkit import TOMLDocument | ||
from datachain.utils import DataChainDir, global_config_dir, system_config_dir | ||
|
||
|
||
def read_config(datachain_root: str) -> Optional["TOMLDocument"]: | ||
config_path = os.path.join(datachain_root, "config") | ||
try: | ||
with open(config_path, encoding="utf-8") as f: | ||
return load(f) | ||
except FileNotFoundError: | ||
return None | ||
class Config: | ||
SYSTEM_LEVELS = ("system", "global") | ||
LOCAL_LEVELS = ("local",) | ||
|
||
# In the order of precedence | ||
LEVELS = SYSTEM_LEVELS + LOCAL_LEVELS | ||
|
||
CONFIG = "config" | ||
|
||
def __init__( | ||
self, | ||
level: Optional[str] = None, | ||
): | ||
self.level = level | ||
|
||
self.init() | ||
|
||
@classmethod | ||
def get_dir(cls, level: Optional[str]) -> str: | ||
if level == "system": | ||
return system_config_dir() | ||
if level == "global": | ||
return global_config_dir() | ||
|
||
return DataChainDir.find().root | ||
|
||
def init(self): | ||
d = DataChainDir(self.get_dir(self.level)) | ||
d.init() | ||
|
||
def load_one(self, level: Optional[str] = None) -> TOMLDocument: | ||
config_path = DataChainDir(self.get_dir(level)).config | ||
|
||
def get_remote_config( | ||
config: Optional["TOMLDocument"], remote: str = "" | ||
) -> Mapping[str, str]: | ||
if config is None: | ||
return {"type": "local"} | ||
if not remote: | ||
try: | ||
remote = config["core"]["default-remote"] # type: ignore[index,assignment] | ||
except KeyError: | ||
with open(config_path, encoding="utf-8") as f: | ||
return load(f) | ||
except FileNotFoundError: | ||
return TOMLDocument() | ||
|
||
def load_config_to_level(self) -> TOMLDocument: | ||
merged_conf = TOMLDocument() | ||
|
||
for merge_level in self.LEVELS: | ||
if merge_level == self.level: | ||
break | ||
config = self.load_one(merge_level) | ||
if config: | ||
merge(merged_conf, config) | ||
|
||
return merged_conf | ||
|
||
def read(self) -> TOMLDocument: | ||
if self.level is None: | ||
return self.load_config_to_level() | ||
return self.load_one(self.level) | ||
|
||
@contextmanager | ||
def edit(self): | ||
config = self.load_one(self.level) | ||
yield config | ||
|
||
self.write(config) | ||
|
||
def config_file(self): | ||
return DataChainDir(self.get_dir(self.level)).config | ||
|
||
def write(self, config: TOMLDocument): | ||
with open(self.config_file(), "w") as f: | ||
dump(config, f) | ||
|
||
def get_remote_config(self, remote: str = "") -> Mapping[str, str]: | ||
config = self.read() | ||
|
||
if not config: | ||
return {"type": "local"} | ||
try: | ||
remote_conf: Mapping[str, str] = config["remote"][remote] # type: ignore[assignment,index] | ||
except KeyError: | ||
raise Exception( | ||
f"missing config section for default remote: remote.{remote}" | ||
) from None | ||
except Exception as exc: | ||
raise Exception("invalid config") from exc | ||
|
||
if not isinstance(remote_conf, Mapping): | ||
raise TypeError(f"config section remote.{remote} must be a mapping") | ||
|
||
remote_type = remote_conf.get("type") | ||
if remote_type not in ("local", "http"): | ||
raise Exception( | ||
f'config section remote.{remote} must have "type" with one of: ' | ||
'"local", "http"' | ||
) | ||
|
||
if remote_type == "http": | ||
for key in ["url", "username", "token"]: | ||
if not remote: | ||
try: | ||
remote_conf[key] | ||
remote = config["core"]["default-remote"] # type: ignore[index,assignment] | ||
except KeyError: | ||
raise Exception( | ||
f"config section remote.{remote} of type {remote_type} " | ||
f"must contain key {key}" | ||
) from None | ||
elif remote_type != "local": | ||
raise Exception( | ||
f"config section remote.{remote} has invalid remote type {remote_type}" | ||
) | ||
return remote_conf | ||
return {"type": "local"} | ||
try: | ||
remote_conf: Mapping[str, str] = config["remote"][remote] # type: ignore[assignment,index] | ||
except KeyError: | ||
raise Exception( | ||
f"missing config section for default remote: remote.{remote}" | ||
) from None | ||
except Exception as exc: | ||
raise Exception("invalid config") from exc | ||
|
||
if not isinstance(remote_conf, Mapping): | ||
raise TypeError(f"config section remote.{remote} must be a mapping") | ||
|
||
remote_type = remote_conf.get("type") | ||
if remote_type not in ("local", "http"): | ||
raise Exception( | ||
f'config section remote.{remote} must have "type" with one of: ' | ||
'"local", "http"' | ||
) | ||
|
||
if remote_type == "http": | ||
for key in ["url", "username", "token"]: | ||
try: | ||
remote_conf[key] | ||
except KeyError: | ||
raise Exception( | ||
f"config section remote.{remote} of type {remote_type} " | ||
f"must contain key {key}" | ||
) from None | ||
elif remote_type != "local": | ||
raise Exception( | ||
f"config section remote.{remote} has invalid remote type {remote_type}" | ||
) | ||
return remote_conf | ||
|
||
|
||
def merge(into: Union[TOMLDocument, dict], update: Union[TOMLDocument, dict]): | ||
"""Merges second dict into first recursively""" | ||
for key, val in update.items(): | ||
if isinstance(into.get(key), dict) and isinstance(val, dict): | ||
merge(into[key], val) # type: ignore[arg-type] | ||
else: | ||
into[key] = val |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters