16
from dataclasses import asdict, dataclass, field
17
from typing import Union
21
from lightning.app.utilities.name_generator import get_unique_name
23
_APP_CONFIG_FILENAME = ".lightning"
28
"""The AppConfig holds configuration metadata for the application.
31
name: Optional name of the application. If not provided, auto-generates a new name.
35
name: str = field(default_factory=get_unique_name)
37
def save_to_file(self, path: Union[str, pathlib.Path]) -> None:
38
"""Save the configuration to the given file in YAML format."""
39
path = pathlib.Path(path)
40
with open(path, "w") as file:
41
yaml.dump(asdict(self), file)
43
def save_to_dir(self, directory: Union[str, pathlib.Path]) -> None:
44
"""Save the configuration to a file '.lightning' to the given folder in YAML format."""
45
self.save_to_file(_get_config_file(directory))
48
def load_from_file(cls, path: Union[str, pathlib.Path]) -> "AppConfig":
49
"""Load the configuration from the given file."""
50
with open(path) as file:
51
config = yaml.safe_load(file)
55
def load_from_dir(cls, directory: Union[str, pathlib.Path]) -> "AppConfig":
56
"""Load the configuration from the given folder.
59
directory: Path to a folder which contains the '.lightning' config file to load.
62
return cls.load_from_file(pathlib.Path(directory, _APP_CONFIG_FILENAME))
65
def _get_config_file(source_path: Union[str, pathlib.Path]) -> pathlib.Path:
66
"""Get the Lightning app config file '.lightning' at the given source path.
69
source_path: A path to a folder or a file.
72
source_path = pathlib.Path(source_path).absolute()
73
if source_path.is_file():
74
source_path = source_path.parent
76
return pathlib.Path(source_path / _APP_CONFIG_FILENAME)