| 1 |
# Copyright (c) 2004 Gavin E. Crooks <[email protected]> |
| 2 |
# |
| 3 |
# This software is distributed under the MIT Open Source License. |
| 4 |
# <http://www.opensource.org/licenses/mit-license.html> |
| 5 |
# |
| 6 |
# Permission is hereby granted, free of charge, to any person obtaining a |
| 7 |
# copy of this software and associated documentation files (the "Software"), |
| 8 |
# to deal in the Software without restriction, including without limitation |
| 9 |
# the rights to use, copy, modify, merge, publish, distribute, sublicense, |
| 10 |
# and/or sell copies of the Software, and to permit persons to whom the |
| 11 |
# Software is furnished to do so, subject to the following conditions: |
| 12 |
# |
| 13 |
# The above copyright notice and this permission notice shall be included |
| 14 |
# in all copies or substantial portions of the Software. |
| 15 |
# |
| 16 |
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 17 |
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 18 |
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 19 |
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 20 |
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 21 |
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN |
| 22 |
# THE SOFTWARE. |
| 23 |
# |
| 24 |
|
| 25 |
"""Custom extensions to OptionParse for parsing command line options.""" |
| 26 |
|
| 27 |
# FIXME: Docstring |
| 28 |
|
| 29 |
# TODO: Add profiling option |
| 30 |
|
| 31 |
# DeOptionParser : |
| 32 |
# |
| 33 |
# http://docs.python.org/lib/module-optparse.html |
| 34 |
# |
| 35 |
# Random_options : |
| 36 |
# Set random generator and seed. Use options.random as |
| 37 |
# source of random numbers |
| 38 |
# Copyright : |
| 39 |
# print copyright information |
| 40 |
|
| 41 |
# Documentation : |
| 42 |
# print extended document information |
| 43 |
# |
| 44 |
# Additional file_in and file_out types |
| 45 |
|
| 46 |
import sys |
| 47 |
from copy import copy |
| 48 |
from optparse import IndentedHelpFormatter, Option, OptionParser, OptionValueError |
| 49 |
from typing import Any, Iterable, Optional, TextIO, Type |
| 50 |
|
| 51 |
|
| 52 |
def _copyright_callback( |
| 53 |
option: Any, opt: Any, value: Any, parser: "DeOptionParser" |
| 54 |
) -> None: |
| 55 |
if option or opt or value or parser: |
| 56 |
pass # Shut up lint checker |
| 57 |
print(parser.copyright) |
| 58 |
sys.exit() |
| 59 |
|
| 60 |
|
| 61 |
def _doc_callback(option: Any, opt: Any, value: Any, parser: "DeOptionParser") -> None: |
| 62 |
if option or opt or value or parser: |
| 63 |
pass # Shut up lint checker |
| 64 |
print(parser.long_description) |
| 65 |
sys.exit() |
| 66 |
|
| 67 |
|
| 68 |
class DeHelpFormatter(IndentedHelpFormatter): |
| 69 |
def __init__( |
| 70 |
self, |
| 71 |
indent_increment: int = 2, |
| 72 |
max_help_position: int = 32, |
| 73 |
width: int = 78, |
| 74 |
short_first: int = 1, |
| 75 |
): |
| 76 |
IndentedHelpFormatter.__init__( |
| 77 |
self, indent_increment, max_help_position, width, short_first |
| 78 |
) |
| 79 |
|
| 80 |
def format_option_strings(self, option: Option) -> str: |
| 81 |
"""Return a comma-separated list of option strings & metavariables.""" |
| 82 |
if option.takes_value(): |
| 83 |
dest = option.dest |
| 84 |
assert dest is not None |
| 85 |
metavar = option.metavar or dest.upper() |
| 86 |
short_opts = option._short_opts |
| 87 |
long_opts = [lopt + " " + metavar for lopt in option._long_opts] |
| 88 |
else: |
| 89 |
short_opts = option._short_opts |
| 90 |
long_opts = option._long_opts |
| 91 |
|
| 92 |
if not short_opts: |
| 93 |
short_opts = [ |
| 94 |
" ", |
| 95 |
] |
| 96 |
|
| 97 |
if self.short_first: |
| 98 |
opts = short_opts + long_opts |
| 99 |
else: |
| 100 |
opts = long_opts + short_opts |
| 101 |
|
| 102 |
return " ".join(opts) |
| 103 |
|
| 104 |
|
| 105 |
def _check_file_in(option: Any, opt: Any, value: str) -> TextIO: |
| 106 |
if option or opt or value: |
| 107 |
pass # Shut up lint checker |
| 108 |
try: |
| 109 |
return open(value, "r") |
| 110 |
except IOError: |
| 111 |
raise OptionValueError("option %s: cannot open file: %s" % (opt, value)) |
| 112 |
|
| 113 |
|
| 114 |
def _check_file_out(option: Any, opt: Any, value: str) -> TextIO: |
| 115 |
if option or opt or value: |
| 116 |
pass # Shut up lint checker |
| 117 |
try: |
| 118 |
return open(value, "w+") |
| 119 |
except IOError: |
| 120 |
raise OptionValueError("option %s: cannot open file: %s" % (opt, value)) |
| 121 |
|
| 122 |
|
| 123 |
def _check_boolean(option: Any, opt: Any, value: str) -> bool: |
| 124 |
if option or opt or value: |
| 125 |
pass # Shut up lint checker |
| 126 |
v = value.lower() |
| 127 |
choices = { |
| 128 |
"no": False, |
| 129 |
"false": False, |
| 130 |
"0": False, |
| 131 |
"yes": True, |
| 132 |
"true": True, |
| 133 |
"1": True, |
| 134 |
} |
| 135 |
try: |
| 136 |
return choices[v] |
| 137 |
except KeyError: |
| 138 |
raise OptionValueError( |
| 139 |
"option %s: invalid choice: '%s' (choose from 'yes' or 'no', 'true' or 'false')" |
| 140 |
% (opt, value) |
| 141 |
) |
| 142 |
|
| 143 |
|
| 144 |
def _check_dict(option: Any, opt: Any, value: str) -> str: |
| 145 |
if option or opt or value: |
| 146 |
pass # Shut up lint checker |
| 147 |
v = value.lower() |
| 148 |
choices = option.choices |
| 149 |
try: |
| 150 |
return choices[v] |
| 151 |
except KeyError: |
| 152 |
raise OptionValueError( |
| 153 |
"option %s: invalid choice: '%s' (choose from '%s')" |
| 154 |
% (opt, value, "', '".join(choices)) |
| 155 |
) |
| 156 |
|
| 157 |
|
| 158 |
class DeOption(Option): |
| 159 |
TYPES = Option.TYPES + ("file_in", "file_out", "boolean", "dict") |
| 160 |
TYPE_CHECKER = copy(Option.TYPE_CHECKER) |
| 161 |
TYPE_CHECKER["file_in"] = _check_file_in |
| 162 |
TYPE_CHECKER["file_out"] = _check_file_out |
| 163 |
TYPE_CHECKER["boolean"] = _check_boolean |
| 164 |
TYPE_CHECKER["dict"] = _check_dict |
| 165 |
choices = None |
| 166 |
|
| 167 |
def _new_check_choice(self) -> None: |
| 168 |
if self.type == "dict": |
| 169 |
if self.choices is None: |
| 170 |
raise OptionValueError( |
| 171 |
"must supply a dictionary of choices for type 'dict'" |
| 172 |
) |
| 173 |
elif not isinstance(self.choices, dict): |
| 174 |
raise OptionValueError( |
| 175 |
"choices must be a dictionary ('%s' supplied)" |
| 176 |
% str(type(self.choices)).split("'")[1] |
| 177 |
) |
| 178 |
return |
| 179 |
self._check_choice() |
| 180 |
|
| 181 |
# Have to override _check_choices so that we can parse |
| 182 |
# a dict through to check_dict |
| 183 |
CHECK_METHODS = Option.CHECK_METHODS |
| 184 |
CHECK_METHODS[2] = _new_check_choice # type: ignore |
| 185 |
|
| 186 |
|
| 187 |
class DeOptionParser(OptionParser): |
| 188 |
def __init__( |
| 189 |
self, |
| 190 |
usage: Optional[str] = None, |
| 191 |
option_list: Optional[Iterable[Option]] = None, |
| 192 |
option_class: Type[Option] = DeOption, |
| 193 |
version: Optional[str] = None, |
| 194 |
conflict_handler: str = "error", |
| 195 |
description: Optional[str] = None, |
| 196 |
long_description: Optional[str] = None, |
| 197 |
formatter: IndentedHelpFormatter = DeHelpFormatter(), |
| 198 |
add_help_option: bool = True, |
| 199 |
prog: Optional[str] = None, |
| 200 |
copyright: Optional[str] = None, |
| 201 |
add_verbose_options: bool = True, |
| 202 |
): |
| 203 |
OptionParser.__init__( |
| 204 |
self, |
| 205 |
usage, |
| 206 |
option_list, |
| 207 |
option_class, |
| 208 |
version, |
| 209 |
conflict_handler, |
| 210 |
description, |
| 211 |
formatter, |
| 212 |
add_help_option, |
| 213 |
prog, |
| 214 |
) |
| 215 |
|
| 216 |
if long_description: |
| 217 |
self.long_description = long_description |
| 218 |
self.add_option( |
| 219 |
"--doc", |
| 220 |
action="callback", |
| 221 |
callback=_doc_callback, |
| 222 |
help="Detailed documentation", |
| 223 |
) |
| 224 |
|
| 225 |
if copyright: |
| 226 |
self.copyright = copyright |
| 227 |
self.add_option( |
| 228 |
"--copyright", action="callback", callback=_copyright_callback, help="" |
| 229 |
) |
| 230 |
|
| 231 |
if add_verbose_options: |
| 232 |
self.add_option( |
| 233 |
"-q", |
| 234 |
"--quite", |
| 235 |
action="store_false", |
| 236 |
dest="verbose", |
| 237 |
default=False, |
| 238 |
help="Run quietly (default)", |
| 239 |
) |
| 240 |
|
| 241 |
self.add_option( |
| 242 |
"-v", |
| 243 |
"--verbose", |
| 244 |
action="store_true", |
| 245 |
dest="verbose", |
| 246 |
default=False, |
| 247 |
help="Verbose output (Not quite)", |
| 248 |
) |