File: argparse_wrappers.py

package info (click to toggle)
python-wilderness 0.1.10-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 368 kB
  • sloc: python: 2,175; makefile: 152; sh: 9
file content (76 lines) | stat: -rw-r--r-- 2,173 bytes parent folder | download
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
# -*- coding: utf-8 -*-

"""ArgumentParser override

Author: G.J.J. van den Burg
License: See the LICENSE file.
Copyright: 2021, G.J.J. van den Burg

This file is part of Wilderness.

"""

import argparse
import sys

from typing import TYPE_CHECKING
from typing import Optional

if TYPE_CHECKING:
    import wilderness.command


class ArgumentParser(argparse.ArgumentParser):
    def __init__(self, *args, exit_on_error=True, **kwargs):
        super().__init__(*args, **kwargs)
        self.exit_on_error = exit_on_error
        self._exit_called = False

    def exit(self, status: Optional[int] = 0, message: Optional[str] = None):
        if message:
            self._print_message(message, sys.stderr)
        self._exit_called = True
        if self.exit_on_error:
            sys.exit(status)


class ArgumentGroup:
    def __init__(self, group: argparse._ArgumentGroup):
        self._group = group
        self._command: Optional[wilderness.command.Command] = None

    @property
    def command(self) -> Optional["wilderness.command.Command"]:
        return self._command

    @command.setter
    def command(self, command: "wilderness.command.Command"):
        self._command = command

    def add_argument(self, *args, **kwargs):
        assert not self.command is None
        description = kwargs.pop("description", None)
        action = self._group.add_argument(*args, **kwargs)
        self.command.argument_help[action.dest] = description
        return action


class MutuallyExclusiveGroup:
    def __init__(self, meg: argparse._MutuallyExclusiveGroup):
        self._meg = meg
        self._command: Optional[wilderness.command.Command] = None

    @property
    def command(self) -> Optional["wilderness.command.Command"]:
        return self._command

    @command.setter
    def command(self, command: "wilderness.command.Command"):
        self._command = command

    def add_argument(self, *args, **kwargs):
        assert not self.command is None
        description = kwargs.pop("description", None)
        action = self._meg.add_argument(*args, **kwargs)
        self.command.argument_help[action.dest] = description
        return action