• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2024 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"""JSON config file loader mixin."""
15
16from typing import Any
17
18import json
19
20from pw_config_loader.yaml_config_loader_mixin import YamlConfigLoaderMixin
21
22
23class JsonConfigLoaderMixin(YamlConfigLoaderMixin):
24    """JSON Config file loader mixin.
25
26    Use this mixin to load json file settings and save them into
27    ``self._config``. For example:
28
29    ::
30
31       from pw_cli.json_config_loader_mixin import JsonConfigLoaderMixin
32
33       class PwBloatPrefs(JsonConfigLoaderMixin):
34           def __init__(self) -> None:
35               self.config_init(
36                   config_section_title='pw_bloat',
37                   project_file=Path('$PW_PROJECT_ROOT/.pw_bloat.json'),
38                   project_user_file=Path(
39                       '$PW_PROJECT_ROOT/.pw_bloat.user.json'),
40                   user_file=Path('~/.pw_bloat.json'),
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 [json.loads(file_contents)]
51