comparison venv/lib/python2.7/site-packages/pip/__init__.py @ 0:d67268158946 draft

planemo upload commit a3f181f5f126803c654b3a66dd4e83a48f7e203b
author bcclaywell
date Mon, 12 Oct 2015 17:43:33 -0400
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:d67268158946
1 #!/usr/bin/env python
2 from __future__ import absolute_import
3
4 import logging
5 import os
6 import optparse
7 import warnings
8
9 import sys
10 import re
11
12 from pip.exceptions import InstallationError, CommandError, PipError
13 from pip.utils import get_installed_distributions, get_prog
14 from pip.utils import deprecation
15 from pip.vcs import git, mercurial, subversion, bazaar # noqa
16 from pip.baseparser import ConfigOptionParser, UpdatingDefaultsHelpFormatter
17 from pip.commands import get_summaries, get_similar_commands
18 from pip.commands import commands_dict
19 from pip._vendor.requests.packages.urllib3.exceptions import (
20 InsecureRequestWarning,
21 )
22
23
24 # assignment for flake8 to be happy
25
26 # This fixes a peculiarity when importing via __import__ - as we are
27 # initialising the pip module, "from pip import cmdoptions" is recursive
28 # and appears not to work properly in that situation.
29 import pip.cmdoptions
30 cmdoptions = pip.cmdoptions
31
32 # The version as used in the setup.py and the docs conf.py
33 __version__ = "6.1.1"
34
35
36 logger = logging.getLogger(__name__)
37
38 # Hide the InsecureRequestWArning from urllib3
39 warnings.filterwarnings("ignore", category=InsecureRequestWarning)
40
41
42 def autocomplete():
43 """Command and option completion for the main option parser (and options)
44 and its subcommands (and options).
45
46 Enable by sourcing one of the completion shell scripts (bash or zsh).
47 """
48 # Don't complete if user hasn't sourced bash_completion file.
49 if 'PIP_AUTO_COMPLETE' not in os.environ:
50 return
51 cwords = os.environ['COMP_WORDS'].split()[1:]
52 cword = int(os.environ['COMP_CWORD'])
53 try:
54 current = cwords[cword - 1]
55 except IndexError:
56 current = ''
57
58 subcommands = [cmd for cmd, summary in get_summaries()]
59 options = []
60 # subcommand
61 try:
62 subcommand_name = [w for w in cwords if w in subcommands][0]
63 except IndexError:
64 subcommand_name = None
65
66 parser = create_main_parser()
67 # subcommand options
68 if subcommand_name:
69 # special case: 'help' subcommand has no options
70 if subcommand_name == 'help':
71 sys.exit(1)
72 # special case: list locally installed dists for uninstall command
73 if subcommand_name == 'uninstall' and not current.startswith('-'):
74 installed = []
75 lc = current.lower()
76 for dist in get_installed_distributions(local_only=True):
77 if dist.key.startswith(lc) and dist.key not in cwords[1:]:
78 installed.append(dist.key)
79 # if there are no dists installed, fall back to option completion
80 if installed:
81 for dist in installed:
82 print(dist)
83 sys.exit(1)
84
85 subcommand = commands_dict[subcommand_name]()
86 options += [(opt.get_opt_string(), opt.nargs)
87 for opt in subcommand.parser.option_list_all
88 if opt.help != optparse.SUPPRESS_HELP]
89
90 # filter out previously specified options from available options
91 prev_opts = [x.split('=')[0] for x in cwords[1:cword - 1]]
92 options = [(x, v) for (x, v) in options if x not in prev_opts]
93 # filter options by current input
94 options = [(k, v) for k, v in options if k.startswith(current)]
95 for option in options:
96 opt_label = option[0]
97 # append '=' to options which require args
98 if option[1]:
99 opt_label += '='
100 print(opt_label)
101 else:
102 # show main parser options only when necessary
103 if current.startswith('-') or current.startswith('--'):
104 opts = [i.option_list for i in parser.option_groups]
105 opts.append(parser.option_list)
106 opts = (o for it in opts for o in it)
107
108 subcommands += [i.get_opt_string() for i in opts
109 if i.help != optparse.SUPPRESS_HELP]
110
111 print(' '.join([x for x in subcommands if x.startswith(current)]))
112 sys.exit(1)
113
114
115 def create_main_parser():
116 parser_kw = {
117 'usage': '\n%prog <command> [options]',
118 'add_help_option': False,
119 'formatter': UpdatingDefaultsHelpFormatter(),
120 'name': 'global',
121 'prog': get_prog(),
122 }
123
124 parser = ConfigOptionParser(**parser_kw)
125 parser.disable_interspersed_args()
126
127 pip_pkg_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
128 parser.version = 'pip %s from %s (python %s)' % (
129 __version__, pip_pkg_dir, sys.version[:3])
130
131 # add the general options
132 gen_opts = cmdoptions.make_option_group(cmdoptions.general_group, parser)
133 parser.add_option_group(gen_opts)
134
135 parser.main = True # so the help formatter knows
136
137 # create command listing for description
138 command_summaries = get_summaries()
139 description = [''] + ['%-27s %s' % (i, j) for i, j in command_summaries]
140 parser.description = '\n'.join(description)
141
142 return parser
143
144
145 def parseopts(args):
146 parser = create_main_parser()
147
148 # Note: parser calls disable_interspersed_args(), so the result of this
149 # call is to split the initial args into the general options before the
150 # subcommand and everything else.
151 # For example:
152 # args: ['--timeout=5', 'install', '--user', 'INITools']
153 # general_options: ['--timeout==5']
154 # args_else: ['install', '--user', 'INITools']
155 general_options, args_else = parser.parse_args(args)
156
157 # --version
158 if general_options.version:
159 sys.stdout.write(parser.version)
160 sys.stdout.write(os.linesep)
161 sys.exit()
162
163 # pip || pip help -> print_help()
164 if not args_else or (args_else[0] == 'help' and len(args_else) == 1):
165 parser.print_help()
166 sys.exit()
167
168 # the subcommand name
169 cmd_name = args_else[0]
170
171 if cmd_name not in commands_dict:
172 guess = get_similar_commands(cmd_name)
173
174 msg = ['unknown command "%s"' % cmd_name]
175 if guess:
176 msg.append('maybe you meant "%s"' % guess)
177
178 raise CommandError(' - '.join(msg))
179
180 # all the args without the subcommand
181 cmd_args = args[:]
182 cmd_args.remove(cmd_name)
183
184 return cmd_name, cmd_args
185
186
187 def check_isolated(args):
188 isolated = False
189
190 if "--isolated" in args:
191 isolated = True
192
193 return isolated
194
195
196 def main(args=None):
197 if args is None:
198 args = sys.argv[1:]
199
200 # Enable our Deprecation Warnings
201 for deprecation_warning in deprecation.DEPRECATIONS:
202 warnings.simplefilter("default", deprecation_warning)
203
204 # Configure our deprecation warnings to be sent through loggers
205 deprecation.install_warning_logger()
206
207 autocomplete()
208
209 try:
210 cmd_name, cmd_args = parseopts(args)
211 except PipError as exc:
212 sys.stderr.write("ERROR: %s" % exc)
213 sys.stderr.write(os.linesep)
214 sys.exit(1)
215
216 command = commands_dict[cmd_name](isolated=check_isolated(cmd_args))
217 return command.main(cmd_args)
218
219
220 # ###########################################################
221 # # Writing freeze files
222
223 class FrozenRequirement(object):
224
225 def __init__(self, name, req, editable, comments=()):
226 self.name = name
227 self.req = req
228 self.editable = editable
229 self.comments = comments
230
231 _rev_re = re.compile(r'-r(\d+)$')
232 _date_re = re.compile(r'-(20\d\d\d\d\d\d)$')
233
234 @classmethod
235 def from_dist(cls, dist, dependency_links, find_tags=False):
236 location = os.path.normcase(os.path.abspath(dist.location))
237 comments = []
238 from pip.vcs import vcs, get_src_requirement
239 if vcs.get_backend_name(location):
240 editable = True
241 try:
242 req = get_src_requirement(dist, location, find_tags)
243 except InstallationError as exc:
244 logger.warning(
245 "Error when trying to get requirement for VCS system %s, "
246 "falling back to uneditable format", exc
247 )
248 req = None
249 if req is None:
250 logger.warning(
251 'Could not determine repository location of %s', location
252 )
253 comments.append(
254 '## !! Could not determine repository location'
255 )
256 req = dist.as_requirement()
257 editable = False
258 else:
259 editable = False
260 req = dist.as_requirement()
261 specs = req.specs
262 assert len(specs) == 1 and specs[0][0] in ["==", "==="], \
263 'Expected 1 spec with == or ===; specs = %r; dist = %r' % \
264 (specs, dist)
265 version = specs[0][1]
266 ver_match = cls._rev_re.search(version)
267 date_match = cls._date_re.search(version)
268 if ver_match or date_match:
269 svn_backend = vcs.get_backend('svn')
270 if svn_backend:
271 svn_location = svn_backend().get_location(
272 dist,
273 dependency_links,
274 )
275 if not svn_location:
276 logger.warning(
277 'Warning: cannot find svn location for %s', req)
278 comments.append(
279 '## FIXME: could not find svn URL in dependency_links '
280 'for this package:'
281 )
282 else:
283 comments.append(
284 '# Installing as editable to satisfy requirement %s:' %
285 req
286 )
287 if ver_match:
288 rev = ver_match.group(1)
289 else:
290 rev = '{%s}' % date_match.group(1)
291 editable = True
292 req = '%s@%s#egg=%s' % (
293 svn_location,
294 rev,
295 cls.egg_name(dist)
296 )
297 return cls(dist.project_name, req, editable, comments)
298
299 @staticmethod
300 def egg_name(dist):
301 name = dist.egg_name()
302 match = re.search(r'-py\d\.\d$', name)
303 if match:
304 name = name[:match.start()]
305 return name
306
307 def __str__(self):
308 req = self.req
309 if self.editable:
310 req = '-e %s' % req
311 return '\n'.join(list(self.comments) + [str(req)]) + '\n'
312
313
314 if __name__ == '__main__':
315 sys.exit(main())