serverwatcher 6.dev1__py3-none-any.whl → 6.dev2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
serverwatcher/cli.py CHANGED
@@ -1,86 +1,214 @@
1
1
  import asyncio
2
- import argparse
3
2
  import cmd
4
3
  import sys
5
-
6
4
  import termios
7
5
  import tty
6
+ from dataclasses import dataclass
8
7
 
9
8
  from hungerlib import utils
10
9
  from mapres import res, maps, setGlobalMaps
11
-
12
10
  from .watcher import ServerWatcher
13
11
 
14
12
  setGlobalMaps(maps.ascii_colors)
15
13
 
14
+ # ARGUMENT PARSING ENGINE
15
+ COMMANDS: dict[str, callable] = {}
16
+
17
+
18
+ @dataclass
19
+ class ParsedArgs:
20
+ subcommand: str | None
21
+ positional: list[str]
22
+ flags: dict[str, bool]
23
+ params: dict[str, str]
24
+
25
+
26
+ def parse_line(raw: str) -> ParsedArgs:
27
+ raw = raw.strip()
28
+ if not raw:
29
+ return ParsedArgs(None, [], {}, {})
30
+
31
+ parts = raw.split()
32
+ sub = parts[0]
33
+ positional: list[str] = []
34
+ flags: dict[str, bool] = {}
35
+ params: dict[str, str] = {}
36
+
37
+ for token in parts[1:]:
38
+ if token.startswith('--'):
39
+ flags[token[2:]] = True
40
+ elif ':' in token:
41
+ key, value = token.split(':', 1)
42
+ params[key.lower()] = value
43
+ else:
44
+ positional.append(token)
45
+
46
+ return ParsedArgs(sub, positional, flags, params)
47
+
48
+
49
+ @dataclass
50
+ class ArgSpec:
51
+ name: str
52
+ kind: str # 'flag' or 'param'
53
+ type: callable = str
54
+ default: object = None
55
+ func: callable | None = None
56
+ present: bool = False
57
+ raw_value: str | None = None
58
+
59
+ def __call__(self):
60
+ if not self.present:
61
+ return self.default
62
+ if self.kind == 'flag':
63
+ return True
64
+ if self.raw_value is None:
65
+ return self.default
66
+ return self.type(self.raw_value)
67
+
68
+
69
+ class CommandContext:
70
+ def __init__(self, parsed: ParsedArgs):
71
+ self.parsed = parsed
72
+ self.arg_specs: dict[str, ArgSpec] = {}
73
+ self.child_name: str | None = None
74
+ self.child_func: callable | None = None
75
+
76
+ def register_param(self, name: str, type_: callable, default: object, func: callable) -> ArgSpec:
77
+ spec = ArgSpec(name=name, kind='param', type=type_, default=default, func=func)
78
+ self.arg_specs[name] = spec
79
+ return spec
80
+
81
+ def register_flag(self, name: str, func: callable) -> ArgSpec:
82
+ spec = ArgSpec(name=name, kind='flag', default=False, func=func)
83
+ self.arg_specs[name] = spec
84
+ return spec
85
+
86
+ def register_child(self, name: str, func: callable) -> callable:
87
+ self.child_name = name
88
+ self.child_func = func
89
+ return func
90
+
91
+ def bind(self) -> None:
92
+ for name, spec in self.arg_specs.items():
93
+ if spec.kind == 'flag' and name in self.parsed.flags:
94
+ spec.present = True
95
+
96
+ for name, spec in self.arg_specs.items():
97
+ if spec.kind == 'param' and name in self.parsed.params:
98
+ spec.present = True
99
+ spec.raw_value = self.parsed.params[name]
100
+
101
+ def positional(self, index: int, default: object = None) -> object:
102
+ try:
103
+ return self.parsed.positional[index]
104
+ except IndexError:
105
+ return default
106
+
107
+
108
+ # decorators
109
+ def command(name: str):
110
+ def decorator(func: callable):
111
+ COMMANDS[name] = func
112
+ return func
113
+ return decorator
114
+
115
+
116
+ def child(name: str):
117
+ def decorator(func: callable):
118
+ func.__child_name__ = name
119
+ return func
120
+ return decorator
121
+
16
122
 
