Rewrite the lunabuild toolchain with enhanced feature (#60)
[lunaix-os.git] / lunaix-os / scripts / build-tools / lbuild / common.py
1 import ast
2 from pathlib import Path
3
4 class DirectoryTracker:
5     def __init__(self):
6         self.__stack = []
7
8     def push(self, dir):
9         self.__stack.append(Path(dir))
10
11     def pop(self):
12         self.__stack.pop()
13     
14     def active_relative(self):
15         root = self.__stack[0]
16         return self.__stack[-1].relative_to(root)
17
18     @staticmethod
19     def context_name():
20         return "__FILESTACK__"
21     
22     @staticmethod
23     def get(context):
24         return context[DirectoryTracker.context_name()]
25     
26     @staticmethod
27     def bind(context):
28         name = DirectoryTracker.context_name()
29         context[name] = DirectoryTracker()
30
31     @staticmethod
32     def emit_enter(dir):
33         name = DirectoryTracker.context_name()
34         return ast.Expr(
35                     ast.Call(
36                         func=ast.Attribute(
37                             value=ast.Name(name, ctx=ast.Load()),
38                             attr="push",
39                             ctx=ast.Load()
40                         ),
41                         args=[
42                             ast.Constant(str(dir))
43                         ],
44                         keywords=[]))
45
46     @staticmethod
47     def emit_leave():
48         name = DirectoryTracker.context_name()
49         return ast.Expr(
50                     ast.Call(
51                         func=ast.Attribute(
52                             value=ast.Name(name, ctx=ast.Load()),
53                             attr="pop",
54                             ctx=ast.Load()
55                         ),
56                         args=[],
57                         keywords=[]))