PageRenderTime 48ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/env/lib/python3.3/site-packages/pip/__init__.py

https://github.com/wantsomechocolate/MosaicMaker
Python | 235 lines | 218 code | 9 blank | 8 comment | 17 complexity | a7c6c4f3b4c4d21fca62c661dcbb1d68 MD5 | raw file
  1. #!/usr/bin/env python
  2. import os
  3. import optparse
  4. import sys
  5. import re
  6. from pip.exceptions import InstallationError, CommandError, PipError
  7. from pip.log import logger
  8. from pip.util import get_installed_distributions, get_prog
  9. from pip.vcs import git, mercurial, subversion, bazaar # noqa
  10. from pip.baseparser import create_main_parser
  11. from pip.commands import commands, get_similar_commands, get_summaries
  12. # The version as used in the setup.py and the docs conf.py
  13. __version__ = "1.4.1"
  14. def autocomplete():
  15. """Command and option completion for the main option parser (and options)
  16. and its subcommands (and options).
  17. Enable by sourcing one of the completion shell scripts (bash or zsh).
  18. """
  19. # Don't complete if user hasn't sourced bash_completion file.
  20. if 'PIP_AUTO_COMPLETE' not in os.environ:
  21. return
  22. cwords = os.environ['COMP_WORDS'].split()[1:]
  23. cword = int(os.environ['COMP_CWORD'])
  24. try:
  25. current = cwords[cword - 1]
  26. except IndexError:
  27. current = ''
  28. subcommands = [cmd for cmd, summary in get_summaries()]
  29. options = []
  30. # subcommand
  31. try:
  32. subcommand_name = [w for w in cwords if w in subcommands][0]
  33. except IndexError:
  34. subcommand_name = None
  35. parser = create_main_parser()
  36. # subcommand options
  37. if subcommand_name:
  38. # special case: 'help' subcommand has no options
  39. if subcommand_name == 'help':
  40. sys.exit(1)
  41. # special case: list locally installed dists for uninstall command
  42. if subcommand_name == 'uninstall' and not current.startswith('-'):
  43. installed = []
  44. lc = current.lower()
  45. for dist in get_installed_distributions(local_only=True):
  46. if dist.key.startswith(lc) and dist.key not in cwords[1:]:
  47. installed.append(dist.key)
  48. # if there are no dists installed, fall back to option completion
  49. if installed:
  50. for dist in installed:
  51. print(dist)
  52. sys.exit(1)
  53. subcommand = commands[subcommand_name](parser)
  54. options += [(opt.get_opt_string(), opt.nargs)
  55. for opt in subcommand.parser.option_list_all
  56. if opt.help != optparse.SUPPRESS_HELP]
  57. # filter out previously specified options from available options
  58. prev_opts = [x.split('=')[0] for x in cwords[1:cword - 1]]
  59. options = [(x, v) for (x, v) in options if x not in prev_opts]
  60. # filter options by current input
  61. options = [(k, v) for k, v in options if k.startswith(current)]
  62. for option in options:
  63. opt_label = option[0]
  64. # append '=' to options which require args
  65. if option[1]:
  66. opt_label += '='
  67. print(opt_label)
  68. else:
  69. # show main parser options only when necessary
  70. if current.startswith('-') or current.startswith('--'):
  71. opts = [i.option_list for i in parser.option_groups]
  72. opts.append(parser.option_list)
  73. opts = (o for it in opts for o in it)
  74. subcommands += [i.get_opt_string() for i in opts
  75. if i.help != optparse.SUPPRESS_HELP]
  76. print(' '.join([x for x in subcommands if x.startswith(current)]))
  77. sys.exit(1)
  78. def parseopts(args):
  79. parser = create_main_parser()
  80. parser.main = True # so the help formatter knows
  81. # create command listing
  82. command_summaries = get_summaries()
  83. description = [''] + ['%-27s %s' % (i, j) for i, j in command_summaries]
  84. parser.description = '\n'.join(description)
  85. options, args = parser.parse_args(args)
  86. if options.version:
  87. sys.stdout.write(parser.version)
  88. sys.stdout.write(os.linesep)
  89. sys.exit()
  90. # pip || pip help || pip --help -> print_help()
  91. if not args or (args[0] == 'help' and len(args) == 1):
  92. parser.print_help()
  93. sys.exit()
  94. if not args:
  95. msg = ('You must give a command '
  96. '(use "pip --help" to see a list of commands)')
  97. raise CommandError(msg)
  98. command = args[0].lower()
  99. if command not in commands:
  100. guess = get_similar_commands(command)
  101. msg = ['unknown command "%s"' % command]
  102. if guess:
  103. msg.append('maybe you meant "%s"' % guess)
  104. raise CommandError(' - '.join(msg))
  105. return command, options, args, parser
  106. def main(initial_args=None):
  107. if initial_args is None:
  108. initial_args = sys.argv[1:]
  109. autocomplete()
  110. try:
  111. cmd_name, options, args, parser = parseopts(initial_args)
  112. except PipError:
  113. e = sys.exc_info()[1]
  114. sys.stderr.write("ERROR: %s" % e)
  115. sys.stderr.write(os.linesep)
  116. sys.exit(1)
  117. command = commands[cmd_name](parser) # see baseparser.Command
  118. return command.main(args[1:], options)
  119. def bootstrap():
  120. """
  121. Bootstrapping function to be called from install-pip.py script.
  122. """
  123. return main(['install', '--upgrade', 'pip'] + sys.argv[1:])
  124. ############################################################
  125. ## Writing freeze files
  126. class FrozenRequirement(object):
  127. def __init__(self, name, req, editable, comments=()):
  128. self.name = name
  129. self.req = req
  130. self.editable = editable
  131. self.comments = comments
  132. _rev_re = re.compile(r'-r(\d+)$')
  133. _date_re = re.compile(r'-(20\d\d\d\d\d\d)$')
  134. @classmethod
  135. def from_dist(cls, dist, dependency_links, find_tags=False):
  136. location = os.path.normcase(os.path.abspath(dist.location))
  137. comments = []
  138. from pip.vcs import vcs, get_src_requirement
  139. if vcs.get_backend_name(location):
  140. editable = True
  141. try:
  142. req = get_src_requirement(dist, location, find_tags)
  143. except InstallationError:
  144. ex = sys.exc_info()[1]
  145. logger.warn("Error when trying to get requirement for VCS system %s, falling back to uneditable format" % ex)
  146. req = None
  147. if req is None:
  148. logger.warn('Could not determine repository location of %s' % location)
  149. comments.append('## !! Could not determine repository location')
  150. req = dist.as_requirement()
  151. editable = False
  152. else:
  153. editable = False
  154. req = dist.as_requirement()
  155. specs = req.specs
  156. assert len(specs) == 1 and specs[0][0] == '=='
  157. version = specs[0][1]
  158. ver_match = cls._rev_re.search(version)
  159. date_match = cls._date_re.search(version)
  160. if ver_match or date_match:
  161. svn_backend = vcs.get_backend('svn')
  162. if svn_backend:
  163. svn_location = svn_backend(
  164. ).get_location(dist, dependency_links)
  165. if not svn_location:
  166. logger.warn(
  167. 'Warning: cannot find svn location for %s' % req)
  168. comments.append('## FIXME: could not find svn URL in dependency_links for this package:')
  169. else:
  170. comments.append('# Installing as editable to satisfy requirement %s:' % req)
  171. if ver_match:
  172. rev = ver_match.group(1)
  173. else:
  174. rev = '{%s}' % date_match.group(1)
  175. editable = True
  176. req = '%s@%s#egg=%s' % (svn_location, rev, cls.egg_name(dist))
  177. return cls(dist.project_name, req, editable, comments)
  178. @staticmethod
  179. def egg_name(dist):
  180. name = dist.egg_name()
  181. match = re.search(r'-py\d\.\d$', name)
  182. if match:
  183. name = name[:match.start()]
  184. return name
  185. def __str__(self):
  186. req = self.req
  187. if self.editable:
  188. req = '-e %s' % req
  189. return '\n'.join(list(self.comments) + [str(req)]) + '\n'
  190. if __name__ == '__main__':
  191. exit = main()
  192. if exit:
  193. sys.exit(exit)