123
+ def param(name: str, type: callable = str, default: object = None):
124
+ def decorator(func: callable):
125
+ func.__arg_kind__ = 'param'
126
+ func.__arg_name__ = name
127
+ func.__arg_type__ = type
128
+ func.__arg_default__ = default
129
+ return func
130
+ return decorator
131
+
132
+
133
+ def flag(name: str):
134
+ def decorator(func: callable):
135
+ func.__arg_kind__ = 'flag'
136
+ func.__arg_name__ = name
137
+ return func
138
+ return decorator
139
+
140
+
141
+ # DISPATCHER
142
+ class CLIBase:
143
+ def safePrint(self, msg: object = '', end: str = '\n') -> None:
144
+ print(str(msg), end=end)
145
+
146
+ def bprint(self, msg: object) -> None:
147
+ self.safePrint(msg)
148
+
149
+
150
+ def dispatch(cli: CLIBase, line: str):
151
+ parsed = parse_line(line)
152
+ if not parsed.subcommand:
153
+ return
154
+
155
+ handler = COMMANDS.get(parsed.subcommand)
156
+ if handler is None:
157
+ cli.safePrint(f'Unknown command \'{parsed.subcommand}\'')
158
+ return
159
+
160
+ ctx = CommandContext(parsed)
161
+
162
+ # Register decorators
163
+ handler(cli, ctx)
164
+
165
+ # Bind parsed values
166
+ ctx.bind()
167
+
168
+ # Execute child command
169
+ if ctx.child_func:
170
+ stat = ctx.positional(0)
171
+ return ctx.child_func(stat)
172
+
173
+
174
+ # CLI Implementation
17
175
  class BufferingStdout:
18
176
  def __init__(self, buffer, real_stdout):
19
177
  self.buffer = buffer
20
178
  self.real_stdout = real_stdout
21
179
 
22
- def write(self, text):
23
- # capture only non-empty lines
180
+ def write(self, text: str) -> None:
24
181
  if self.buffer.enabled and text.strip():
25
182
  self.buffer.captured.append(text.rstrip('\n'))
26
183
  self.real_stdout.write(text)
27
184
 
28
- def flush(self):
185
+ def flush(self) -> None:
29
186
  self.real_stdout.flush()
30
187
 
31
188
 
32
- stats_parser = argparse.ArgumentParser(add_help=False)
33
- stats_parser.add_argument(
34
- 'stat',
35
- choices=['cpu', 'ram', 'uptime', 'tps', 'players'],
36
- help='Statistic to retrieve'
37
- )
38
-
39
- schedule_parser = argparse.ArgumentParser()
40
- schedule_parser.add_argument(
41
- 'minutes',
42
- type=int,
43
- help='Minutes until restart'
44
- )
45
-
46
-
47
- class WatcherCLI(cmd.Cmd):
189
+ class WatcherCLI(cmd.Cmd, CLIBase):
48
190
  prompt = ''
49
191
 
50
192
  def __init__(self, watcher: ServerWatcher):
51
193
  self.watcher = watcher
52
-
53
- # buffer for CLI output
54
194
  self.buffer = utils.Buffer(enabled=True)
55
-
56
- # real stdout (terminal)
57
195
  self.real_stdout = sys.stdout
58
-
59
- # CLI stdout goes through BufferingStdout → captured in self.buffer
60
196
  self.cli_stdout = BufferingStdout(self.buffer, self.real_stdout)
61
-
62
- # permanently override cmd.Cmd stdout
63
197
  super().__init__(stdout=self.cli_stdout)
64
-
65
- # output mode: both | cli | silent
66
198
  self.outputMode = 'both'
67
-
68
- # disable rawinput in order to control input manually
69
199
  self.use_rawinput = False
70
200
 
71
- def read_line_raw(self):
201
+ def read_line_raw(self) -> str:
72
202
  fd = sys.stdin.fileno()
