Migrate Python optparse to argparse

patch by Vineet Gali; reviewed by Stefan Miklosovic and Brandon Williams for CASSANDRA-17914
This commit is contained in:
vgali7 2023-07-10 09:27:49 -04:00 committed by Stefan Miklosovic
parent 2584f4f070
commit b4b9f31983
No known key found for this signature in database
GPG Key ID: 32F35CB2F546D93E
2 changed files with 71 additions and 68 deletions

View File

@ -1,4 +1,5 @@
4.0.12 4.0.12
* Migrate Python optparse to argparse (CASSANDRA-17914)
Merged from 3.11: Merged from 3.11:
* Moved jflex from runtime to build dependencies (CASSANDRA-18664) * Moved jflex from runtime to build dependencies (CASSANDRA-18664)
Merged from 3.0: Merged from 3.0:

View File

@ -22,7 +22,7 @@ import cmd
import codecs import codecs
import csv import csv
import getpass import getpass
import optparse import argparse
import os import os
import platform import platform
import re import re
@ -189,51 +189,52 @@ defaults can be changed by setting $CQLSH_HOST and/or $CQLSH_PORT. When a
host (and optional port number) are given on the command line, they take host (and optional port number) are given on the command line, they take
precedence over any defaults.""" % globals() precedence over any defaults.""" % globals()
parser = optparse.OptionParser(description=description, epilog=epilog, parser = argparse.ArgumentParser(description=description, epilog=epilog,
usage="Usage: %prog [options] [host [port]]", usage="Usage: %(prog)s [options] [host [port]]",
version='cqlsh ' + version) prog='cqlsh')
parser.add_option("-C", "--color", action='store_true', dest='color', parser.add_argument('-v', '--version', action='version', version='cqlsh ' + version)
help='Always use color output') parser.add_argument("-C", "--color", action='store_true', dest='color',
parser.add_option("--no-color", action='store_false', dest='color', help='Always use color output')
help='Never use color output') parser.add_argument("--no-color", action='store_false', dest='color',
parser.add_option("--browser", dest='browser', help="""The browser to use to display CQL help, where BROWSER can be: help='Never use color output')
parser.add_argument("--browser", dest='browser', help="""The browser to use to display CQL help, where BROWSER can be:
- one of the supported browsers in https://docs.python.org/3/library/webbrowser.html. - one of the supported browsers in https://docs.python.org/3/library/webbrowser.html.
- browser path followed by %s, example: /usr/bin/google-chrome-stable %s""") - browser path followed by %s, example: /usr/bin/google-chrome-stable %s""")
parser.add_option('--ssl', action='store_true', help='Use SSL', default=False) parser.add_argument('--ssl', action='store_true', help='Use SSL', default=False)
parser.add_option("-u", "--username", help="Authenticate as user.") parser.add_argument("-u", "--username", help="Authenticate as user.")
parser.add_option("-p", "--password", help="Authenticate using password.") parser.add_argument("-p", "--password", help="Authenticate using password.")
parser.add_option('-k', '--keyspace', help='Authenticate to the given keyspace.') parser.add_argument('-k', '--keyspace', help='Authenticate to the given keyspace.')
parser.add_option("-f", "--file", help="Execute commands from FILE, then exit") parser.add_argument("-f", "--file", help="Execute commands from FILE, then exit")
parser.add_option('--debug', action='store_true', parser.add_argument('--debug', action='store_true',
help='Show additional debugging information') help='Show additional debugging information')
parser.add_option('--coverage', action='store_true', parser.add_argument('--coverage', action='store_true',
help='Collect coverage data') help='Collect coverage data')
parser.add_option("--encoding", help="Specify a non-default encoding for output." parser.add_argument("--encoding", help="Specify a non-default encoding for output."
+ " (Default: %s)" % (UTF8,)) + " (Default: %s)" % (UTF8,))
parser.add_option("--cqlshrc", help="Specify an alternative cqlshrc file location.") parser.add_argument("--cqlshrc", help="Specify an alternative cqlshrc file location.")
parser.add_option('--cqlversion', default=None, parser.add_argument('--cqlversion', default=None,
help='Specify a particular CQL version, ' help='Specify a particular CQL version, '
'by default the highest version supported by the server will be used.' 'by default the highest version supported by the server will be used.'
' Examples: "3.0.3", "3.1.0"') ' Examples: "3.0.3", "3.1.0"')
parser.add_option("--protocol-version", type="int", default=None, parser.add_argument("--protocol-version", type=int, default=None,
help='Specify a specific protcol version otherwise the client will default and downgrade as necessary') help='Specify a specific protcol version otherwise the client will default and downgrade as necessary')
parser.add_option("-e", "--execute", help='Execute the statement and quit.') parser.add_argument("-e", "--execute", help='Execute the statement and quit.')
parser.add_option("--connect-timeout", default=DEFAULT_CONNECT_TIMEOUT_SECONDS, dest='connect_timeout', parser.add_argument("--connect-timeout", default=DEFAULT_CONNECT_TIMEOUT_SECONDS, dest='connect_timeout',
help='Specify the connection timeout in seconds (default: %default seconds).') help='Specify the connection timeout in seconds (default: %default seconds).')
parser.add_option("--request-timeout", default=DEFAULT_REQUEST_TIMEOUT_SECONDS, dest='request_timeout', parser.add_argument("--request-timeout", default=DEFAULT_REQUEST_TIMEOUT_SECONDS, dest='request_timeout',
help='Specify the default request timeout in seconds (default: %default seconds).') help='Specify the default request timeout in seconds (default: %default seconds).')
parser.add_option("-t", "--tty", action='store_true', dest='tty', parser.add_argument("-t", "--tty", action='store_true', dest='tty',
help='Force tty mode (command prompt).') help='Force tty mode (command prompt).')
cfarguments, args = parser.parse_known_args()
optvalues = optparse.Values()
(options, arguments) = parser.parse_args(sys.argv[1:], values=optvalues)
# BEGIN history/config definition # BEGIN history/config definition
HISTORY_DIR = os.path.expanduser(os.path.join('~', '.cassandra')) HISTORY_DIR = os.path.expanduser(os.path.join('~', '.cassandra'))
if hasattr(options, 'cqlshrc'): if cfarguments.cqlshrc is not None:
CONFIG_FILE = options.cqlshrc CONFIG_FILE = cfarguments.cqlshrc
if not os.path.exists(CONFIG_FILE): if not os.path.exists(CONFIG_FILE):
print('\nWarning: Specified cqlshrc location `%s` does not exist. Using `%s` instead.\n' % (CONFIG_FILE, HISTORY_DIR)) print('\nWarning: Specified cqlshrc location `%s` does not exist. Using `%s` instead.\n' % (CONFIG_FILE, HISTORY_DIR))
CONFIG_FILE = os.path.join(HISTORY_DIR, 'cqlshrc') CONFIG_FILE = os.path.join(HISTORY_DIR, 'cqlshrc')
@ -2114,47 +2115,48 @@ def read_options(cmdlineargs, environment):
rawconfigs = configparser.RawConfigParser() rawconfigs = configparser.RawConfigParser()
rawconfigs.read(CONFIG_FILE) rawconfigs.read(CONFIG_FILE)
optvalues = optparse.Values() argvalues = argparse.Namespace()
optvalues.username = option_with_default(configs.get, 'authentication', 'username')
optvalues.password = option_with_default(rawconfigs.get, 'authentication', 'password') argvalues.username = option_with_default(configs.get, 'authentication', 'username')
optvalues.keyspace = option_with_default(configs.get, 'authentication', 'keyspace') argvalues.password = option_with_default(rawconfigs.get, 'authentication', 'password')
optvalues.browser = option_with_default(configs.get, 'ui', 'browser', None) argvalues.keyspace = option_with_default(configs.get, 'authentication', 'keyspace')
optvalues.completekey = option_with_default(configs.get, 'ui', 'completekey', argvalues.browser = option_with_default(configs.get, 'ui', 'browser', None)
argvalues.completekey = option_with_default(configs.get, 'ui', 'completekey',
DEFAULT_COMPLETEKEY) DEFAULT_COMPLETEKEY)
optvalues.color = option_with_default(configs.getboolean, 'ui', 'color') argvalues.color = option_with_default(configs.getboolean, 'ui', 'color')
optvalues.time_format = raw_option_with_default(configs, 'ui', 'time_format', argvalues.time_format = raw_option_with_default(configs, 'ui', 'time_format',
DEFAULT_TIMESTAMP_FORMAT) DEFAULT_TIMESTAMP_FORMAT)
optvalues.nanotime_format = raw_option_with_default(configs, 'ui', 'nanotime_format', argvalues.nanotime_format = raw_option_with_default(configs, 'ui', 'nanotime_format',
DEFAULT_NANOTIME_FORMAT) DEFAULT_NANOTIME_FORMAT)
optvalues.date_format = raw_option_with_default(configs, 'ui', 'date_format', argvalues.date_format = raw_option_with_default(configs, 'ui', 'date_format',
DEFAULT_DATE_FORMAT) DEFAULT_DATE_FORMAT)
optvalues.float_precision = option_with_default(configs.getint, 'ui', 'float_precision', argvalues.float_precision = option_with_default(configs.getint, 'ui', 'float_precision',
DEFAULT_FLOAT_PRECISION) DEFAULT_FLOAT_PRECISION)
optvalues.double_precision = option_with_default(configs.getint, 'ui', 'double_precision', argvalues.double_precision = option_with_default(configs.getint, 'ui', 'double_precision',
DEFAULT_DOUBLE_PRECISION) DEFAULT_DOUBLE_PRECISION)
optvalues.field_size_limit = option_with_default(configs.getint, 'csv', 'field_size_limit', csv.field_size_limit()) argvalues.field_size_limit = option_with_default(configs.getint, 'csv', 'field_size_limit', csv.field_size_limit())
optvalues.max_trace_wait = option_with_default(configs.getfloat, 'tracing', 'max_trace_wait', argvalues.max_trace_wait = option_with_default(configs.getfloat, 'tracing', 'max_trace_wait',
DEFAULT_MAX_TRACE_WAIT) DEFAULT_MAX_TRACE_WAIT)
optvalues.timezone = option_with_default(configs.get, 'ui', 'timezone', None) argvalues.timezone = option_with_default(configs.get, 'ui', 'timezone', None)
optvalues.debug = False argvalues.debug = False
optvalues.coverage = False argvalues.coverage = False
if 'CQLSH_COVERAGE' in environment.keys(): if 'CQLSH_COVERAGE' in environment.keys():
optvalues.coverage = True argvalues.coverage = True
optvalues.file = None argvalues.file = None
optvalues.ssl = option_with_default(configs.getboolean, 'connection', 'ssl', DEFAULT_SSL) argvalues.ssl = option_with_default(configs.getboolean, 'connection', 'ssl', DEFAULT_SSL)
optvalues.encoding = option_with_default(configs.get, 'ui', 'encoding', UTF8) argvalues.encoding = option_with_default(configs.get, 'ui', 'encoding', UTF8)
optvalues.tty = option_with_default(configs.getboolean, 'ui', 'tty', sys.stdin.isatty()) argvalues.tty = option_with_default(configs.getboolean, 'ui', 'tty', sys.stdin.isatty())
optvalues.protocol_version = option_with_default(configs.getint, 'protocol', 'version', None) argvalues.protocol_version = option_with_default(configs.getint, 'protocol', 'version', None)
optvalues.cqlversion = option_with_default(configs.get, 'cql', 'version', None) argvalues.cqlversion = option_with_default(configs.get, 'cql', 'version', None)
optvalues.connect_timeout = option_with_default(configs.getint, 'connection', 'timeout', DEFAULT_CONNECT_TIMEOUT_SECONDS) argvalues.connect_timeout = option_with_default(configs.getint, 'connection', 'timeout', DEFAULT_CONNECT_TIMEOUT_SECONDS)
optvalues.request_timeout = option_with_default(configs.getint, 'connection', 'request_timeout', DEFAULT_REQUEST_TIMEOUT_SECONDS) argvalues.request_timeout = option_with_default(configs.getint, 'connection', 'request_timeout', DEFAULT_REQUEST_TIMEOUT_SECONDS)
optvalues.execute = None argvalues.execute = None
(options, arguments) = parser.parse_args(cmdlineargs, values=optvalues) options, arguments = parser.parse_known_args(cmdlineargs, argvalues)
# Make sure some user values read from the command line are in unicode # Make sure some user values read from the command line are in unicode
options.execute = maybe_ensure_text(options.execute) options.execute = maybe_ensure_text(options.execute)
options.username = maybe_ensure_text(options.username) options.username = maybe_ensure_text(options.username)
@ -2190,8 +2192,8 @@ def read_options(cmdlineargs, environment):
if options.execute and not options.execute.endswith(';'): if options.execute and not options.execute.endswith(';'):
options.execute += ';' options.execute += ';'
if optvalues.color in (True, False): if argvalues.color in (True, False):
options.color = optvalues.color options.color = argvalues.color
else: else:
if options.file is not None: if options.file is not None:
options.color = False options.color = False