File: common_options.py

package info (click to toggle)
python-pbcommand 2.1.1%2Bgit20231020.28d1635-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,016 kB
  • sloc: python: 7,676; makefile: 220; sh: 73
file content (132 lines) | stat: -rw-r--r-- 3,861 bytes parent folder | download | duplicates (3)
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
"""
Common options and utils that can me used in commandline utils
"""

import argparse
import logging
import sys


def add_debug_option(p):
    p.add_argument("--pdb", action="store_true", default=False,
                   help="Enable Python debugger")
    return p


def add_log_debug_option(p):
    """This requires the log-level option"""
    p.add_argument('--debug', action="store_true", default=False,
                   help="Alias for setting log level to DEBUG")
    return p


def add_log_quiet_option(p):
    """This requires the log-level option"""
    p.add_argument(
        '--quiet',
        action="store_true",
        default=False,
        help="Alias for setting log level to CRITICAL to suppress output.")
    return p


def add_log_verbose_option(p):
    p.add_argument(
        "-v",
        "--verbose",
        dest="verbosity",
        action="count",
        help="Set the verbosity level.")
    return p


def add_log_level_option(p, default_level='INFO'):
    """Add logging level with a default value"""
    if isinstance(default_level, int):
        default_level = logging.getLevelName(default_level)
    p.add_argument('--log-level', choices=('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'),
                   default=default_level, help="Set log level")
    return p


def add_log_file_option(p):
    p.add_argument('--log-file', default=None, type=str,
                   help="Write the log to file. Default(None) will write to stdout.")
    return p


def add_nproc_option(p, default=1):
    p.add_argument("-j", "--nproc", type=int, default=default,
                   help="Number of processors to use")
    return p


def add_base_options(p, default_level='INFO'):
    """Add the core logging options to the parser and set the default log level

    If you don't want the default log behavior to go to stdout, then set
    the default log level to be "ERROR". This will essentially suppress all
    output to stdout.

    Default behavior will only emit to stderr. This is essentially a '--quiet'
    default mode.

    my-tool --my-opt=1234 file_in.txt

    To override the default behavior:

    my-tool --my-opt=1234 --log-level=INFO file_in.txt

    Or write the file to an explict log file

    my-tool --my-opt=1234 --log-level=DEBUG --log-file=file.log file_in.txt

    """
    # This should automatically/required be added to be added from
    # get_default_argparser
    add_log_file_option(p)
    p_log = p.add_mutually_exclusive_group()
    add_log_verbose_option(add_log_quiet_option(add_log_debug_option(
        add_log_level_option(p_log, default_level=default_level))))
    return p


def add_common_options(p, default_level='INFO'):
    """
    New model for 3.1 release. This should replace add_base_options
    """
    return add_log_quiet_option(add_log_debug_option(
        add_log_level_option(add_log_file_option(p), default_level=default_level)))


def _to_print_message_action(msg):

    class PrintMessageAction(argparse.Action):

        """Print message and exit"""

        def __call__(self, parser, namespace, values, option_string=None):
            sys.stdout.write(msg + "\n")
            sys.exit(0)

    return PrintMessageAction


def add_subcomponent_versions_option(p, subcomponents):
    """Add subcomponents to a subparser to provide more information
     about the tools dependencies.

     Subcomponents must be provided as a list of tuples (component, version)
     """
    max_length = max(len(x) for x, _ in subcomponents)
    pad = 2
    msg = "\n" .join([" : ".join([x.rjust(max_length + pad), y])
                      for x, y in subcomponents])

    action = _to_print_message_action(msg)
    p.add_argument("--versions",
                   nargs=0,
                   help="Show versions of individual components",
                   action=action)

    return p