forked from OCP-on-NERC/python-batchtools
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasecommand.py
More file actions
62 lines (48 loc) · 1.63 KB
/
basecommand.py
File metadata and controls
62 lines (48 loc) · 1.63 KB
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
# pyright: reportExplicitAny=false, reportAny=false
import abc
from typing import Protocol
from typing import Any
from typing_extensions import override
import argparse
class SubParserFactory(Protocol):
"""
This is here to make type checkers happy. Since argparse._SubParsersAction
is a private class, we can't use it as a type hint, so we use this instead.
"""
def add_parser(
self,
name: str,
*,
deprecated: bool = False,
**kwargs: Any,
) -> argparse.ArgumentParser: ...
class ArgumentDefaultsHelpFormatter(argparse.ArgumentDefaultsHelpFormatter):
"""Provide the behavior of both argparse.ArgumentDefaultsHelpFormatter
and argparse.RawDescriptionHelpFormatter. This means that argparse will
care of documenting default values for us, and it won't reformat our
carefully crafted help text."""
@override
def _fill_text(
self, text: str, width: int | None = None, indent: str | None = None
):
return "".join(indent + line for line in text.splitlines(keepends=True))
class Command(abc.ABC):
"""
Base class for all command implementations.
"""
name: str
help: str
description: str | None = None
@classmethod
def build_parser(cls, subparsers: SubParserFactory) -> argparse.ArgumentParser:
p = subparsers.add_parser(
cls.name,
help=cls.help,
description=cls.__doc__,
formatter_class=ArgumentDefaultsHelpFormatter,
)
return p
@staticmethod
@abc.abstractmethod
def run(args: argparse.Namespace) -> None:
raise NotImplementedError()