73
203
  old = termios.tcgetattr(fd)
74
-
75
204
  try:
76
205
  tty.setraw(fd)
77
- chars = []
206
+ chars: list[str] = []
78
207
  while True:
79
208
  ch = sys.stdin.read(1)
80
209
  if ch in ('\r', '\n'):
81
210
  break
82
211
  chars.append(ch)
83
-
84
212
  return ''.join(chars)
85
213
  finally:
86
214
  termios.tcsetattr(fd, termios.TCSADRAIN, old)
@@ -92,7 +220,7 @@ class WatcherCLI(cmd.Cmd):
92
220
  line = line.strip()
93
221
  if not line:
94
222
  continue
95
- if self.buffer.enabled and not line.startswith("view"):
223
+ if self.buffer.enabled and not line.startswith('view'):
96
224
  self.buffer.captured.append(line)
97
225
  stop = await asyncio.to_thread(self.onecmd, line)
98
226
  if stop:
@@ -104,201 +232,154 @@ class WatcherCLI(cmd.Cmd):
104
232
  else:
105
233
  raise
106
234
 
107
- def safePrint(self, msg='', end='\n'):
108
- self.real_stdout.write(str(msg) + end)
109
- self.real_stdout.flush()
110
-
111
- def printHeader(self):
235
+ def onecmd(self, line: str):
236
+ return dispatch(self, line)
237
+
238
+ def printHeader(self) -> None:
112
239
  self.safePrint(res('<yellow>-----------------------------------'))
113
240
  self.safePrint(res('<yellow>-------- <aqua>ServerWatcher CLI <yellow>--------'))
114
241
  self.safePrint(res('<yellow>-----------------------------------'))
115
242
  self.safePrint('\n')
116
243
 
117
- # view commands
118
- def do_view(self, arg):
119
- '''
120
- view cli
121
- view watcher
122
- '''
123
- if arg == 'cli':
124
- self._view_cli()
125
- elif arg == 'watcher':
126
- self._view_watcher()
127
- else:
128
- self.safePrint('Usage: view <cli|watcher>')
129
244
 
130
- def _view_cli(self):
131
- self.watcher.router.disableOriginOutput()
132
- self.outputMode = 'cli'
133
- self.buffer.enabled = True
245
+ # commands
246
+ @command('stats')
247
+ def stats(self: WatcherCLI, ctx: CommandContext):
134
248
 
135
- utils.clearTerminal()
136
- self.safePrint('', end='')
249
+ @child('get')
250
+ def get(stat: str):
137
251
 
138
- # header is always printed fresh, not stored in buffer
139
- self.printHeader()
252
+ @param('rounding', type=int, default=2)
253
+ def rounding(value: int) -> int:
254
+ return value
140
255
 
141
- # replay captured CLI output
142
- for msg in self.buffer.captured:
143
- self.safePrint(msg)
256
+ @param('mode', default='current')
257
+ def mode(value: str) -> str:
258
+ return value
144
259
 
145
- def _view_watcher(self):
146
- self.watcher.router.enableOriginOutput()
147
- self.outputMode = 'both'
260
+ @flag('raw')
261
+ def raw() -> bool:
262
+ return False
148
263
 
149
- utils.clearTerminal()
150
- self.safePrint('', end='')
264
+ @flag('formatted')
265
+ def formatted() -> bool:
266
+ return True
151
267
 
152
- # replay watcher output
153
- for msg in self.watcher.router.buffer.captured:
154
- self.safePrint(msg)
268
+ @flag('no-formatted')
269
+ def no_formatted() -> bool:
270
+ return False
155
271
 
