xkits-command 0.1__py2.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.
@@ -0,0 +1,9 @@
1
+ # coding:utf-8
2
+
3
+ from xkits_command.actuator import Command # noqa:F401
4
+ from xkits_command.actuator import CommandArgument # noqa:F401,H306
5
+ from xkits_command.actuator import CommandCreation # noqa:F401
6
+ from xkits_command.actuator import CommandDeletion # noqa:F401
7
+ from xkits_command.actuator import CommandExecutor # noqa:F401
8
+ from xkits_command.actuator import Namespace # noqa:F401
9
+ from xkits_command.parser import ArgParser # noqa:F401
@@ -0,0 +1,724 @@
1
+ # coding:utf-8
2
+
3
+ from argparse import Namespace
4
+ from errno import ECANCELED
5
+ from errno import EINVAL
6
+ from errno import ENOENT
7
+ from errno import ENOTRECOVERABLE
8
+ import logging
9
+ from logging import Logger
10
+ from os import getenv
11
+ import sys
12
+ from typing import Any
13
+ from typing import Callable
14
+ from typing import Dict
15
+ from typing import List
16
+ from typing import Optional
17
+ from typing import Sequence
18
+ from typing import Tuple
19
+
20
+ from xkits_logger.attribute import __project__
21
+ from xkits_logger.logger import Logger as Log
22
+
23
+ from xkits_command.parser import ArgParser
24
+
25
+
26
+ class CommandArgument:
27
+ '''Define a new command-line node.
28
+
29
+ For example:
30
+
31
+ >>> from xkits_command import ArgParser\n
32
+ >>> from xkits_command import CommandArgument\n
33
+
34
+ >>> @CommandArgument("example")\n
35
+ >>> def cmd(_arg: ArgParser):\n
36
+ >>> _arg.add_opt_on("-t", "--test")\n
37
+ '''
38
+
39
+ def __init__(self, name: str, **kwargs):
40
+ '''Initialize the node.
41
+
42
+ @param name: Node name
43
+ @type name: str
44
+
45
+ @param description: Text to display before the argument help
46
+ @type description: str (by default, no text)
47
+
48
+ @param epilog: Text to display after the argument help
49
+ @type epilog: str (by default, no text)
50
+
51
+ @param help: Help message as a subcommand
52
+ @type help: str
53
+
54
+ @param add_help: Add a -h/--help option to the node
55
+ @type add_help: bool (default: True)
56
+ '''
57
+ if "help" in kwargs and "description" not in kwargs:
58
+ kwargs["description"] = kwargs["help"]
59
+ if "description" in kwargs and "help" not in kwargs:
60
+ kwargs["help"] = kwargs["description"]
61
+ self.__name: str = name
62
+ self.__prev: CommandArgument = self
63
+ self.__cmds: Command = Command()
64
+ self.__options: Dict[str, Any] = kwargs
65
+ self.__bind: Optional[CommandExecutor] = None
66
+ self.__subs: Optional[Tuple[CommandArgument, ...]] = None
67
+ self.__func: Optional[Callable[[ArgParser], None]] = None
68
+
69
+ def __call__(self, cmd_func: Callable[[ArgParser], None]):
70
+ self.__func = cmd_func
71
+ return self
72
+
73
+ @property
74
+ def func(self) -> Callable[[ArgParser], None]:
75
+ if self.__func is None:
76
+ raise ValueError("No function") # pragma: no cover
77
+ return self.__func
78
+
79
+ @property
80
+ def name(self) -> str:
81
+ return self.__name
82
+
83
+ @property
84
+ def root(self) -> "CommandArgument":
85
+ root = self.__prev
86
+ while root.prev != root:
87
+ root = root.prev
88
+ return root
89
+
90
+ @property
91
+ def prev(self) -> "CommandArgument":
92
+ return self.__prev
93
+
94
+ @prev.setter
95
+ def prev(self, value: "CommandArgument"):
96
+ assert isinstance(value, CommandArgument)
97
+ self.__prev = value
98
+
99
+ @property
100
+ def cmds(self) -> "Command":
101
+ return self.__cmds
102
+
103
+ @property
104
+ def options(self) -> Dict[str, Any]:
105
+ return self.__options
106
+
107
+ @property
108
+ def bind(self) -> Optional["CommandExecutor"]:
109
+ return self.__bind
110
+
111
+ @bind.setter
112
+ def bind(self, value: "CommandExecutor"):
113
+ assert isinstance(value, CommandExecutor)
114
+ self.__bind = value
115
+
116
+ @property
117
+ def subs(self) -> Optional[Tuple["CommandArgument", ...]]:
118
+ return self.__subs
119
+
120
+ @subs.setter
121
+ def subs(self, value: Tuple["CommandArgument", ...]):
122
+ assert isinstance(value, Tuple)
123
+ for sub in value:
124
+ assert isinstance(sub, CommandArgument)
125
+ self.__subs = value
126
+
127
+ @property
128
+ def sub_dest(self) -> str:
129
+ node: CommandArgument = self
130
+ subs: List[str] = [self.name]
131
+ while node.prev is not node:
132
+ node = node.prev
133
+ subs.insert(0, node.name)
134
+ name = "_".join(subs)
135
+ return f"__sub_dest_{name}__"
136
+
137
+
138
+ class CommandExecutor:
139
+ '''Define the main callback function, and bind it to a node and
140
+ all subcommands.
141
+
142
+ For example:
143
+
144
+ >>> from xkits_command import Command\n
145
+ >>> from xkits_command import CommandExecutor\n
146
+
147
+ >>> @CommandExecutor(cmd, cmd_get, cmd_set)\n
148
+ >>> def run(cmds: Command) -> int:\n
149
+ >>> return 0\n
150
+ '''
151
+
152
+ def __init__(self, cmd_bind: CommandArgument, *sub_cmds: CommandArgument,
153
+ skip: bool = False):
154
+ '''Initialize the node.
155
+
156
+ @param cmd_bind: Bind to a root command node
157
+ @type name: CommandArgument
158
+
159
+ @param *sub_cmds: All required subcommands
160
+ @type *sub_cmds: CommandArgument
161
+
162
+ @param skip: This node (CommandExecutor, CommandCreation and
163
+ CommandDeletion) does not run when a subcommand is specified,
164
+ run this node without any subcommands
165
+ @type skip: bool (default: False)
166
+ '''
167
+ assert isinstance(cmd_bind, CommandArgument)
168
+ assert isinstance(skip, bool)
169
+ cmd_bind.bind = self
170
+ cmd_bind.subs = sub_cmds
171
+ for sub in sub_cmds:
172
+ sub.prev = cmd_bind
173
+ cmd_bind.cmds.root = cmd_bind.root
174
+ self.__skip: bool = skip
175
+ self.__bind: CommandArgument = cmd_bind
176
+ self.__prep: Optional["CommandCreation"] = None
177
+ self.__done: Optional["CommandDeletion"] = None
178
+ self.__func: Optional[Callable[["Command"], int]] = None
179
+
180
+ def __call__(self, run_func: Callable[["Command"], int]):
181
+ self.__func = run_func
182
+ return self
183
+
184
+ @property
185
+ def func(self) -> Callable[["Command"], int]:
186
+ if self.__func is None:
187
+ raise ValueError("No function") # pragma: no cover
188
+ return self.__func
189
+
190
+ @property
191
+ def bind(self) -> CommandArgument:
192
+ return self.__bind
193
+
194
+ @property
195
+ def prep(self) -> Optional["CommandCreation"]:
196
+ return self.__prep
197
+
198
+ @prep.setter
199
+ def prep(self, value: "CommandCreation"):
200
+ assert isinstance(value, CommandCreation)
201
+ self.__prep = value
202
+
203
+ @property
204
+ def done(self) -> Optional["CommandDeletion"]:
205
+ return self.__done
206
+
207
+ @done.setter
208
+ def done(self, value: "CommandDeletion"):
209
+ assert isinstance(value, CommandDeletion)
210
+ self.__done = value
211
+
212
+ @property
213
+ def skip(self) -> bool:
214
+ return self.__skip
215
+
216
+
217
+ class CommandCreation:
218
+ '''Define prepare callback function, and bind it with main callback.
219
+
220
+ For example:
221
+
222
+ >>> from xkits_command import Command\n
223
+ >>> from xkits_command import CommandCreation\n
224
+ >>> from xkits_command import CommandExecutor\n
225
+
226
+ >>> @CommandExecutor(cmd, cmd_get, cmd_set)\n
227
+ >>> def run(cmds: Command) -> int:\n
228
+ >>> return 0\n
229
+
230
+ >>> @CommandCreation(run)\n
231
+ >>> def pre(cmds: Command) -> int:\n
232
+ >>> return 0\n
233
+ '''
234
+
235
+ def __init__(self, run_bind: CommandExecutor):
236
+ '''Initialize the node.
237
+
238
+ @param cmd_bind: Bind to a root command node
239
+ @type name: CommandArgument
240
+ '''
241
+ assert isinstance(run_bind, CommandExecutor)
242
+ run_bind.prep = self
243
+ self.__main: CommandExecutor = run_bind
244
+ self.__func: Optional[Callable[["Command"], int]] = None
245
+
246
+ def __call__(self, run_func: Callable[["Command"], int]):
247
+ self.__func = run_func
248
+ return self
249
+
250
+ @property
251
+ def func(self) -> Callable[["Command"], int]:
252
+ if self.__func is None:
253
+ raise ValueError("No function") # pragma: no cover
254
+ return self.__func
255
+
256
+ @property
257
+ def main(self) -> CommandExecutor:
258
+ return self.__main
259
+
260
+
261
+ class CommandDeletion:
262
+ '''Define purge callback function, and bind it with main callback.
263
+
264
+ For example:
265
+
266
+ >>> from xkits_command import Command\n
267
+ >>> from xkits_command import CommandDeletion\n
268
+ >>> from xkits_command import CommandExecutor\n
269
+
270
+ >>> @CommandExecutor(cmd, cmd_get, cmd_set)\n
271
+ >>> def run(cmds: Command) -> int:\n
272
+ >>> return 0\n
273
+
274
+ >>> @CommandDeletion(run)\n
275
+ >>> def end(cmds: Command) -> int:\n
276
+ >>> return 0\n
277
+ '''
278
+
279
+ def __init__(self, run_bind: CommandExecutor):
280
+ '''Initialize the node.
281
+
282
+ @param cmd_bind: Bind to a root command node
283
+ @type name: CommandArgument
284
+ '''
285
+ assert isinstance(run_bind, CommandExecutor)
286
+ run_bind.done = self
287
+ self.__main: CommandExecutor = run_bind
288
+ self.__func: Optional[Callable[["Command"], int]] = None
289
+
290
+ def __call__(self, run_func: Callable[["Command"], int]):
291
+ self.__func = run_func
292
+ return self
293
+
294
+ @property
295
+ def func(self) -> Callable[["Command"], int]:
296
+ if self.__func is None:
297
+ raise ValueError("No function") # pragma: no cover
298
+ return self.__func
299
+
300
+ @property
301
+ def main(self) -> CommandExecutor:
302
+ return self.__main
303
+
304
+
305
+ class Command(Log):
306
+ '''Singleton command-line tool based on argparse.
307
+
308
+ Define and bind all callback functions before calling run() or parse().
309
+
310
+ For example:
311
+
312
+ >>> from typing import Optional\n
313
+ >>> from typing import Sequence\n
314
+
315
+ >>> from xkits_command import ArgParser\n
316
+ >>> from xkits_command import Command\n
317
+ >>> from xkits_command import CommandArgument\n
318
+ >>> from xkits_command import CommandCreation\n
319
+ >>> from xkits_command import CommandDeletion\n
320
+ >>> from xkits_command import CommandExecutor\n
321
+
322
+ >>> @CommandArgument("example")\n
323
+ >>> def cmd(_arg: ArgParser):\n
324
+ >>> _arg.add_opt_on("-t", "--test")\n
325
+
326
+ >>> @CommandExecutor(cmd, cmd_get, cmd_set)\n
327
+ >>> def run(cmds: Command) -> int:\n
328
+ >>> return 0\n
329
+
330
+ >>> @CommandCreation(run)\n
331
+ >>> def pre(cmds: Command) -> int:\n
332
+ >>> return 0\n
333
+
334
+ >>> @CommandDeletion(run)\n
335
+ >>> def end(cmds: Command) -> int:\n
336
+ >>> return 0\n
337
+
338
+ >>> def main(argv: Optional[Sequence[str]] = None) -> int:\n
339
+ >>> return Command().run(\n
340
+ >>> root=cmd,\n
341
+ >>> argv=argv,\n
342
+ >>> prog="xkits-command-example",\n
343
+ >>> description="Simple command-line tool based on argparse.")\n
344
+ '''
345
+
346
+ LOGGER_ARGUMENT_GROUP = "logger options"
347
+
348
+ __INSTANCE: Optional["Command"] = None
349
+ __INITIALIZED: bool = False
350
+
351
+ def __init__(self):
352
+ if not self.__INITIALIZED:
353
+ self.__prog: str = __project__
354
+ self.__root: Optional[CommandArgument] = None
355
+ self.__args: Namespace = Namespace()
356
+ self.__version: Optional[str] = None
357
+ self.__enabled_logger: bool = True
358
+ self.__INITIALIZED = True
359
+ super().__init__()
360
+
361
+ def __new__(cls):
362
+ if not cls.__INSTANCE:
363
+ cls.__INSTANCE = super(Command, cls).__new__(cls)
364
+ return cls.__INSTANCE
365
+
366
+ @property
367
+ def prog(self) -> str:
368
+ return self.__prog
369
+
370
+ @property
371
+ def root(self) -> Optional[CommandArgument]:
372
+ '''Root Command.'''
373
+ return self.__root
374
+
375
+ @root.setter
376
+ def root(self, value: CommandArgument):
377
+ assert isinstance(value, CommandArgument)
378
+ self.__root = value
379
+
380
+ @property
381
+ def args(self) -> Namespace:
382
+ '''Namespace after parse arguments.'''
383
+ assert isinstance(self.__args, Namespace)
384
+ return self.__args
385
+
386
+ @args.setter
387
+ def args(self, value: Namespace):
388
+ assert isinstance(value, Namespace)
389
+ self.__args = value
390
+
391
+ @property
392
+ def version(self) -> Optional[str]:
393
+ '''Custom version for "-v" or "--version" output.'''
394
+ return self.__version
395
+
396
+ @version.setter
397
+ def version(self, value: str):
398
+ assert isinstance(value, str)
399
+ _version = value.strip()
400
+ self.__version = _version
401
+
402
+ @property
403
+ def enabled_logger(self) -> bool:
404
+ return self.__enabled_logger
405
+
406
+ @enabled_logger.setter
407
+ def enabled_logger(self, value: bool):
408
+ assert isinstance(value, bool)
409
+ self.__enabled_logger = value
410
+
411
+ @property
412
+ def logger(self) -> Logger:
413
+ '''Logger.'''
414
+ return self.get_logger(self.prog)
415
+
416
+ def __add_optional_version(self, _arg: ArgParser):
417
+ version = self.version
418
+ if not isinstance(version, str):
419
+ return
420
+
421
+ options = _arg.filter_optional_name("-v", "--version")
422
+ if len(options) > 0:
423
+ _arg.add_argument(*options, action="version",
424
+ version=f"%(prog)s {version.strip()}")
425
+
426
+ def __add_inner_parser_tail(self, _arg: ArgParser):
427
+
428
+ def filter_optional_name(*name: str) -> Optional[str]:
429
+ options = _arg.filter_optional_name(*name)
430
+ if len(options) > 0:
431
+ for i in name:
432
+ if i in options:
433
+ return i
434
+ return None
435
+
436
+ def add_optional_level():
437
+ group = _arg.argument_group(self.LOGGER_ARGUMENT_GROUP)
438
+ group_level = group.add_mutually_exclusive_group()
439
+
440
+ option_level = filter_optional_name("--level", "--log-level")
441
+ if isinstance(option_level, str):
442
+ DEF_LOG_LEVEL: str = getenv("LOG_LEVEL", self.LOG_LEVELS.INFO.value).lower() # noqa:E501
443
+ group_level.add_argument(
444
+ option_level,
445
+ type=str,
446
+ nargs="?",
447
+ const=DEF_LOG_LEVEL,
448
+ default=DEF_LOG_LEVEL,
449
+ choices=self.ALLOWED_LOG_LEVELS,
450
+ dest="_log_level_str_",
451
+ help=f"Logger output level, default is {DEF_LOG_LEVEL}.")
452
+
453
+ for level in self.ALLOWED_LOG_LEVELS:
454
+ options = []
455
+ if isinstance(filter_optional_name(f"-{level[0]}"), str):
456
+ options.append(f"-{level[0]}")
457
+ if isinstance(filter_optional_name(f"--{level}"), str):
458
+ options.append(f"--{level}")
459
+ elif isinstance(filter_optional_name(f"--{level}-level"), str):
460
+ options.append(f"--{level}-level")
461
+
462
+ if not options:
463
+ continue
464
+ group_level.add_argument(*options,
465
+ action="store_const",
466
+ const=level,
467
+ dest="_log_level_str_",
468
+ help=f"Logger level set to {level}.")
469
+
470
+ def add_optional_stream():
471
+ option = filter_optional_name("--log", "--log-file")
472
+ if not isinstance(option, str):
473
+ return
474
+
475
+ group = _arg.argument_group(self.LOGGER_ARGUMENT_GROUP)
476
+ group.add_argument(option,
477
+ type=str,
478
+ nargs=1,
479
+ default=[],
480
+ metavar="FILE",
481
+ action="extend",
482
+ dest="_log_files_",
483
+ help="Logger output to file.")
484
+
485
+ def add_optional_format():
486
+ option = filter_optional_name("--format", "--log-format")
487
+ if not isinstance(option, str):
488
+ return
489
+
490
+ DEFAULT_LOG_FMT = "%(log_color)s%(asctime)s"\
491
+ " %(process)d %(threadName)s %(levelname)s"\
492
+ " %(funcName)s %(filename)s:%(lineno)s"\
493
+ " %(message)s"
494
+
495
+ group = _arg.argument_group(self.LOGGER_ARGUMENT_GROUP)
496
+ group.add_argument(option,
497
+ type=str,
498
+ nargs="?",
499
+ const=DEFAULT_LOG_FMT,
500
+ default=self.DEFAULT_LOG_FORMAT,
501
+ metavar="STRING",
502
+ dest="_log_format_",
503
+ help="Logger output format.")
504
+
505
+ def add_optional_console():
506
+ group = _arg.argument_group(self.LOGGER_ARGUMENT_GROUP)
507
+ group_std = group.add_mutually_exclusive_group()
508
+
509
+ option = filter_optional_name("--stdout", "--log-stdout")
510
+ if isinstance(option, str):
511
+ group_std.add_argument(option,
512
+ const=sys.stdout,
513
+ action="store_const",
514
+ dest="_log_console_",
515
+ help="Logger output to stdout.")
516
+
517
+ option = filter_optional_name("--stderr", "--log-stderr")
518
+ if isinstance(option, str):
519
+ group_std.add_argument(option,
520
+ const=sys.stderr,
521
+ action="store_const",
522
+ dest="_log_console_",
523
+ help="Logger output to stderr.")
524
+
525
+ if self.enabled_logger:
526
+ add_optional_level()
527
+ add_optional_stream()
528
+ add_optional_format()
529
+ add_optional_console()
530
+
531
+ def __parse_logger(self, args: Namespace):
532
+ if not self.enabled_logger:
533
+ return
534
+
535
+ def parse_format() -> Optional[str]:
536
+ if hasattr(args, "_log_format_"):
537
+ fmt = getattr(args, "_log_format_")
538
+ if isinstance(fmt, str):
539
+ return fmt
540
+ return None
541
+
542
+ def parse_level() -> Optional[str]:
543
+ if hasattr(args, "_log_level_str_"):
544
+ level = getattr(args, "_log_level_str_")
545
+ if isinstance(level, str):
546
+ return level.upper()
547
+ return None
548
+
549
+ def parse_console() -> Optional[Any]:
550
+ return getattr(args, "_log_console_", None)
551
+
552
+ def parse_files() -> List[str]:
553
+ return getattr(args, "_log_files_", [])
554
+
555
+ fmt: Optional[str] = parse_format()
556
+ level_name: Optional[str] = parse_level()
557
+ console: Optional[Any] = parse_console()
558
+
559
+ handlers: List[logging.Handler] = []
560
+ if console is not None:
561
+ handlers.append(Log.new_stream_handler(stream=console, fmt=fmt))
562
+ for filename in parse_files():
563
+ handlers.append(Log.new_file_handler(filename=filename, fmt=fmt))
564
+ self.initiate_logger(self.logger, level=level_name, handlers=handlers)
565
+
566
+ def __add_parser(self, _map: Dict[CommandArgument, ArgParser],
567
+ arg_root: ArgParser, cmd_root: CommandArgument, **kwargs):
568
+ assert isinstance(cmd_root, CommandArgument)
569
+ assert cmd_root not in _map
570
+ _map[cmd_root] = arg_root
571
+
572
+ if not cmd_root.subs or len(cmd_root.subs) <= 0:
573
+ return
574
+
575
+ _sub = arg_root.add_subparsers(dest=cmd_root.sub_dest)
576
+ for sub in cmd_root.subs:
577
+ assert isinstance(sub, CommandArgument)
578
+ options = sub.options.copy()
579
+ for key, value in kwargs.items():
580
+ options.setdefault(key, value)
581
+ options.setdefault("epilog", arg_root.epilog)
582
+ options.setdefault("prev_parser", arg_root)
583
+ _arg: ArgParser = _sub.add_parser(sub.name, **options)
584
+ self.__add_parser(_map, _arg, sub)
585
+
586
+ def __add_option(self, _map: Dict[CommandArgument, ArgParser]):
587
+ for _cmd, _arg in _map.items():
588
+ _cmd.func(_arg)
589
+ self.__add_inner_parser_tail(_arg)
590
+
591
+ @classmethod
592
+ def check_error(cls, value: Any) -> int:
593
+ '''Check value is an error.
594
+
595
+ Return True if value is an error, otherwise False.
596
+ '''
597
+ return value if isinstance(value, int) else 0 if value in (None, True) else EINVAL # noqa:E501
598
+
599
+ def parse(self, root: Optional[CommandArgument] = None,
600
+ argv: Optional[Sequence[str]] = None, **kwargs) -> Namespace:
601
+ '''Parse the command line.'''
602
+ if root is None:
603
+ root = self.root
604
+ assert isinstance(root, CommandArgument)
605
+
606
+ _map: Dict[CommandArgument, ArgParser] = {}
607
+ _arg = ArgParser(argv=argv, **kwargs)
608
+ self.__prog = _arg.prog
609
+ self.__add_optional_version(_arg)
610
+ # To support preparse_from_sys_argv(), all subparsers must be added
611
+ # first. Otherwise, an error will occur during the help action.
612
+ self.__add_parser(_map, _arg, root, **kwargs)
613
+ self.__add_option(_map)
614
+
615
+ args = _arg.parse_args(args=argv)
616
+ assert isinstance(args, Namespace)
617
+ self.__parse_logger(args)
618
+ self.args = args
619
+ return self.args
620
+
621
+ def has_sub(self, root: CommandArgument,
622
+ args: Optional[Namespace] = None) -> bool:
623
+ '''If the root command node has any subcommand nodes, return true.
624
+
625
+ @param root: Command node
626
+ @type root: CommandArgument
627
+
628
+ @param args: Command arguments
629
+ @type args: Namespace or None (default self.args if None is specified)
630
+
631
+ @return: bool
632
+ '''
633
+ if args is None:
634
+ args = self.args
635
+ assert isinstance(root, CommandArgument)
636
+ assert isinstance(args, Namespace)
637
+ return isinstance(getattr(args, root.sub_dest), str)\
638
+ if hasattr(args, root.sub_dest) else False
639
+
640
+ def __run(self, args: Namespace, root: CommandArgument) -> int:
641
+ assert isinstance(root, CommandArgument)
642
+ assert isinstance(root.bind, CommandExecutor)
643
+
644
+ if not root.bind.skip or not self.has_sub(root, args):
645
+ ret = root.bind.func(self)
646
+ if self.check_error(ret):
647
+ return ret
648
+
649
+ if hasattr(args, root.sub_dest):
650
+ sub_dest = getattr(args, root.sub_dest)
651
+ if isinstance(sub_dest, str):
652
+ assert isinstance(root.subs, (list, tuple))
653
+ for sub in root.subs:
654
+ assert isinstance(sub, CommandArgument)
655
+ if sub.name == sub_dest:
656
+ ret = self.__run(args, sub)
657
+ if self.check_error(ret):
658
+ return ret
659
+
660
+ done = root.bind.done
661
+ if done is not None:
662
+ assert isinstance(done, CommandDeletion)
663
+ if not root.bind.skip or not self.has_sub(root, args):
664
+ ret = done.func(self) # purge
665
+ if self.check_error(ret):
666
+ return ret
667
+ return 0
668
+
669
+ def __pre(self, args: Namespace, root: CommandArgument) -> int:
670
+ assert isinstance(root, CommandArgument)
671
+ assert isinstance(root.bind, CommandExecutor)
672
+
673
+ prep = root.bind.prep
674
+ if prep is not None:
675
+ assert isinstance(prep, CommandCreation)
676
+ if not root.bind.skip or not self.has_sub(root, args):
677
+ ret = prep.func(self)
678
+ if self.check_error(ret):
679
+ return ret
680
+
681
+ if hasattr(args, root.sub_dest):
682
+ sub_dest = getattr(args, root.sub_dest)
683
+ if isinstance(sub_dest, str):
684
+ assert isinstance(root.subs, (list, tuple))
685
+ for sub in root.subs:
686
+ assert isinstance(sub, CommandArgument)
687
+ if sub.name == sub_dest:
688
+ return self.__pre(args, sub)
689
+ return 0
690
+
691
+ def run(self,
692
+ root: Optional[CommandArgument] = None,
693
+ argv: Optional[Sequence[str]] = None,
694
+ **kwargs) -> int:
695
+ '''Parse and run the command line.'''
696
+ if root is None:
697
+ root = self.root
698
+
699
+ if not isinstance(root, CommandArgument):
700
+ self.logger.debug("cannot find root")
701
+ return ENOENT
702
+
703
+ kwargs.pop("prog", None) # Please do not specify prog
704
+ if "description" in root.options: # Default use root's description
705
+ kwargs["description"] = root.options["description"]
706
+ args = self.parse(root, argv, **kwargs)
707
+ self.logger.debug("%s", args)
708
+
709
+ try:
710
+ version = self.version
711
+ if isinstance(version, str):
712
+ # Output version for the debug level. Internal log
713
+ # items are debug level only, except for errors.
714
+ self.logger.debug("version: %s", version)
715
+
716
+ ret = self.__pre(args, root)
717
+ if self.check_error(ret):
718
+ return ret
719
+ return self.__run(args, root)
720
+ except KeyboardInterrupt:
721
+ return ECANCELED
722
+ except BaseException: # pylint: disable=broad-except
723
+ self.logger.exception("Something went wrong:")
724
+ return ENOTRECOVERABLE
@@ -0,0 +1,10 @@
1
+ # coding:utf-8
2
+
3
+ __project__ = "xkits-command"
4
+ __version__ = "0.1"
5
+ __description__ = "Command line module"
6
+ __urlhome__ = "https://github.com/bondbox/xcommand/"
7
+
8
+ # author
9
+ __author__ = "Mingzhe Zou"
10
+ __author_email__ = "zoumingzhe@outlook.com"
@@ -0,0 +1,235 @@
1
+ # coding:utf-8
2
+
3
+ from argparse import ArgumentParser
4
+ from argparse import Namespace
5
+ from argparse import _ArgumentGroup # noqa:H306
6
+ from argparse import _HelpAction
7
+ from argparse import _SubParsersAction
8
+ from typing import Dict
9
+ from typing import List
10
+ from typing import Optional
11
+ from typing import Sequence
12
+ from typing import Set
13
+ from typing import Tuple
14
+
15
+ from xkits_logger.attribute import __project__
16
+ from xkits_logger.attribute import __urlhome__
17
+
18
+ try:
19
+ from argcomplete import autocomplete
20
+ except ModuleNotFoundError: # pragma: no cover
21
+ pass # pragma: no cover
22
+
23
+
24
+ class Checker():
25
+
26
+ prefix_chars = "-"
27
+
28
+ @classmethod
29
+ def check_name_pos(cls, fn):
30
+ '''check positional argument name'''
31
+
32
+ def inner(self, name: str, **kwargs):
33
+ assert isinstance(name, str) and name[0] not in cls.prefix_chars, \
34
+ f"{name} is not a positional argument name"
35
+ return fn(self, name, **kwargs)
36
+
37
+ return inner
38
+
39
+ @classmethod
40
+ def check_name_opt(cls, fn):
41
+ '''check optional argument name'''
42
+
43
+ def inner(self, *name: str, **kwargs):
44
+ # 1. check short form optional argument ("-x")
45
+ # 2. check long form optional argument ("--xx")
46
+ # 3. only short form or long form or short form + long form
47
+ # 模棱两可的数据(-1可以是一个负数的位置参数)
48
+ for n in name:
49
+ assert isinstance(n, str) and n[0] in cls.prefix_chars, \
50
+ f"{n} is not an optional argument name"
51
+ return fn(self, *name, **kwargs)
52
+
53
+ return inner
54
+
55
+ @classmethod
56
+ def check_nargs_opt(cls, fn):
57
+ '''nargs hook function:
58
+ nargs < -1: using "?", 0 or 1 argument, default value
59
+ nargs = -1: using "+", arguments list, at least 1
60
+ nargs = 0: using "*", arguments list, allow to be empty
61
+ nargs = 1: redirect to "?", 0 or 1 argument
62
+ nargs > 1: N arguments list
63
+ '''
64
+
65
+ def inner(self, *args, **kwargs):
66
+ _nargs = kwargs.get("nargs", -2)
67
+ if isinstance(_nargs, int) and _nargs < 2:
68
+ _nargs = {1: "?", 0: "*", -1: "+"}.get(_nargs, "?")
69
+ kwargs.update({"nargs": _nargs})
70
+ return fn(self, *args, **kwargs)
71
+
72
+ return inner
73
+
74
+
75
+ class ArgParser(ArgumentParser):
76
+ '''Simple command-line tool based on argparse.'''
77
+
78
+ def __init__(self, # pylint: disable=R0913,R0917
79
+ argv: Optional[Sequence[str]] = None,
80
+ prog: Optional[str] = None,
81
+ usage: Optional[str] = None,
82
+ prev_parser: Optional["ArgParser"] = None,
83
+ description: Optional[str] = f"Command-line based on {__project__}.", # noqa:E501
84
+ epilog: Optional[str] = f"For more, please visit {__urlhome__}", # noqa:E501
85
+ **kwargs):
86
+ kwargs.setdefault("prog", prog)
87
+ kwargs.setdefault("usage", usage)
88
+ kwargs.setdefault("description", description)
89
+ kwargs.setdefault("epilog", epilog)
90
+ ArgumentParser.__init__(self, **kwargs)
91
+ self.__argv: Optional[Sequence[str]] = argv
92
+ self.__help_option: Dict[str, _HelpAction] = {}
93
+ self.__prev_parser: ArgParser = prev_parser or self
94
+ self.__next_parser: List[ArgParser] = []
95
+ if prev_parser is not None:
96
+ prev_parser.next_parser.append(self)
97
+
98
+ @property
99
+ def argv(self) -> Optional[Sequence[str]]:
100
+ root = self.root_parser
101
+ return root.argv if root is not self else self.__argv
102
+
103
+ @property
104
+ def prev_parser(self) -> "ArgParser":
105
+ return self.__prev_parser
106
+
107
+ @property
108
+ def next_parser(self) -> List["ArgParser"]:
109
+ return self.__next_parser
110
+
111
+ @property
112
+ def root_parser(self) -> "ArgParser":
113
+ root = self.prev_parser
114
+ while root.prev_parser != root:
115
+ root = root.prev_parser
116
+ return root
117
+
118
+ def argument_group(self,
119
+ title: Optional[str] = None,
120
+ description: Optional[str] = None,
121
+ **kwargs) -> _ArgumentGroup:
122
+ '''Find the created argument group by title, create if not exist.'''
123
+ for group in self._action_groups:
124
+ if title == group.title:
125
+ return group
126
+ return self.add_argument_group(title, description, **kwargs)
127
+
128
+ @Checker.check_name_opt
129
+ def filter_optional_name(self, *name: str) -> Sequence[str]:
130
+ '''Filter defined optional argument name.'''
131
+ option_strings: Set[str] = set()
132
+ for action in self._get_optional_actions():
133
+ option_strings.update(action.option_strings)
134
+ return [n for n in name if n not in option_strings]
135
+
136
+ @Checker.check_name_pos
137
+ def add_pos(self, name: str, **kwargs) -> None:
138
+ '''Add positional argument.'''
139
+ assert "dest" not in kwargs, \
140
+ "dest supplied twice for positional argument"
141
+ self.add_argument(name, **kwargs)
142
+
143
+ @Checker.check_name_opt
144
+ @Checker.check_nargs_opt
145
+ def add_opt(self, *name: str, **kwargs) -> None:
146
+ '''Add optional argument.'''
147
+ self.add_argument(*name, **kwargs)
148
+
149
+ @Checker.check_name_opt
150
+ def add_opt_on(self, *name: str, **kwargs) -> None:
151
+ '''Add boolean optional argument, default value is False.'''
152
+ kwargs.update({"action": "store_true"})
153
+ for key in ("type", "nargs", "const", "default", "choices"):
154
+ assert key not in kwargs, f"'{key}' is an invalid argument"
155
+ self.add_argument(*name, **kwargs)
156
+
157
+ @Checker.check_name_opt
158
+ def add_opt_off(self, *name: str, **kwargs) -> None:
159
+ '''Add boolean optional argument, default value is True.'''
160
+ kwargs.update({"action": "store_false"})
161
+ for key in ("type", "nargs", "const", "default", "choices"):
162
+ assert key not in kwargs, f"'{key}' is an invalid argument"
163
+ self.add_argument(*name, **kwargs)
164
+
165
+ def add_subparsers(self, *args, **kwargs) -> _SubParsersAction:
166
+ '''Add subparsers.'''
167
+ # subparser: cannot have multiple subparser arguments
168
+ kwargs.setdefault("title", "subcommands")
169
+ kwargs.setdefault("description", None)
170
+ kwargs.setdefault("dest", f"subcmd_{self.prog}")
171
+ kwargs.setdefault("help", None)
172
+ kwargs.setdefault("metavar", None)
173
+ return ArgumentParser.add_subparsers(self, *args, **kwargs)
174
+
175
+ def parse_args( # pylint: disable=useless-parent-delegation
176
+ self, args: Optional[Sequence[str]] = None,
177
+ namespace: Optional[Namespace] = None
178
+ ) -> Namespace:
179
+ try:
180
+ autocomplete(self) # For tab completion
181
+ except NameError: # pragma: no cover
182
+ pass # pragma: no cover
183
+ return super().parse_args(args, namespace) # type: ignore
184
+
185
+ def parse_known_args( # pylint: disable=useless-parent-delegation
186
+ self, args: Optional[Sequence[str]] = None,
187
+ namespace: Optional[Namespace] = None
188
+ ) -> Tuple[Namespace, List[str]]:
189
+ return super().parse_known_args(args, namespace) # type: ignore
190
+
191
+ def __enable_help_action(self): # pylint: disable=unused-private-member
192
+ while len(self.__help_option) > 0:
193
+ option, action = self.__help_option.popitem()
194
+ self._option_string_actions[option] = action
195
+ assert len(self.__help_option) == 0
196
+
197
+ def __disable_help_action(self): # pylint: disable=unused-private-member
198
+ assert len(self.__help_option) == 0
199
+ for option, action in self._option_string_actions.items():
200
+ if isinstance(action, _HelpAction):
201
+ self.__help_option[option] = action
202
+ for option in self.__help_option:
203
+ self._option_string_actions.pop(option)
204
+
205
+ def preparse_from_sys_argv(self) -> Namespace:
206
+ '''Preparse some arguments from sys.argv for tab completion.
207
+
208
+ When arguments contain the help option, call parse_known_args()
209
+ will print help message and exit. The command line can parse
210
+ normally.
211
+
212
+ But parameters added after calling preparse_from_sys_argv() will
213
+ not show in the help message, because the exit occurred before
214
+ adding parameters.
215
+
216
+ So, disable the help action before calling parse_known_args().
217
+ The help option will be stored, and restored after the call ends.
218
+ '''
219
+
220
+ def __dfs_enable_help_action(root: ArgParser):
221
+ root.__enable_help_action() # pylint: disable=protected-access
222
+ for _sub in root.next_parser:
223
+ __dfs_enable_help_action(_sub)
224
+
225
+ def __dfs_disable_help_action(root: ArgParser):
226
+ root.__disable_help_action() # pylint: disable=protected-access
227
+ for _sub in root.next_parser:
228
+ __dfs_disable_help_action(_sub)
229
+
230
+ try:
231
+ __dfs_disable_help_action(self.root_parser)
232
+ namespace, _ = self.root_parser.parse_known_args(self.argv)
233
+ return namespace
234
+ finally:
235
+ __dfs_enable_help_action(self.root_parser)
@@ -0,0 +1,339 @@
1
+ GNU GENERAL PUBLIC LICENSE
2
+ Version 2, June 1991
3
+
4
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
5
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
6
+ Everyone is permitted to copy and distribute verbatim copies
7
+ of this license document, but changing it is not allowed.
8
+
9
+ Preamble
10
+
11
+ The licenses for most software are designed to take away your
12
+ freedom to share and change it. By contrast, the GNU General Public
13
+ License is intended to guarantee your freedom to share and change free
14
+ software--to make sure the software is free for all its users. This
15
+ General Public License applies to most of the Free Software
16
+ Foundation's software and to any other program whose authors commit to
17
+ using it. (Some other Free Software Foundation software is covered by
18
+ the GNU Lesser General Public License instead.) You can apply it to
19
+ your programs, too.
20
+
21
+ When we speak of free software, we are referring to freedom, not
22
+ price. Our General Public Licenses are designed to make sure that you
23
+ have the freedom to distribute copies of free software (and charge for
24
+ this service if you wish), that you receive source code or can get it
25
+ if you want it, that you can change the software or use pieces of it
26
+ in new free programs; and that you know you can do these things.
27
+
28
+ To protect your rights, we need to make restrictions that forbid
29
+ anyone to deny you these rights or to ask you to surrender the rights.
30
+ These restrictions translate to certain responsibilities for you if you
31
+ distribute copies of the software, or if you modify it.
32
+
33
+ For example, if you distribute copies of such a program, whether
34
+ gratis or for a fee, you must give the recipients all the rights that
35
+ you have. You must make sure that they, too, receive or can get the
36
+ source code. And you must show them these terms so they know their
37
+ rights.
38
+
39
+ We protect your rights with two steps: (1) copyright the software, and
40
+ (2) offer you this license which gives you legal permission to copy,
41
+ distribute and/or modify the software.
42
+
43
+ Also, for each author's protection and ours, we want to make certain
44
+ that everyone understands that there is no warranty for this free
45
+ software. If the software is modified by someone else and passed on, we
46
+ want its recipients to know that what they have is not the original, so
47
+ that any problems introduced by others will not reflect on the original
48
+ authors' reputations.
49
+
50
+ Finally, any free program is threatened constantly by software
51
+ patents. We wish to avoid the danger that redistributors of a free
52
+ program will individually obtain patent licenses, in effect making the
53
+ program proprietary. To prevent this, we have made it clear that any
54
+ patent must be licensed for everyone's free use or not licensed at all.
55
+
56
+ The precise terms and conditions for copying, distribution and
57
+ modification follow.
58
+
59
+ GNU GENERAL PUBLIC LICENSE
60
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
61
+
62
+ 0. This License applies to any program or other work which contains
63
+ a notice placed by the copyright holder saying it may be distributed
64
+ under the terms of this General Public License. The "Program", below,
65
+ refers to any such program or work, and a "work based on the Program"
66
+ means either the Program or any derivative work under copyright law:
67
+ that is to say, a work containing the Program or a portion of it,
68
+ either verbatim or with modifications and/or translated into another
69
+ language. (Hereinafter, translation is included without limitation in
70
+ the term "modification".) Each licensee is addressed as "you".
71
+
72
+ Activities other than copying, distribution and modification are not
73
+ covered by this License; they are outside its scope. The act of
74
+ running the Program is not restricted, and the output from the Program
75
+ is covered only if its contents constitute a work based on the
76
+ Program (independent of having been made by running the Program).
77
+ Whether that is true depends on what the Program does.
78
+
79
+ 1. You may copy and distribute verbatim copies of the Program's
80
+ source code as you receive it, in any medium, provided that you
81
+ conspicuously and appropriately publish on each copy an appropriate
82
+ copyright notice and disclaimer of warranty; keep intact all the
83
+ notices that refer to this License and to the absence of any warranty;
84
+ and give any other recipients of the Program a copy of this License
85
+ along with the Program.
86
+
87
+ You may charge a fee for the physical act of transferring a copy, and
88
+ you may at your option offer warranty protection in exchange for a fee.
89
+
90
+ 2. You may modify your copy or copies of the Program or any portion
91
+ of it, thus forming a work based on the Program, and copy and
92
+ distribute such modifications or work under the terms of Section 1
93
+ above, provided that you also meet all of these conditions:
94
+
95
+ a) You must cause the modified files to carry prominent notices
96
+ stating that you changed the files and the date of any change.
97
+
98
+ b) You must cause any work that you distribute or publish, that in
99
+ whole or in part contains or is derived from the Program or any
100
+ part thereof, to be licensed as a whole at no charge to all third
101
+ parties under the terms of this License.
102
+
103
+ c) If the modified program normally reads commands interactively
104
+ when run, you must cause it, when started running for such
105
+ interactive use in the most ordinary way, to print or display an
106
+ announcement including an appropriate copyright notice and a
107
+ notice that there is no warranty (or else, saying that you provide
108
+ a warranty) and that users may redistribute the program under
109
+ these conditions, and telling the user how to view a copy of this
110
+ License. (Exception: if the Program itself is interactive but
111
+ does not normally print such an announcement, your work based on
112
+ the Program is not required to print an announcement.)
113
+
114
+ These requirements apply to the modified work as a whole. If
115
+ identifiable sections of that work are not derived from the Program,
116
+ and can be reasonably considered independent and separate works in
117
+ themselves, then this License, and its terms, do not apply to those
118
+ sections when you distribute them as separate works. But when you
119
+ distribute the same sections as part of a whole which is a work based
120
+ on the Program, the distribution of the whole must be on the terms of
121
+ this License, whose permissions for other licensees extend to the
122
+ entire whole, and thus to each and every part regardless of who wrote it.
123
+
124
+ Thus, it is not the intent of this section to claim rights or contest
125
+ your rights to work written entirely by you; rather, the intent is to
126
+ exercise the right to control the distribution of derivative or
127
+ collective works based on the Program.
128
+
129
+ In addition, mere aggregation of another work not based on the Program
130
+ with the Program (or with a work based on the Program) on a volume of
131
+ a storage or distribution medium does not bring the other work under
132
+ the scope of this License.
133
+
134
+ 3. You may copy and distribute the Program (or a work based on it,
135
+ under Section 2) in object code or executable form under the terms of
136
+ Sections 1 and 2 above provided that you also do one of the following:
137
+
138
+ a) Accompany it with the complete corresponding machine-readable
139
+ source code, which must be distributed under the terms of Sections
140
+ 1 and 2 above on a medium customarily used for software interchange; or,
141
+
142
+ b) Accompany it with a written offer, valid for at least three
143
+ years, to give any third party, for a charge no more than your
144
+ cost of physically performing source distribution, a complete
145
+ machine-readable copy of the corresponding source code, to be
146
+ distributed under the terms of Sections 1 and 2 above on a medium
147
+ customarily used for software interchange; or,
148
+
149
+ c) Accompany it with the information you received as to the offer
150
+ to distribute corresponding source code. (This alternative is
151
+ allowed only for noncommercial distribution and only if you
152
+ received the program in object code or executable form with such
153
+ an offer, in accord with Subsection b above.)
154
+
155
+ The source code for a work means the preferred form of the work for
156
+ making modifications to it. For an executable work, complete source
157
+ code means all the source code for all modules it contains, plus any
158
+ associated interface definition files, plus the scripts used to
159
+ control compilation and installation of the executable. However, as a
160
+ special exception, the source code distributed need not include
161
+ anything that is normally distributed (in either source or binary
162
+ form) with the major components (compiler, kernel, and so on) of the
163
+ operating system on which the executable runs, unless that component
164
+ itself accompanies the executable.
165
+
166
+ If distribution of executable or object code is made by offering
167
+ access to copy from a designated place, then offering equivalent
168
+ access to copy the source code from the same place counts as
169
+ distribution of the source code, even though third parties are not
170
+ compelled to copy the source along with the object code.
171
+
172
+ 4. You may not copy, modify, sublicense, or distribute the Program
173
+ except as expressly provided under this License. Any attempt
174
+ otherwise to copy, modify, sublicense or distribute the Program is
175
+ void, and will automatically terminate your rights under this License.
176
+ However, parties who have received copies, or rights, from you under
177
+ this License will not have their licenses terminated so long as such
178
+ parties remain in full compliance.
179
+
180
+ 5. You are not required to accept this License, since you have not
181
+ signed it. However, nothing else grants you permission to modify or
182
+ distribute the Program or its derivative works. These actions are
183
+ prohibited by law if you do not accept this License. Therefore, by
184
+ modifying or distributing the Program (or any work based on the
185
+ Program), you indicate your acceptance of this License to do so, and
186
+ all its terms and conditions for copying, distributing or modifying
187
+ the Program or works based on it.
188
+
189
+ 6. Each time you redistribute the Program (or any work based on the
190
+ Program), the recipient automatically receives a license from the
191
+ original licensor to copy, distribute or modify the Program subject to
192
+ these terms and conditions. You may not impose any further
193
+ restrictions on the recipients' exercise of the rights granted herein.
194
+ You are not responsible for enforcing compliance by third parties to
195
+ this License.
196
+
197
+ 7. If, as a consequence of a court judgment or allegation of patent
198
+ infringement or for any other reason (not limited to patent issues),
199
+ conditions are imposed on you (whether by court order, agreement or
200
+ otherwise) that contradict the conditions of this License, they do not
201
+ excuse you from the conditions of this License. If you cannot
202
+ distribute so as to satisfy simultaneously your obligations under this
203
+ License and any other pertinent obligations, then as a consequence you
204
+ may not distribute the Program at all. For example, if a patent
205
+ license would not permit royalty-free redistribution of the Program by
206
+ all those who receive copies directly or indirectly through you, then
207
+ the only way you could satisfy both it and this License would be to
208
+ refrain entirely from distribution of the Program.
209
+
210
+ If any portion of this section is held invalid or unenforceable under
211
+ any particular circumstance, the balance of the section is intended to
212
+ apply and the section as a whole is intended to apply in other
213
+ circumstances.
214
+
215
+ It is not the purpose of this section to induce you to infringe any
216
+ patents or other property right claims or to contest validity of any
217
+ such claims; this section has the sole purpose of protecting the
218
+ integrity of the free software distribution system, which is
219
+ implemented by public license practices. Many people have made
220
+ generous contributions to the wide range of software distributed
221
+ through that system in reliance on consistent application of that
222
+ system; it is up to the author/donor to decide if he or she is willing
223
+ to distribute software through any other system and a licensee cannot
224
+ impose that choice.
225
+
226
+ This section is intended to make thoroughly clear what is believed to
227
+ be a consequence of the rest of this License.
228
+
229
+ 8. If the distribution and/or use of the Program is restricted in
230
+ certain countries either by patents or by copyrighted interfaces, the
231
+ original copyright holder who places the Program under this License
232
+ may add an explicit geographical distribution limitation excluding
233
+ those countries, so that distribution is permitted only in or among
234
+ countries not thus excluded. In such case, this License incorporates
235
+ the limitation as if written in the body of this License.
236
+
237
+ 9. The Free Software Foundation may publish revised and/or new versions
238
+ of the General Public License from time to time. Such new versions will
239
+ be similar in spirit to the present version, but may differ in detail to
240
+ address new problems or concerns.
241
+
242
+ Each version is given a distinguishing version number. If the Program
243
+ specifies a version number of this License which applies to it and "any
244
+ later version", you have the option of following the terms and conditions
245
+ either of that version or of any later version published by the Free
246
+ Software Foundation. If the Program does not specify a version number of
247
+ this License, you may choose any version ever published by the Free Software
248
+ Foundation.
249
+
250
+ 10. If you wish to incorporate parts of the Program into other free
251
+ programs whose distribution conditions are different, write to the author
252
+ to ask for permission. For software which is copyrighted by the Free
253
+ Software Foundation, write to the Free Software Foundation; we sometimes
254
+ make exceptions for this. Our decision will be guided by the two goals
255
+ of preserving the free status of all derivatives of our free software and
256
+ of promoting the sharing and reuse of software generally.
257
+
258
+ NO WARRANTY
259
+
260
+ 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
261
+ FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
262
+ OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
263
+ PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
264
+ OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
265
+ MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
266
+ TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
267
+ PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
268
+ REPAIR OR CORRECTION.
269
+
270
+ 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
271
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
272
+ REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
273
+ INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
274
+ OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
275
+ TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
276
+ YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
277
+ PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
278
+ POSSIBILITY OF SUCH DAMAGES.
279
+
280
+ END OF TERMS AND CONDITIONS
281
+
282
+ How to Apply These Terms to Your New Programs
283
+
284
+ If you develop a new program, and you want it to be of the greatest
285
+ possible use to the public, the best way to achieve this is to make it
286
+ free software which everyone can redistribute and change under these terms.
287
+
288
+ To do so, attach the following notices to the program. It is safest
289
+ to attach them to the start of each source file to most effectively
290
+ convey the exclusion of warranty; and each file should have at least
291
+ the "copyright" line and a pointer to where the full notice is found.
292
+
293
+ <one line to give the program's name and a brief idea of what it does.>
294
+ Copyright (C) <year> <name of author>
295
+
296
+ This program is free software; you can redistribute it and/or modify
297
+ it under the terms of the GNU General Public License as published by
298
+ the Free Software Foundation; either version 2 of the License, or
299
+ (at your option) any later version.
300
+
301
+ This program is distributed in the hope that it will be useful,
302
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
303
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
304
+ GNU General Public License for more details.
305
+
306
+ You should have received a copy of the GNU General Public License along
307
+ with this program; if not, write to the Free Software Foundation, Inc.,
308
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
309
+
310
+ Also add information on how to contact you by electronic and paper mail.
311
+
312
+ If the program is interactive, make it output a short notice like this
313
+ when it starts in an interactive mode:
314
+
315
+ Gnomovision version 69, Copyright (C) year name of author
316
+ Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
317
+ This is free software, and you are welcome to redistribute it
318
+ under certain conditions; type `show c' for details.
319
+
320
+ The hypothetical commands `show w' and `show c' should show the appropriate
321
+ parts of the General Public License. Of course, the commands you use may
322
+ be called something other than `show w' and `show c'; they could even be
323
+ mouse-clicks or menu items--whatever suits your program.
324
+
325
+ You should also get your employer (if you work as a programmer) or your
326
+ school, if any, to sign a "copyright disclaimer" for the program, if
327
+ necessary. Here is a sample; alter the names:
328
+
329
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the program
330
+ `Gnomovision' (which makes passes at compilers) written by James Hacker.
331
+
332
+ <signature of Ty Coon>, 1 April 1989
333
+ Ty Coon, President of Vice
334
+
335
+ This General Public License does not permit incorporating your program into
336
+ proprietary programs. If your program is a subroutine library, you may
337
+ consider it more useful to permit linking proprietary applications with the
338
+ library. If this is what you want to do, use the GNU Lesser General
339
+ Public License instead of this License.
@@ -0,0 +1,23 @@
1
+ Metadata-Version: 2.1
2
+ Name: xkits-command
3
+ Version: 0.1
4
+ Summary: Command line module
5
+ Home-page: https://github.com/bondbox/xcommand/
6
+ Author: Mingzhe Zou
7
+ Author-email: zoumingzhe@outlook.com
8
+ License: GPLv2
9
+ Project-URL: Source Code, https://github.com/bondbox/xcommand/
10
+ Project-URL: Bug Tracker, https://github.com/bondbox/xcommand/issues
11
+ Project-URL: Documentation, https://github.com/bondbox/xcommand/
12
+ Keywords: command-line,argparse,shell,bash,terminal
13
+ Platform: any
14
+ Classifier: Programming Language :: Python
15
+ Classifier: Programming Language :: Python :: 3
16
+ Requires-Python: >=3.8
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Requires-Dist: xkits-logger >=0.1
20
+
21
+ # xcommand
22
+
23
+ Command line module
@@ -0,0 +1,10 @@
1
+ xkits_command/__init__.py,sha256=wXuMzN8SfVZw0wIyFZmVd37SmxhPK6lpceGgx3xDmeQ,447
2
+ xkits_command/actuator.py,sha256=C3Qtw3AMW87KZzz1hkZE5If9LySyqP13FlArEQkq1lI,24230
3
+ xkits_command/attribute.py,sha256=WUpEItekibbFE8XZ9kVNPmyUML66XKA8JNg7LQG_kl0,240
4
+ xkits_command/parser.py,sha256=XdI7gBuPyJO7vs8Zf3KC-9jB5K_yoANWQ_uOM_zEn38,9095
5
+ xkits_command-0.1.dist-info/LICENSE,sha256=gXf5dRMhNSbfLPYYTY_5hsZ1r7UU1OaKQEAQUhuIBkM,18092
6
+ xkits_command-0.1.dist-info/METADATA,sha256=uxGh3zB_LUGKZxfHo-GXGolmZI35CRkSP3sgFI2gmxc,710
7
+ xkits_command-0.1.dist-info/WHEEL,sha256=pWvVuNuBTVmNV7Lp2jMAgt1NplTICeFdl1SW8U3MWN4,109
8
+ xkits_command-0.1.dist-info/top_level.txt,sha256=cTjduFaptSrsDAiu3H_1QR_eqZjytYwABnaA1oiE2VU,14
9
+ xkits_command-0.1.dist-info/zip-safe,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
10
+ xkits_command-0.1.dist-info/RECORD,,
@@ -0,0 +1,6 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (70.3.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py2-none-any
5
+ Tag: py3-none-any
6
+
@@ -0,0 +1 @@
1
+ xkits_command
@@ -0,0 +1 @@
1
+