remove global command instances

Rework the way commands are defined, loaded and ran in pip:

 - Commands are instantiated on demand in pip.main().

 - A command 'registry' - mapping of command names to command classes in
   pip.commands.__init__.

 - Remove deferred command module loading.
This commit is contained in:
Georgi Valkov 2012-11-10 06:05:38 +02:00
parent 843ffb38fe
commit 7427eca00b
13 changed files with 63 additions and 56 deletions

View File

@ -6,12 +6,11 @@ import sys
import re
import difflib
from pip.basecommand import command_dict, load_command, load_all_commands, command_names
from pip.baseparser import parser
from pip.exceptions import InstallationError
from pip.exceptions import InstallationError, CommandError, PipError
from pip.log import logger
from pip.util import get_installed_distributions, get_prog
from pip.vcs import git, mercurial, subversion, bazaar # noqa
from pip.commands import commands, get_similar_commands, get_summaries
# The version as used in the setup.py and the docs conf.py
@ -33,8 +32,8 @@ def autocomplete():
current = cwords[cword - 1]
except IndexError:
current = ''
load_all_commands()
subcommands = [cmd for cmd, cls in command_dict.items() if not cls.hidden]
subcommands = [cmd for cmd, cls in commands.items() if not cls.hidden]
options = []
# subcommand
try:
@ -58,7 +57,7 @@ def autocomplete():
for dist in installed:
print(dist)
sys.exit(1)
subcommand = command_dict.get(subcommand_name)
subcommand = commands.get(subcommand_name)
options += [(opt.get_opt_string(), opt.nargs)
for opt in subcommand.parser.option_list
if opt.help != optparse.SUPPRESS_HELP]

View File

@ -8,7 +8,6 @@ import tempfile
import traceback
import time
from pip import commands
from pip.log import logger
from pip.baseparser import parser, ConfigOptionParser, UpdatingDefaultsHelpFormatter
from pip.download import urlopen
@ -19,10 +18,8 @@ from pip.status_codes import SUCCESS, ERROR, UNKNOWN_ERROR, VIRTUALENV_NOT_FOUND
from pip.util import get_prog
__all__ = ['command_dict', 'Command', 'load_all_commands',
'load_command', 'command_names']
__all__ = ['Command']
command_dict = {}
# for backwards compatibiliy
get_proxy = urlopen.get_proxy
@ -179,23 +176,3 @@ def open_logfile(filename, mode='a'):
log_fp.write('%s run on %s\n' % (sys.argv[0], time.strftime('%c')))
return log_fp
def load_command(name):
full_name = 'pip.commands.%s' % name
if full_name in sys.modules:
return
try:
__import__(full_name)
except ImportError:
pass
def load_all_commands():
for name in command_names():
load_command(name)
def command_names():
names = set((pkg[1] for pkg in walk_packages(path=commands.__path__)))
return list(names)

View File

@ -1 +1,57 @@
#
"""
Package containing all pip commands
"""
from pip.commands.bundle import BundleCommand
from pip.commands.completion import CompletionCommand
from pip.commands.freeze import FreezeCommand
from pip.commands.help import HelpCommand
from pip.commands.search import SearchCommand
from pip.commands.show import ShowCommand
from pip.commands.install import InstallCommand
from pip.commands.uninstall import UninstallCommand
from pip.commands.unzip import UnzipCommand
from pip.commands.zip import ZipCommand
commands = {
BundleCommand.name : BundleCommand,
CompletionCommand.name : CompletionCommand,
FreezeCommand.name : FreezeCommand,
HelpCommand.name : HelpCommand,
SearchCommand.name : SearchCommand,
ShowCommand.name : ShowCommand,
InstallCommand.name : InstallCommand,
UninstallCommand.name : UninstallCommand,
UnzipCommand.name : UnzipCommand,
ZipCommand.name : ZipCommand,
}
def get_summaries(ignore_hidden=True):
"""Return a sorted list of (command name, command summary)."""
items = []
for name, command_class in commands.items():
if ignore_hidden and command_class.hidden:
continue
items.append( (name, command_class.summary) )
return sorted(items)
def get_similar_commands(name):
"""Command name auto-correct."""
from difflib import get_close_matches
close_commands = get_close_matches(name, commands.keys())
if close_commands:
guess = close_commands[0]
else:
guess = False
return guess

View File

@ -34,5 +34,3 @@ class BundleCommand(InstallCommand):
requirement_set = super(BundleCommand, self).run(options, args)
return requirement_set
BundleCommand()

View File

@ -56,5 +56,3 @@ class CompletionCommand(Command):
print(BASE_COMPLETION % {'script': script, 'shell': options.shell})
else:
sys.stderr.write('ERROR: You must pass %s\n' % ' or '.join(shell_options))
CompletionCommand()

View File

@ -106,6 +106,3 @@ class FreezeCommand(Command):
f.write('## The following requirements were added by pip --freeze:\n')
for installation in sorted(installations.values(), key=lambda x: x.name):
f.write(str(installation))
FreezeCommand()

View File

@ -30,4 +30,3 @@ class HelpCommand(Command):
print(' %s: %s' % (command.name, command.summary))
return SUCCESS
HelpCommand()

View File

@ -292,6 +292,3 @@ class InstallCommand(Command):
)
shutil.rmtree(temp_target_dir)
return requirement_set
InstallCommand()

View File

@ -124,6 +124,3 @@ def compare_versions(version1, version2):
def highest_version(versions):
return reduce((lambda v1, v2: compare_versions(v1, v2) == 1 and v1 or v2), versions)
SearchCommand()

View File

@ -73,6 +73,3 @@ def print_results(distributions, list_all_files):
logger.notify(" %s" % line.strip())
else:
logger.notify("Cannot locate installed-files.txt")
ShowCommand()

View File

@ -39,5 +39,3 @@ class UninstallCommand(Command):
raise InstallationError('You must give at least one requirement '
'to %(name)s (see "pip help %(name)s")' % dict(name=self.name))
requirement_set.uninstall(auto_confirm=options.yes)
UninstallCommand()

View File

@ -4,6 +4,3 @@ from pip.commands.zip import ZipCommand
class UnzipCommand(ZipCommand):
name = 'unzip'
summary = 'Unzip individual packages'
UnzipCommand()

View File

@ -341,6 +341,3 @@ class ZipCommand(Command):
if not f.lower().endswith('.pyc')]
total += len(filenames)
return total
ZipCommand()