156
- # stats commands
157
- def do_stats(self, arg):
158
- '''
159
- stats get <cpu|ram|uptime|tps|players> [gb:true|false] [rounding:<int>]
160
- Example:
161
- stats get ram
162
- stats get ram gb:false
163
- stats get ram gb:false rounding:1
164
- '''
165
- parts = arg.split()
166
- if len(parts) == 0 or parts[0] != 'get':
167
- self.safePrint('Usage: stats get <cpu|ram|uptime|tps|players> [gb:true|false] [rounding:<int>]')
168
- return
169
-
170
- # strip the leading 'get'
171
- tokens = parts[1:]
172
- if not tokens:
173
- self.safePrint('Usage: stats get <cpu|ram|uptime|tps|players> [gb:true|false] [rounding:<int>]')
174
- return
175
-
176
- # first token is the stat name, validated by stats_parser
177
- try:
178
- args = stats_parser.parse_args([tokens[0]])
179
- stat = args.stat
180
- except SystemExit:
181
- self.safePrint('Usage: stats get <cpu|ram|uptime|tps|players> [gb:<bool>] [rounding:<int>] [formatted:<bool>]')
182
- return
183
-
184
- # defaults
185
- gb = True
186
- rounding = 2
187
- formatted = True
188
-
189
- # parse optional key:value tokens
190
- for token in tokens[1:]:
191
- if ':' not in token:
192
- continue
193
- key, value = token.split(':', 1)
194
- key = key.strip().lower()
195
- value = value.strip().lower()
196
-
197
- if key == 'gb':
198
- gb = value == 'true'
199
- elif key == 'rounding':
200
- try:
201
- rounding = int(value)
202
- except ValueError:
203
- self.safePrint('rounding must be an integer')
204
- return
205
- elif key == 'formatted':
206
- formatted = value == 'true'
272
+ # extract specs
273
+ r = ctx.arg_specs['rounding']
274
+ m = ctx.arg_specs['mode']
275
+ raw_f = ctx.arg_specs['raw']
276
+ fmt_f = ctx.arg_specs['formatted']
277
+ nofmt_f = ctx.arg_specs['no-formatted']
207
278
 
208
- self._stats_get(stat, gb=gb, rounding=rounding, formatted=formatted)
279
+ rounding_val = r()
280
+ mode_val = m()
209
281
 
210
- def _stats_get(self, stat: str, gb: bool=True, rounding: int=2, formatted: bool=True):
211
- self.watcher.server.refresh()
282
+ gb: bool = False if raw_f.present else True
212
283
 
213
- if stat == 'ram':
214
- value = self.watcher.server.getRAM(rounding=rounding, gb=gb)
215
- stat_name = 'RAM'
216
- unit = ' GB' if gb else ' MB'
217
- elif stat == 'cpu':
218
- value = self.watcher.server.getCPU(rounding=rounding)
219
- stat_name = 'CPU'
220
- unit = '%'
221
- elif stat == 'uptime':
222
- value = self.watcher.server.getUptime(formatted=formatted)
223
- stat_name = 'Uptime'
224
- unit = '' if formatted else 'ms'
225
- elif stat == 'tps':
226
- value = self.watcher.server.getTPS()
227
- stat_name = 'TPS'
228
- unit = ''
229
- elif stat == 'players':
230
- value = self.watcher.server.getPlayers()
231
- stat_name = 'Players'
232
- unit = ''
284
+ if fmt_f.present:
285
+ fmt: bool = True
286
+ elif nofmt_f.present:
287
+ fmt = False
233
288
  else:
234
- self.safePrint('Unknown stat')
235
- return
236
-
237
- self.bprint(f'{stat_name}: {value}{unit}')
238
-
239
- # clear command
240
- def do_clear(self, arg):
241
- '''
242
- clear buffer:true
243
- clear buffer:false
244
- '''
245
- parts = arg.split()
246
- clear_buffer = False
247
-
248
- # parse key:value pairs
249
- for token in parts:
250
- if ':' not in token:
251
- continue
252
- key, value = token.split(':', 1)
253
- key = key.strip().lower()
254
- value = value.strip().lower()
289
+ fmt = True
255
290
 
256
- if key == 'buffer':
257
- clear_buffer = (value == 'true')
291
+ self.watcher.server.refresh()
258
292
 
