PageRenderTime 79ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 0ms

/docs/docs_env/Lib/site-packages/pip-1.0-py2.5.egg/pip/basecommand.py

https://gitlab.com/BeshoyAtef/StudentsPortal
Python | 201 lines | 150 code | 34 blank | 17 comment | 36 complexity | a83c976b4db60cffae4d7e1189ab551d MD5 | raw file
  1. """Base Command class, and related routines"""
  2. import os
  3. import socket
  4. import sys
  5. import traceback
  6. import time
  7. from pip import commands
  8. from pip.log import logger
  9. from pip.baseparser import parser, ConfigOptionParser, UpdatingDefaultsHelpFormatter
  10. from pip.download import urlopen
  11. from pip.exceptions import BadCommand, InstallationError, UninstallationError
  12. from pip.venv import restart_in_venv
  13. from pip.backwardcompat import StringIO, urllib, urllib2, walk_packages
  14. __all__ = ['command_dict', 'Command', 'load_all_commands',
  15. 'load_command', 'command_names']
  16. command_dict = {}
  17. # for backwards compatibiliy
  18. get_proxy = urlopen.get_proxy
  19. class Command(object):
  20. name = None
  21. usage = None
  22. hidden = False
  23. def __init__(self):
  24. assert self.name
  25. self.parser = ConfigOptionParser(
  26. usage=self.usage,
  27. prog='%s %s' % (sys.argv[0], self.name),
  28. version=parser.version,
  29. formatter=UpdatingDefaultsHelpFormatter(),
  30. name=self.name)
  31. for option in parser.option_list:
  32. if not option.dest or option.dest == 'help':
  33. # -h, --version, etc
  34. continue
  35. self.parser.add_option(option)
  36. command_dict[self.name] = self
  37. def merge_options(self, initial_options, options):
  38. # Make sure we have all global options carried over
  39. for attr in ['log', 'venv', 'proxy', 'venv_base', 'require_venv',
  40. 'respect_venv', 'log_explicit_levels', 'log_file',
  41. 'timeout', 'default_vcs', 'skip_requirements_regex',
  42. 'no_input']:
  43. setattr(options, attr, getattr(initial_options, attr) or getattr(options, attr))
  44. options.quiet += initial_options.quiet
  45. options.verbose += initial_options.verbose
  46. def setup_logging(self):
  47. pass
  48. def main(self, complete_args, args, initial_options):
  49. options, args = self.parser.parse_args(args)
  50. self.merge_options(initial_options, options)
  51. level = 1 # Notify
  52. level += options.verbose
  53. level -= options.quiet
  54. level = logger.level_for_integer(4-level)
  55. complete_log = []
  56. logger.consumers.extend(
  57. [(level, sys.stdout),
  58. (logger.DEBUG, complete_log.append)])
  59. if options.log_explicit_levels:
  60. logger.explicit_levels = True
  61. self.setup_logging()
  62. if options.require_venv and not options.venv:
  63. # If a venv is required check if it can really be found
  64. if not os.environ.get('VIRTUAL_ENV'):
  65. logger.fatal('Could not find an activated virtualenv (required).')
  66. sys.exit(3)
  67. # Automatically install in currently activated venv if required
  68. options.respect_venv = True
  69. if args and args[-1] == '___VENV_RESTART___':
  70. ## FIXME: We don't do anything this this value yet:
  71. args = args[:-2]
  72. options.venv = None
  73. else:
  74. # If given the option to respect the activated environment
  75. # check if no venv is given as a command line parameter
  76. if options.respect_venv and os.environ.get('VIRTUAL_ENV'):
  77. if options.venv and os.path.exists(options.venv):
  78. # Make sure command line venv and environmental are the same
  79. if (os.path.realpath(os.path.expanduser(options.venv)) !=
  80. os.path.realpath(os.environ.get('VIRTUAL_ENV'))):
  81. logger.fatal("Given virtualenv (%s) doesn't match "
  82. "currently activated virtualenv (%s)."
  83. % (options.venv, os.environ.get('VIRTUAL_ENV')))
  84. sys.exit(3)
  85. else:
  86. options.venv = os.environ.get('VIRTUAL_ENV')
  87. logger.info('Using already activated environment %s' % options.venv)
  88. if options.venv:
  89. logger.info('Running in environment %s' % options.venv)
  90. site_packages=False
  91. if options.site_packages:
  92. site_packages=True
  93. restart_in_venv(options.venv, options.venv_base, site_packages,
  94. complete_args)
  95. # restart_in_venv should actually never return, but for clarity...
  96. return
  97. ## FIXME: not sure if this sure come before or after venv restart
  98. if options.log:
  99. log_fp = open_logfile(options.log, 'a')
  100. logger.consumers.append((logger.DEBUG, log_fp))
  101. else:
  102. log_fp = None
  103. socket.setdefaulttimeout(options.timeout or None)
  104. urlopen.setup(proxystr=options.proxy, prompting=not options.no_input)
  105. exit = 0
  106. try:
  107. self.run(options, args)
  108. except (InstallationError, UninstallationError):
  109. e = sys.exc_info()[1]
  110. logger.fatal(str(e))
  111. logger.info('Exception information:\n%s' % format_exc())
  112. exit = 1
  113. except BadCommand:
  114. e = sys.exc_info()[1]
  115. logger.fatal(str(e))
  116. logger.info('Exception information:\n%s' % format_exc())
  117. exit = 1
  118. except:
  119. logger.fatal('Exception:\n%s' % format_exc())
  120. exit = 2
  121. if log_fp is not None:
  122. log_fp.close()
  123. if exit:
  124. log_fn = options.log_file
  125. text = '\n'.join(complete_log)
  126. logger.fatal('Storing complete log in %s' % log_fn)
  127. log_fp = open_logfile(log_fn, 'w')
  128. log_fp.write(text)
  129. log_fp.close()
  130. return exit
  131. def format_exc(exc_info=None):
  132. if exc_info is None:
  133. exc_info = sys.exc_info()
  134. out = StringIO()
  135. traceback.print_exception(*exc_info, **dict(file=out))
  136. return out.getvalue()
  137. def open_logfile(filename, mode='a'):
  138. """Open the named log file in append mode.
  139. If the file already exists, a separator will also be printed to
  140. the file to separate past activity from current activity.
  141. """
  142. filename = os.path.expanduser(filename)
  143. filename = os.path.abspath(filename)
  144. dirname = os.path.dirname(filename)
  145. if not os.path.exists(dirname):
  146. os.makedirs(dirname)
  147. exists = os.path.exists(filename)
  148. log_fp = open(filename, mode)
  149. if exists:
  150. log_fp.write('%s\n' % ('-'*60))
  151. log_fp.write('%s run on %s\n' % (sys.argv[0], time.strftime('%c')))
  152. return log_fp
  153. def load_command(name):
  154. full_name = 'pip.commands.%s' % name
  155. if full_name in sys.modules:
  156. return
  157. try:
  158. __import__(full_name)
  159. except ImportError:
  160. pass
  161. def load_all_commands():
  162. for name in command_names():
  163. load_command(name)
  164. def command_names():
  165. names = set((pkg[1] for pkg in walk_packages(path=commands.__path__)))
  166. return list(names)