Rewrite the lunabuild toolchain with enhanced feature (#60)
[lunaix-os.git] / lunaix-os / scripts / build-tools / shared / build_gen.py
1 from os.path      import isdir, exists
2 from lbuild.build import BuildEnvironment
3 from lbuild.scope import ScopeAccessor
4
5 def gen_source_file(subscope : ScopeAccessor):
6     items = " ".join(subscope.values())
7     return [f"BUILD_SRCS := {items}"]
8
9 def gen_header_file(subscope : ScopeAccessor):
10     inc, hdr = [], []
11     for x in subscope.values():
12         if not exists(x):
13             print(f"warning: '{x}' does not exists, skipped")
14             continue
15
16         if isdir(x):
17             inc.append(x)
18         else:
19             hdr.append(x)
20             
21     return [
22         f"BUILD_INC := {' '.join(inc)}",
23         f"BUILD_HDR := {' '.join(hdr)}",
24     ]
25
26 def gen_ccflags(subscope : ScopeAccessor):
27     items = " ".join(subscope.values())
28     return [f"BUILD_CFLAGS := {items}"]
29
30 def gen_ldflags(subscope : ScopeAccessor):
31     items = " ".join(subscope.values())
32     return [f"BUILD_LDFLAGS := {items}"]
33
34
35 class BuildScriptGenerator:
36     def __init__(self, env: BuildEnvironment):
37         self.__gen_policy = {
38             "src": {
39                 "c": gen_source_file,
40                 "h": gen_header_file
41             },
42             "flag": {
43                 "cc": gen_ccflags,
44                 "ld": gen_ldflags
45             }
46         }
47
48         self.__env = env
49
50     def __gen_lines(self, scope, subscope):
51         
52         policy = self.__gen_policy.get(scope.name)
53         if policy is None:
54             print( "warning: no associated policy with"
55                   f"'{scope.name}'"
56                    ", skipped")
57             return []
58         
59         policy = policy.get(subscope.name)
60         if policy is None:
61             print( "warning: no associated policy with "
62                   f"'{scope.name}.{subscope.name}' "
63                    ", skipped")
64             return []
65         
66         return policy(subscope)
67     
68     def generate(self, file):
69         lines = []
70
71         for scope in self.__env.scopes.values():
72             for subscope in scope.accessors():
73                 lines += self.__gen_lines(scope, subscope)
74
75         with open(file, 'w') as f:
76             f.write('\n'.join(lines))
77