259
- # clear CLI buffer only
260
- if clear_buffer:
261
- self.buffer.clear()
293
+ unit: str = ''
294
+ match stat:
295
+ case 'ram':
296
+ value = self.watcher.server.getRAM(rounding=rounding_val, gb=gb)
297
+ name = 'RAM'
298
+ unit = ' GB' if gb else ' MB'
299
+ case 'cpu':
300
+ value = self.watcher.server.getCPU(rounding=rounding_val)
301
+ name = 'CPU'
302
+ unit = '%'
303
+ case 'uptime':
304
+ value = self.watcher.server.getUptime(formatted=fmt)
305
+ name = 'Uptime'
306
+ unit = '' if fmt else 'ms'
307
+ case 'tps':
308
+ value = self.watcher.server.getTPS(rounding=rounding_val, mode=mode_val)
309
+ name = 'TPS'
310
+ case 'players':
311
+ value = self.watcher.server.getPlayers()
312
+ name = 'Players'
313
+ case 'version':
314
+ value = self.watcher.server.version
315
+ name = 'Minecraft version'
316
+ case 'platform':
317
+ value = self.watcher.server.platform
318
+ name = 'Server platform'
319
+ case _:
320
+ return self.safePrint('Unknown stat')
321
+
322
+ self.bprint(f'{name}: {value}{unit}')
323
+
324
+
325
+ @command('view')
326
+ def view(self: WatcherCLI, ctx: CommandContext):
327
+
328
+ @child('cli')
329
+ def cli_view(_):
330
+ self.watcher.router.disableOriginOutput()
331
+ self.outputMode = 'cli'
332
+ self.buffer.enabled = True
333
+ utils.clearTerminal()
334
+ self.printHeader()
335
+ for msg in self.buffer.captured:
336
+ self.safePrint(msg)
262
337
 
263
- # clear terminal (but NOT watcher buffer)
338
+ @child('watcher')
339
+ def watcher_view(_):
340
+ self.watcher.router.enableOriginOutput()
341
+ self.outputMode = 'both'
264
342
  utils.clearTerminal()
265
343
  self.printHeader()
344
+ for msg in self.watcher.router.buffer.captured:
345
+ self.safePrint(msg)
266
346
 
267
347
 
268
- # watcher commands
269
- def do_watcher(self, arg):
270
- '''
271
- watcher restart
272
- watcher schedule <minutes>
273
- watcher shutdown
274
- '''
275
- parts = arg.split()
348
+ @command('clear')
349
+ def clear(self: WatcherCLI, ctx: CommandContext):
276
350
 
277
- if len(parts) == 0:
278
- self.safePrint('Usage: watcher <restart|schedule|shutdown>')
279
- return
351
+ @param('buffer', type=str, default='true')
352
+ def buffer_param(value: str) -> bool:
353
+ return value.lower() == 'true'
280
354
 
281
- sub = parts[0]
355
+ buf = ctx.arg_specs['buffer']()
282
356
 
283
- if sub == 'restart':
284
- self.watcher.restart_and_wait()
357
+ if buf:
358
+ self.buffer.clear()
285
359
 
286
- elif sub == 'schedule':
287
- try:
288
- args = schedule_parser.parse_args(parts[1:])
289
- self.watcher.schedule_restart(args.minutes)
290
- except SystemExit:
291
- self.safePrint('Usage: watcher schedule <minutes>')
360
+ utils.clearTerminal()
361
+ self.printHeader()
292
362
 
293
- elif sub == 'shutdown':
294
- self.watcher.shutdown()
295
- return True
296
363
 
297
- else:
298
- self.safePrint('Usage: watcher <restart|schedule|shutdown>')
364
+ @command('watcher')
365
+ def watcher(self: WatcherCLI, ctx: CommandContext):
299
366
 
