xref: /aosp_15_r20/external/pigweed/pw_config_loader/py/pw_config_loader/toml_config_loader_mixin.py (revision 61c4878ac05f98d0ceed94b57d316916de578985)
1# Copyright 2022 The Pigweed Authors
2#
3# Licensed under the Apache License, Version 2.0 (the "License"); you may not
4# use this file except in compliance with the License. You may obtain a copy of
5# the License at
6#
7#     https://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12# License for the specific language governing permissions and limitations under
13# the License.
14"""Toml config file loader mixin."""
15
16from typing import Any
17
18import toml  # type: ignore
19
20from pw_config_loader.yaml_config_loader_mixin import YamlConfigLoaderMixin
21
22
23class TomlConfigLoaderMixin(YamlConfigLoaderMixin):
24    """TOML Config file loader mixin.
25
26    Use this mixin to load toml file settings and save them into
27    ``self._config``. For example:
28
29    ::
30
31       from pw_cli.toml_config_loader_mixin import TomlConfigLoaderMixin
32
33       class PwBloatPrefs(TomlConfigLoaderMixin):
34           def __init__(self) -> None:
35               self.config_init(
36                   config_section_title='pw_bloat',
37                   project_file=Path('$PW_PROJECT_ROOT/.pw_bloat.toml'),
38                   project_user_file=Path(
39                       '$PW_PROJECT_ROOT/.pw_bloat.user.toml'),
40                   user_file=Path('~/.pw_bloat.toml'),
41                   default_config={},
42                   environment_var='PW_BLOAT_CONFIG_FILE',
43               )
44
45    """
46
47    def _load_config_from_string(  # pylint: disable=no-self-use
48        self, file_contents: str
49    ) -> list[dict[Any, Any]]:
50        return [toml.loads(file_contents)]
51