|
12 | 12 | # See the License for the specific language governing permissions and
|
13 | 13 | # limitations under the License.
|
14 | 14 |
|
| 15 | +import argparse |
| 16 | +import dataclasses |
| 17 | +import logging |
15 | 18 | import sys
|
16 | 19 | import typing
|
17 | 20 | from collections.abc import Sequence
|
18 | 21 |
|
19 | 22 | type ExitCode = int
|
20 | 23 |
|
21 | 24 | def main(args: Sequence[str], stdout: typing.TextIO, stderr: typing.TextIO) -> ExitCode:
|
| 25 | + try: |
| 26 | + parsed_args = parse_args(args[0], args[1:], stdout) |
| 27 | + except MyArgumentParser.Error as e: |
| 28 | + if e.exit_code != 0: |
| 29 | + print(f"ERROR: invalid command-line arguments: {e}", file=stderr) |
| 30 | + print(f"Run with --help for help", file=stderr) |
| 31 | + return e.exit_code |
| 32 | + |
22 | 33 | return 0
|
23 | 34 |
|
| 35 | +@dataclasses.dataclass(frozen=True) |
| 36 | +class GetIssueNumberCommand: |
| 37 | + github_ref: str |
| 38 | + github_event_name: str |
| 39 | + default_github_issue: int |
| 40 | + |
| 41 | +@dataclasses.dataclass(frozen=True) |
| 42 | +class ParsedArgs: |
| 43 | + log_level: int |
| 44 | + command: GetIssueNumberCommand |
| 45 | + |
| 46 | +class MyArgumentParser(argparse.ArgumentParser): |
| 47 | + |
| 48 | + def __init__(self, prog: str, stdout: typing.TextIO) -> None: |
| 49 | + super().__init__(prog=prog, usage="%(prog)s <command> [options]") |
| 50 | + self.stdout = stdout |
| 51 | + |
| 52 | + @typing.override |
| 53 | + def exit(self, status: int = 0, message: str | None = None) -> typing.Never: |
| 54 | + raise self.Error(exit_code=status, message=message) |
| 55 | + |
| 56 | + @typing.override |
| 57 | + def error(self, message: str) -> typing.Never: |
| 58 | + self.exit(2, message) |
| 59 | + |
| 60 | + @typing.override |
| 61 | + def print_usage(self, file: typing.TextIO | None = None) -> None: |
| 62 | + file = file if file is not None else self.stdout |
| 63 | + super().print_usage(file) |
| 64 | + |
| 65 | + @typing.override |
| 66 | + def print_help(self, file: typing.TextIO | None =None) -> None: |
| 67 | + file = file if file is not None else self.stdout |
| 68 | + super().print_help(file) |
| 69 | + |
| 70 | + class Error(Exception): |
| 71 | + def __init__(self, exit_code: ExitCode, message: str | None) -> None: |
| 72 | + super().__init__(message) |
| 73 | + self.exit_code = exit_code |
| 74 | + |
| 75 | + |
| 76 | +def parse_args(prog: str, args: Sequence[str], stdout: typing.TextIO) -> ExitCode: |
| 77 | + arg_parser = MyArgumentParser(prog, stdout) |
| 78 | + parsed_args = arg_parser.parse_args(args) |
| 79 | + |
24 | 80 | if __name__ == "__main__":
|
25 | 81 | try:
|
26 | 82 | exit_code = main(sys.argv, sys.stdout, sys.stderr)
|
|
0 commit comments