300
- # buffer print
301
- def bprint(self, text):
302
- if self.buffer.enabled:
303
- self.buffer.captured.append(str(text))
304
- self.safePrint(str(text))
367
+ @child('restart')
368
+ def restart(_):
369
+ self.watcher.restart_and_wait()
370
+
371
+ @child('schedule')
372
+ def schedule(_):
373
+ minutes = ctx.positional(1)
374
+ if minutes is None:
375
+ return self.safePrint('Usage: watcher schedule <minutes>')
376
+ try:
377
+ minutes = int(minutes)
378
+ except ValueError:
379
+ return self.safePrint('Minutes must be an integer')
380
+ self.watcher.schedule_restart(minutes)
381
+
382
+ @child('shutdown')
383
+ def shutdown(_):
384
+ self.watcher.shutdown()
385
+ return True
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: serverwatcher
3
- Version: 6.dev1
3
+ Version: 6.dev2
4
4
  Summary: A HungerLib-powered Minecraft server automation engine.
5
5
  Author: iFamished
6
6
  License: GPL-3.0
@@ -1,6 +1,6 @@
1
1
  serverwatcher/__init__.py,sha256=Q_afN0XU29n48d6Gf0-LT2lLo3RiTWlHRT6rC_fYbjw,486
2
2
  serverwatcher/__main__.py,sha256=XjGcQ_-8p4ttuVYlYEvYKUEvcAsvZUQaEA0mX0ajRbU,3097
3
- serverwatcher/cli.py,sha256=RMQ03fWFQi1O7HUtmILmUf8XZfxQ5eFc9lZp85uEnFw,8794
3
+ serverwatcher/cli.py,sha256=scVUrEHn4MUTz0W3AADeU5bDuSsNtLbs1vim-yw8R4s,10551
4
4
  serverwatcher/validator.py,sha256=aD6GHOz1S5VFC93Mj89WO9vZG1bTjhg7QZbdlvQf4wo,1778
5
5
  serverwatcher/watcher.py,sha256=ZiocJpeyhKTGOwYYak36MXNEFpLnpdl9v6BnMPGrBmM,13593
6
6
  serverwatcher/configclasses/__init__.py,sha256=YS0KhxtAJGdMcaiFstqTRNxIPLnR7s9v3Tkt5h2uKE4,182
@@ -10,8 +10,8 @@ serverwatcher/configclasses/watcher.py,sha256=OIAYQZF9hD9e5FbcaYV5N9CAdCZoLgXSqA
10
10
  serverwatcher/defaultconfigs/config.yaml,sha256=yrJ59Jx0F4TJzE1EdBF5IKPCDqs09XcbKHFfkYGJ1ys,721
11
11
  serverwatcher/defaultconfigs/messages.yaml,sha256=jSVEl-RYqPHhe5U5KLl8zfJtUBymvyE74hmzH0RFC_Y,3177
12
12
  serverwatcher/defaultconfigs/watcher.yaml,sha256=GlAEKCuzFUSF6wWOqQLFL1CeuPltb1ltfYxFe_FUClw,723
13
- serverwatcher-6.dev1.dist-info/licenses/LICENSE,sha256=OXLcl0T2SZ8Pmy2_dmlvKuetivmyPd5m1q-Gyd-zaYY,35149
14
- serverwatcher-6.dev1.dist-info/METADATA,sha256=fROEfLXcejeD8UvlAJhb28lTCBpmNdvz-ihEwiDWY3s,2646
15
- serverwatcher-6.dev1.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
16
- serverwatcher-6.dev1.dist-info/top_level.txt,sha256=8DJAf8WmmglgtZHkp8aoTriRJ2YPcS4F3DfOIkytASo,14
17
- serverwatcher-6.dev1.dist-info/RECORD,,
13
+ serverwatcher-6.dev2.dist-info/licenses/LICENSE,sha256=OXLcl0T2SZ8Pmy2_dmlvKuetivmyPd5m1q-Gyd-zaYY,35149
14
+ serverwatcher-6.dev2.dist-info/METADATA,sha256=TDUf2JgkW6vWztOTK0cuEaP2NAX946IPp34tAGXymvs,2646
15
+ serverwatcher-6.dev2.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
16
+ serverwatcher-6.dev2.dist-info/top_level.txt,sha256=8DJAf8WmmglgtZHkp8aoTriRJ2YPcS4F3DfOIkytASo,14
17
+ serverwatcher-6.dev2.dist-info/RECORD,,