1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
|
#!/usr/bin/env python3
import importlib
import logging
import os
import sys
from abc import ABC, abstractmethod
from getopt import getopt
import palhm
class ProgConf:
conf = "/etc/palhm/palhm.jsonc"
cmd = None
override_vl = None
ctx = None
def alloc_ctx ():
ProgConf.ctx = palhm.setup_conf(palhm.load_conf(ProgConf.conf))
if not ProgConf.override_vl is None:
ProgConf.ctx.l.setLevel(ProgConf.override_vl)
def err_unknown_cmd ():
sys.stderr.write("Unknown command. Run '" + sys.argv[0] + " help' for usage.\n")
exit(2)
class Cmd (ABC):
@abstractmethod
def do_cmd (self):
...
class ConfigCmd (Cmd):
def __init__ (self, *args, **kwargs):
pass
def do_cmd (self):
ProgConf.alloc_ctx()
print(ProgConf.ctx)
return 0
def print_help ():
print(
"Usage: " + sys.argv[0] + " config" + '''
Load and parse config. Print the structure to stdout.''')
class RunCmd (Cmd):
def __init__ (self, optlist, args):
self.optlist = optlist
self.args = args
def do_cmd (self):
ProgConf.alloc_ctx()
if self.args and self.args[0]: # empty string as "default"
task = self.args[0]
else:
task = palhm.DEFAULT.RUN_TASK.value
ProgConf.ctx.task_map[task].run(ProgConf.ctx)
return 0
def print_help ():
print(
"Usage: " + sys.argv[0] + " run [TASK]" + '''
Run a task in config. Run the "''' + palhm.DEFAULT.RUN_TASK.value +
'''" task if [TASK] is not specified.''')
class ModsCmd (Cmd):
def __init__ (self, *args, **kwargs):
pass
def _walk_mods (self, path: str):
def is_mod_dir (path: str) -> bool:
try:
for i in os.scandir(path):
if i.name.startswith("__init__.py"):
return True
except NotADirectoryError:
pass
return False
def is_mod_file (path: str) -> str:
if not os.path.isfile(path):
return None
try:
pos = path.rindex(".")
if path[pos + 1:].startswith("py"):
return os.path.basename(path[:pos])
except ValueError:
pass
for i in os.scandir(path):
if i.name.startswith("_"):
continue
elif is_mod_dir(i.path):
print(i.name)
self._walk_mods(i.path)
else:
name = is_mod_file(i.path)
if name:
print(name)
def do_cmd (self):
for i in importlib.util.find_spec("palhm.mod").submodule_search_locations:
self._walk_mods(i)
return 0
def print_help ():
print(
"Usage: " + sys.argv[0] + " mods" + '''
Prints the available modules to stdout.''')
class HelpCmd (Cmd):
def __init__ (self, optlist, args):
self.optlist = optlist
self.args = args
def do_cmd (self):
if len(self.args) >= 2:
if not args[0] in CmdMap:
err_unknown_cmd()
else:
CmdMap[self.args[0]].print_help()
else:
HelpCmd.print_help()
return 0
def print_help ():
print(
"Usage: " + sys.argv[0] + " [options] CMD [command options ...]" + '''
Options:
-q Set the verbosity level to 0(CRITIAL). Overrides config
-v Increase the verbosity level by 1. Overrides config
-f FILE Load config from FILE instead of the hard-coded default
Config: ''' + ProgConf.conf + '''
Commands:
run run a task
config load config and print the contents
help [CMD] print this message and exit normally if [CMD] is not specified.
Print usage of [CMD] otherwise
mods list available modules''')
return 0
CmdMap = {
"config": ConfigCmd,
"run": RunCmd,
"help": HelpCmd,
"mods": ModsCmd
}
optlist, args = getopt(sys.argv[1:], "qvf:")
optkset = set()
for p in optlist:
optkset.add(p[0])
if "-v" in optkset and "-q" in optkset:
sys.stderr.write("Options -v and -q cannot not used together.\n")
exit(2)
if not args or not args[0] in CmdMap:
err_unknown_cmd()
for p in optlist:
if p[0] == "-q": ProgConf.override_vl = logging.ERROR
elif p[0] == "-v":
if ProgConf.override_vl is None:
ProgConf.override_vl = palhm.DEFAULT.VL.value - 10
else:
ProgConf.override_vl -= 10
elif p[0] == "-f": ProgConf.conf = p[1]
logging.basicConfig(format = "%(name)s %(message)s")
ProgConf.cmd = CmdMap[args[0]](optlist, args)
del args[0]
exit(ProgConf.cmd.do_cmd())
|