Introducing LunaBuild to the build flow (#36)
[lunaix-os.git] / lunaix-os / scripts / build-tools / integration / config_io.py
1 from lcfg.api import ConfigIOProvider
2 from lcfg.utils import is_basic
3
4 import re
5
6 class CHeaderConfigProvider(ConfigIOProvider):
7     def __init__(self, header_save, 
8                  header_prefix="CONFIG_") -> None:
9         self.__header_export = header_save
10         self.__prefix = header_prefix
11         self.__re = re.compile(r"^[A-Za-z0-9_]+$")
12
13     def export(self, env, config_dict):
14         lines = []
15         for k, v in config_dict.items():
16             result = [ "#define" ]
17             s = str.upper(k)
18             s = f"{self.__prefix}{s}"
19
20             if isinstance(v, str) and self.__re.match(v):
21                 s = f"{s}_{str.upper(v)}"
22                 v = ""
23     
24             result.append(s)
25             
26             v = self.serialize_value(v)
27             if v is None or v is False:
28                 result.insert(0, "//")
29             else:
30                 result.append(v)
31
32             lines.append(" ".join(result))
33             
34         with open(self.__header_export, 'w') as f:
35             f.write("\n".join(lines))
36
37
38     def serialize_value(self, v):
39         if v is None:
40             return None
41         
42         if isinstance(v, bool):
43             return v
44         
45         if v and isinstance(v, str):
46             return f'"{v}"'
47         
48         if is_basic(v):
49             return str(v)
50         
51         raise ValueError(
52                 f"serialising {type(v)}: not supported")