5e7c9165e6cc6a49f6f9379db1b51da64abc311c
[lunaix-os.git] / lunaix-os / scripts / build-tools / shared / shconfig / main.py
1 import readline, textwrap
2
3 from rlcompleter    import Completer
4 from lcfg2.config   import ConfigEnvironment
5 from .common        import ShconfigException, get_config_name
6 from .commands      import Commands
7
8 class ConfigNameCompleter(Completer):
9     def __init__(self, env: ConfigEnvironment):
10         super().__init__(None)
11
12         self.__options = []
13         self.__config_set= [
14             get_config_name(x._name)
15             for x in env.terms()
16         ]
17
18     def complete(self, text, state):
19         if state == 0:
20             text = text if text else ""
21             self.__options = [
22                 x for x in self.__config_set if x.startswith(text)]
23         
24         return None if not self.__options else self.__options[state]
25
26
27 def next_input(cmds: Commands):
28     line = input("shconfig> ")
29
30     if len(line) == 0:
31         return True
32     
33     parts = line.split(' ')
34     name, args = parts[0], parts[1:]
35
36     if name in ['q', 'exit']:
37         return False
38     
39     if name == "q!":
40         raise KeyboardInterrupt()
41     
42     if name.startswith("CONFIG_"):
43         cmds.call("opt", name)
44         return True
45
46     cmds.call(name, *args)
47     return True
48
49 def shconfig(env: ConfigEnvironment):
50     print(
51         "\n",
52         textwrap.dedent(
53             
54             """
55             Lunaix Interactive Configurator (shconfig)
56             
57             Type "help" to see all commands avaliables
58             Type "q" or "exit" to confirm and exit
59             Type "q!" or use ^C to discard and abort
60
61             """
62         ).strip(), "\n")
63
64     cmds = Commands(env)
65     cmpleter = ConfigNameCompleter(env)
66     readline.parse_and_bind('tab: complete')
67     readline.set_completer(cmpleter.complete)
68
69     while True:
70         try:
71             if not next_input(cmds):
72                 return True
73         except ShconfigException as e:
74             print(str(e))
75             continue
76         except KeyboardInterrupt as e:
77             return False
78         except Exception as e:
79             raise e
80             return False