1 # SPDX-License-Identifier: GPL-2.0
3 # Builds a .config from a kunitconfig.
5 # Copyright (C) 2019, Google LLC.
6 # Author: Felix Guo <felixguoxiuping@gmail.com>
7 # Author: Brendan Higgins <brendanhiggins@google.com>
9 from dataclasses import dataclass
11 from typing import List, Set
13 CONFIG_IS_NOT_SET_PATTERN = r'^# CONFIG_(\w+) is not set$'
14 CONFIG_PATTERN = r'^CONFIG_(\w+)=(\S+|".*")$'
16 @dataclass(frozen=True)
21 def __str__(self) -> str:
23 return f'# CONFIG_{self.name} is not set'
24 return f'CONFIG_{self.name}={self.value}'
27 class KconfigParseError(Exception):
28 """Error parsing Kconfig defconfig or .config."""
32 """Represents defconfig or .config specified using the Kconfig language."""
34 def __init__(self) -> None:
35 self._entries = [] # type: List[KconfigEntry]
37 def entries(self) -> Set[KconfigEntry]:
38 return set(self._entries)
40 def add_entry(self, entry: KconfigEntry) -> None:
41 self._entries.append(entry)
43 def is_subset_of(self, other: 'Kconfig') -> bool:
44 other_dict = {e.name: e.value for e in other.entries()}
45 for a in self.entries():
46 b = other_dict.get(a.name)
55 def merge_in_entries(self, other: 'Kconfig') -> None:
56 if other.is_subset_of(self):
58 self._entries = list(self.entries().union(other.entries()))
60 def write_to_file(self, path: str) -> None:
61 with open(path, 'a+') as f:
62 for entry in self.entries():
63 f.write(str(entry) + '\n')
65 def parse_file(path: str) -> Kconfig:
66 with open(path, 'r') as f:
67 return parse_from_string(f.read())
69 def parse_from_string(blob: str) -> Kconfig:
70 """Parses a string containing Kconfig entries."""
72 is_not_set_matcher = re.compile(CONFIG_IS_NOT_SET_PATTERN)
73 config_matcher = re.compile(CONFIG_PATTERN)
74 for line in blob.split('\n'):
79 match = config_matcher.match(line)
81 entry = KconfigEntry(match.group(1), match.group(2))
82 kconfig.add_entry(entry)
85 empty_match = is_not_set_matcher.match(line)
87 entry = KconfigEntry(empty_match.group(1), 'n')
88 kconfig.add_entry(entry)
93 raise KconfigParseError('Failed to parse: ' + line)