refactor(commands): Add method add_options and remove __init__

This removes the __init__ method of child classes and defines
explicit method for adding command options.
This commit is contained in:
gutsytechster 2020-05-21 14:00:44 +05:30
parent db75ac5587
commit 72a42197a4
14 changed files with 72 additions and 89 deletions

View File

@ -87,6 +87,13 @@ class Command(CommandContextMixIn):
self.parser, self.parser,
) )
self.parser.add_option_group(gen_opts) self.parser.add_option_group(gen_opts)
try:
# mypy raises error due to
# https://github.com/python/mypy/issues/5868
self.add_options(self.cmd_opts) # type: ignore
except AttributeError:
# it means that the base class has not defined the method
logger.debug("No add_options method defined in the class")
def handle_pip_version_check(self, options): def handle_pip_version_check(self, options):
# type: (Values) -> None # type: (Values) -> None

View File

@ -9,8 +9,8 @@ from pip._internal.utils.misc import get_prog
from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.utils.typing import MYPY_CHECK_RUNNING
if MYPY_CHECK_RUNNING: if MYPY_CHECK_RUNNING:
from typing import Any, List from typing import List
from optparse import Values from optparse import Values, OptionGroup
BASE_COMPLETION = """ BASE_COMPLETION = """
# pip {shell} completion start{script}# pip {shell} completion end # pip {shell} completion start{script}# pip {shell} completion end
@ -56,12 +56,8 @@ class CompletionCommand(Command):
ignore_require_venv = True ignore_require_venv = True
def __init__(self, *args, **kw): def add_options(self, cmd_opts):
# type: (*Any, **Any) -> None # type: (OptionGroup) -> None
super(CompletionCommand, self).__init__(*args, **kw)
cmd_opts = self.cmd_opts
cmd_opts.add_option( cmd_opts.add_option(
'--bash', '-b', '--bash', '-b',
action='store_const', action='store_const',

View File

@ -45,12 +45,15 @@ class ConfigurationCommand(Command):
%prog [<file-option>] unset name %prog [<file-option>] unset name
""" """
def __init__(self, *args, **kwargs): def __init__(self, name, summary, isolated=False):
super(ConfigurationCommand, self).__init__(*args, **kwargs) super(ConfigurationCommand, self).__init__(
name, summary, isolated=isolated
)
self.configuration = None self.configuration = None
self.cmd_opts.add_option( def add_options(self, cmd_opts):
cmd_opts.add_option(
'--editor', '--editor',
dest='editor', dest='editor',
action='store', action='store',
@ -61,7 +64,7 @@ class ConfigurationCommand(Command):
) )
) )
self.cmd_opts.add_option( cmd_opts.add_option(
'--global', '--global',
dest='global_file', dest='global_file',
action='store_true', action='store_true',
@ -69,7 +72,7 @@ class ConfigurationCommand(Command):
help='Use the system-wide configuration file only' help='Use the system-wide configuration file only'
) )
self.cmd_opts.add_option( cmd_opts.add_option(
'--user', '--user',
dest='user_file', dest='user_file',
action='store_true', action='store_true',
@ -77,7 +80,7 @@ class ConfigurationCommand(Command):
help='Use the user configuration file only' help='Use the user configuration file only'
) )
self.cmd_opts.add_option( cmd_opts.add_option(
'--site', '--site',
dest='site_file', dest='site_file',
action='store_true', action='store_true',
@ -85,7 +88,7 @@ class ConfigurationCommand(Command):
help='Use the current environment configuration file only' help='Use the current environment configuration file only'
) )
self.parser.insert_option_group(0, self.cmd_opts) self.parser.insert_option_group(0, cmd_opts)
def run(self, options, args): def run(self, options, args):
handlers = { handlers = {

View File

@ -20,8 +20,8 @@ from pip._internal.utils.typing import MYPY_CHECK_RUNNING
if MYPY_CHECK_RUNNING: if MYPY_CHECK_RUNNING:
from types import ModuleType from types import ModuleType
from typing import Any, List, Optional, Dict from typing import List, Optional, Dict
from optparse import Values from optparse import Values, OptionGroup
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -193,11 +193,8 @@ class DebugCommand(Command):
%prog <options>""" %prog <options>"""
ignore_require_venv = True ignore_require_venv = True
def __init__(self, *args, **kw): def add_options(self, cmd_opts):
# type: (*Any, **Any) -> None # type: (OptionGroup) -> None
super(DebugCommand, self).__init__(*args, **kw)
cmd_opts = self.cmd_opts
cmdoptions.add_target_python_options(cmd_opts) cmdoptions.add_target_python_options(cmd_opts)
self.parser.insert_option_group(0, cmd_opts) self.parser.insert_option_group(0, cmd_opts)
self.parser.config.load() self.parser.config.load()

View File

@ -39,12 +39,7 @@ class DownloadCommand(RequirementCommand):
%prog [options] <local project path> ... %prog [options] <local project path> ...
%prog [options] <archive url/path> ...""" %prog [options] <archive url/path> ..."""
def __init__(self, *args, **kw): def add_options(self, cmd_opts):
# type: (*Any, **Any) -> None
super(DownloadCommand, self).__init__(*args, **kw)
cmd_opts = self.cmd_opts
cmd_opts.add_option(cmdoptions.constraints()) cmd_opts.add_option(cmdoptions.constraints())
cmd_opts.add_option(cmdoptions.requirements()) cmd_opts.add_option(cmdoptions.requirements())
cmd_opts.add_option(cmdoptions.build_dir()) cmd_opts.add_option(cmdoptions.build_dir())

View File

@ -29,11 +29,8 @@ class FreezeCommand(Command):
%prog [options]""" %prog [options]"""
log_streams = ("ext://sys.stderr", "ext://sys.stderr") log_streams = ("ext://sys.stderr", "ext://sys.stderr")
def __init__(self, *args, **kw): def add_options(self, cmd_opts):
# type: (*Any, **Any) -> None cmd_opts.add_option(
super(FreezeCommand, self).__init__(*args, **kw)
self.cmd_opts.add_option(
'-r', '--requirement', '-r', '--requirement',
dest='requirements', dest='requirements',
action='append', action='append',
@ -42,7 +39,7 @@ class FreezeCommand(Command):
help="Use the order in the given requirements file and its " help="Use the order in the given requirements file and its "
"comments when generating output. This option can be " "comments when generating output. This option can be "
"used multiple times.") "used multiple times.")
self.cmd_opts.add_option( cmd_opts.add_option(
'-f', '--find-links', '-f', '--find-links',
dest='find_links', dest='find_links',
action='append', action='append',
@ -50,33 +47,33 @@ class FreezeCommand(Command):
metavar='URL', metavar='URL',
help='URL for finding packages, which will be added to the ' help='URL for finding packages, which will be added to the '
'output.') 'output.')
self.cmd_opts.add_option( cmd_opts.add_option(
'-l', '--local', '-l', '--local',
dest='local', dest='local',
action='store_true', action='store_true',
default=False, default=False,
help='If in a virtualenv that has global access, do not output ' help='If in a virtualenv that has global access, do not output '
'globally-installed packages.') 'globally-installed packages.')
self.cmd_opts.add_option( cmd_opts.add_option(
'--user', '--user',
dest='user', dest='user',
action='store_true', action='store_true',
default=False, default=False,
help='Only output packages installed in user-site.') help='Only output packages installed in user-site.')
self.cmd_opts.add_option(cmdoptions.list_path()) cmd_opts.add_option(cmdoptions.list_path())
self.cmd_opts.add_option( cmd_opts.add_option(
'--all', '--all',
dest='freeze_all', dest='freeze_all',
action='store_true', action='store_true',
help='Do not skip these packages in the output:' help='Do not skip these packages in the output:'
' {}'.format(', '.join(DEV_PKGS))) ' {}'.format(', '.join(DEV_PKGS)))
self.cmd_opts.add_option( cmd_opts.add_option(
'--exclude-editable', '--exclude-editable',
dest='exclude_editable', dest='exclude_editable',
action='store_true', action='store_true',
help='Exclude editable package from output.') help='Exclude editable package from output.')
self.parser.insert_option_group(0, self.cmd_opts) self.parser.insert_option_group(0, cmd_opts)
def run(self, options, args): def run(self, options, args):
# type: (Values, List[str]) -> int # type: (Values, List[str]) -> int

View File

@ -11,8 +11,8 @@ from pip._internal.utils.misc import read_chunks, write_output
from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.utils.typing import MYPY_CHECK_RUNNING
if MYPY_CHECK_RUNNING: if MYPY_CHECK_RUNNING:
from optparse import Values from optparse import Values, OptionGroup
from typing import Any, List from typing import List
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -28,10 +28,9 @@ class HashCommand(Command):
usage = '%prog [options] <file> ...' usage = '%prog [options] <file> ...'
ignore_require_venv = True ignore_require_venv = True
def __init__(self, *args, **kw): def add_options(self, cmd_opts):
# type: (*Any, **Any) -> None # type: (OptionGroup) -> None
super(HashCommand, self).__init__(*args, **kw) cmd_opts.add_option(
self.cmd_opts.add_option(
'-a', '--algorithm', '-a', '--algorithm',
dest='algorithm', dest='algorithm',
choices=STRONG_HASHES, choices=STRONG_HASHES,
@ -39,7 +38,7 @@ class HashCommand(Command):
default=FAVORITE_HASH, default=FAVORITE_HASH,
help='The hash algorithm to use: one of {}'.format( help='The hash algorithm to use: one of {}'.format(
', '.join(STRONG_HASHES))) ', '.join(STRONG_HASHES)))
self.parser.insert_option_group(0, self.cmd_opts) self.parser.insert_option_group(0, cmd_opts)
def run(self, options, args): def run(self, options, args):
# type: (Values, List[str]) -> int # type: (Values, List[str]) -> int

View File

@ -43,7 +43,7 @@ from pip._internal.utils.virtualenv import virtualenv_no_global
from pip._internal.wheel_builder import build, should_build_for_install_command from pip._internal.wheel_builder import build, should_build_for_install_command
if MYPY_CHECK_RUNNING: if MYPY_CHECK_RUNNING:
from optparse import Values from optparse import Values, OptionGroup
from typing import Any, Iterable, List, Optional from typing import Any, Iterable, List, Optional
from pip._internal.models.format_control import FormatControl from pip._internal.models.format_control import FormatControl
@ -87,11 +87,8 @@ class InstallCommand(RequirementCommand):
%prog [options] [-e] <local project path> ... %prog [options] [-e] <local project path> ...
%prog [options] <archive url/path> ...""" %prog [options] <archive url/path> ..."""
def __init__(self, *args, **kw): def add_options(self, cmd_opts):
super(InstallCommand, self).__init__(*args, **kw) # type: (OptionGroup) -> None
cmd_opts = self.cmd_opts
cmd_opts.add_option(cmdoptions.requirements()) cmd_opts.add_option(cmdoptions.requirements())
cmd_opts.add_option(cmdoptions.constraints()) cmd_opts.add_option(cmdoptions.constraints())
cmd_opts.add_option(cmdoptions.no_deps()) cmd_opts.add_option(cmdoptions.no_deps())

View File

@ -22,8 +22,8 @@ from pip._internal.utils.packaging import get_installer
from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.utils.typing import MYPY_CHECK_RUNNING
if MYPY_CHECK_RUNNING: if MYPY_CHECK_RUNNING:
from optparse import Values from optparse import Values, OptionGroup
from typing import Any, List, Set, Tuple, Iterator from typing import List, Set, Tuple, Iterator
from pip._internal.network.session import PipSession from pip._internal.network.session import PipSession
from pip._vendor.pkg_resources import Distribution from pip._vendor.pkg_resources import Distribution
@ -41,12 +41,8 @@ class ListCommand(IndexGroupCommand):
usage = """ usage = """
%prog [options]""" %prog [options]"""
def __init__(self, *args, **kw): def add_options(self, cmd_opts):
# type: (*Any, **Any) -> None # type: (OptionGroup) -> None
super(ListCommand, self).__init__(*args, **kw)
cmd_opts = self.cmd_opts
cmd_opts.add_option( cmd_opts.add_option(
'-o', '--outdated', '-o', '--outdated',
action='store_true', action='store_true',

View File

@ -41,17 +41,15 @@ class SearchCommand(Command, SessionCommandMixin):
%prog [options] <query>""" %prog [options] <query>"""
ignore_require_venv = True ignore_require_venv = True
def __init__(self, *args, **kw): def add_options(self, cmd_opts):
# type: (*Any, **Any) -> None cmd_opts.add_option(
super(SearchCommand, self).__init__(*args, **kw)
self.cmd_opts.add_option(
'-i', '--index', '-i', '--index',
dest='index', dest='index',
metavar='URL', metavar='URL',
default=PyPI.pypi_url, default=PyPI.pypi_url,
help='Base URL of Python Package Index (default %default)') help='Base URL of Python Package Index (default %default)')
self.parser.insert_option_group(0, self.cmd_opts) self.parser.insert_option_group(0, cmd_opts)
def run(self, options, args): def run(self, options, args):
# type: (Values, List[str]) -> int # type: (Values, List[str]) -> int

View File

@ -13,8 +13,8 @@ from pip._internal.utils.misc import write_output
from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.utils.typing import MYPY_CHECK_RUNNING
if MYPY_CHECK_RUNNING: if MYPY_CHECK_RUNNING:
from optparse import Values from optparse import Values, OptionGroup
from typing import Any, List, Dict, Iterator from typing import List, Dict, Iterator
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -30,17 +30,16 @@ class ShowCommand(Command):
%prog [options] <package> ...""" %prog [options] <package> ..."""
ignore_require_venv = True ignore_require_venv = True
def __init__(self, *args, **kw): def add_options(self, cmd_opts):
# type: (*Any, **Any) -> None # type: (OptionGroup) -> None
super(ShowCommand, self).__init__(*args, **kw) cmd_opts.add_option(
self.cmd_opts.add_option(
'-f', '--files', '-f', '--files',
dest='files', dest='files',
action='store_true', action='store_true',
default=False, default=False,
help='Show the full list of installed files for each package.') help='Show the full list of installed files for each package.')
self.parser.insert_option_group(0, self.cmd_opts) self.parser.insert_option_group(0, cmd_opts)
def run(self, options, args): def run(self, options, args):
# type: (Values, List[str]) -> int # type: (Values, List[str]) -> int

View File

@ -15,8 +15,8 @@ from pip._internal.utils.misc import protect_pip_from_modification_on_windows
from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.utils.typing import MYPY_CHECK_RUNNING
if MYPY_CHECK_RUNNING: if MYPY_CHECK_RUNNING:
from optparse import Values from optparse import Values, OptionGroup
from typing import Any, List from typing import List
class UninstallCommand(Command, SessionCommandMixin): class UninstallCommand(Command, SessionCommandMixin):
@ -34,10 +34,9 @@ class UninstallCommand(Command, SessionCommandMixin):
%prog [options] <package> ... %prog [options] <package> ...
%prog [options] -r <requirements file> ...""" %prog [options] -r <requirements file> ..."""
def __init__(self, *args, **kw): def add_options(self, cmd_opts):
# type: (*Any, **Any) -> None # type: (OptionGroup) -> None
super(UninstallCommand, self).__init__(*args, **kw) cmd_opts.add_option(
self.cmd_opts.add_option(
'-r', '--requirement', '-r', '--requirement',
dest='requirements', dest='requirements',
action='append', action='append',
@ -46,13 +45,13 @@ class UninstallCommand(Command, SessionCommandMixin):
help='Uninstall all the packages listed in the given requirements ' help='Uninstall all the packages listed in the given requirements '
'file. This option can be used multiple times.', 'file. This option can be used multiple times.',
) )
self.cmd_opts.add_option( cmd_opts.add_option(
'-y', '--yes', '-y', '--yes',
dest='yes', dest='yes',
action='store_true', action='store_true',
help="Don't ask for confirmation of uninstall deletions.") help="Don't ask for confirmation of uninstall deletions.")
self.parser.insert_option_group(0, self.cmd_opts) self.parser.insert_option_group(0, cmd_opts)
def run(self, options, args): def run(self, options, args):
# type: (Values, List[str]) -> int # type: (Values, List[str]) -> int

View File

@ -18,8 +18,8 @@ from pip._internal.utils.typing import MYPY_CHECK_RUNNING
from pip._internal.wheel_builder import build, should_build_for_wheel_command from pip._internal.wheel_builder import build, should_build_for_wheel_command
if MYPY_CHECK_RUNNING: if MYPY_CHECK_RUNNING:
from optparse import Values from optparse import Values, OptionGroup
from typing import Any, List from typing import List
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -47,10 +47,8 @@ class WheelCommand(RequirementCommand):
%prog [options] [-e] <local project path> ... %prog [options] [-e] <local project path> ...
%prog [options] <archive url/path> ...""" %prog [options] <archive url/path> ..."""
def __init__(self, *args, **kw): def add_options(self, cmd_opts):
# type: (*Any, **Any) -> None # type: (OptionGroup) -> None
super(WheelCommand, self).__init__(*args, **kw)
cmd_opts = self.cmd_opts cmd_opts = self.cmd_opts
cmd_opts.add_option( cmd_opts.add_option(

View File

@ -9,8 +9,10 @@ class SimpleCommand(Command):
def __init__(self): def __init__(self):
super(SimpleCommand, self).__init__('fake', 'fake summary') super(SimpleCommand, self).__init__('fake', 'fake summary')
self.cmd_opts.add_option(cmdoptions.no_binary())
self.cmd_opts.add_option(cmdoptions.only_binary()) def add_options(self, cmd_opts):
cmd_opts.add_option(cmdoptions.no_binary())
cmd_opts.add_option(cmdoptions.only_binary())
def run(self, options, args): def run(self, options, args):
self.options = options self.options = options