| 1 |
from typing import Iterable |
| 2 |
from collections import OrderedDict |
| 3 |
|
| 4 |
__all__ = ( |
| 5 |
"KconfigFile", |
| 6 |
) |
| 7 |
|
| 8 |
|
| 9 |
class KConfigEntry(object): |
| 10 |
__slots__ = 'name', 'value', 'comments' |
| 11 |
|
| 12 |
def __init__(self, name, value, comments=None) -> None: |
| 13 |
self.name, self.value = name, value |
| 14 |
self.comments = comments or [] |
| 15 |
|
| 16 |
def __eq__(self, other) -> bool: |
| 17 |
return self.name == other.name and self.value == other.value |
| 18 |
|
| 19 |
def __hash__(self) -> int: |
| 20 |
return hash(self.name) | hash(self.value) |
| 21 |
|
| 22 |
def __repr__(self) -> str: |
| 23 |
return ('<{}({!r}, {!r}, {!r})>' |
| 24 |
.format(self.__class__.__name__, self.name, self.value, |
| 25 |
self.comments)) |
| 26 |
|
| 27 |
def __str__(self) -> str: |
| 28 |
return 'CONFIG_{}={}'.format(self.name, self.value) |
| 29 |
|
| 30 |
def write(self) -> Iterable[str]: |
| 31 |
for comment in self.comments: |
| 32 |
yield '#. ' + comment |
| 33 |
yield str(self) |
| 34 |
|
| 35 |
|
| 36 |
class KConfigEntryTristate(KConfigEntry): |
| 37 |
__slots__ = () |
| 38 |
|
| 39 |
VALUE_NO = False |
| 40 |
VALUE_YES = True |
| 41 |
VALUE_MOD = object() |
| 42 |
|
| 43 |
def __init__(self, name, value, comments=None) -> None: |
| 44 |
if value == 'n' or value is None: |
| 45 |
value = self.VALUE_NO |
| 46 |
elif value == 'y': |
| 47 |
value = self.VALUE_YES |
| 48 |
elif value == 'm': |
| 49 |
value = self.VALUE_MOD |
| 50 |
else: |
| 51 |
raise NotImplementedError |
| 52 |
super(KConfigEntryTristate, self).__init__(name, value, comments) |
| 53 |
|
| 54 |
def __str__(self) -> str: |
| 55 |
if self.value is self.VALUE_MOD: |
| 56 |
return 'CONFIG_{}=m'.format(self.name) |
| 57 |
if self.value: |
| 58 |
return 'CONFIG_{}=y'.format(self.name) |
| 59 |
return '# CONFIG_{} is not set'.format(self.name) |
| 60 |
|
| 61 |
|
| 62 |
class KconfigFile(OrderedDict[str, KConfigEntry]): |
| 63 |
def __str__(self) -> str: |
| 64 |
ret = [] |
| 65 |
for i in self.str_iter(): |
| 66 |
ret.append(i) |
| 67 |
return '\n'.join(ret) + '\n' |
| 68 |
|
| 69 |
def read(self, f) -> None: |
| 70 |
for line in iter(f.readlines()): |
| 71 |
line = line.strip() |
| 72 |
if line.startswith("CONFIG_"): |
| 73 |
i = line.find('=') |
| 74 |
option = line[7:i] |
| 75 |
value = line[i + 1:] |
| 76 |
self.set(option, value) |
| 77 |
elif line.startswith("# CONFIG_"): |
| 78 |
option = line[9:-11] |
| 79 |
self.set(option, 'n') |
| 80 |
elif line.startswith("#") or not line: |
| 81 |
pass |
| 82 |
else: |
| 83 |
raise RuntimeError("Can't recognize %s" % line) |
| 84 |
|
| 85 |
def set(self, key, value) -> None: |
| 86 |
if value in ('y', 'm', 'n'): |
| 87 |
self[key] = KConfigEntryTristate(key, value) |
| 88 |
else: |
| 89 |
self[key] = KConfigEntry(key, value) |
| 90 |
|
| 91 |
def str_iter(self) -> Iterable[str]: |
| 92 |
for key, value in self.items(): |
| 93 |
yield str(value) |