summaryrefslogtreecommitdiff
path: root/venv/lib/python3.7/site-packages/pip-10.0.1-py3.7.egg/pip/_internal/commands/install.py
diff options
context:
space:
mode:
authorShubham Saini <shubham6405@gmail.com>2018-12-11 10:01:23 +0000
committerShubham Saini <shubham6405@gmail.com>2018-12-11 10:01:23 +0000
commit68df54d6629ec019142eb149dd037774f2d11e7c (patch)
tree345bc22d46b4e01a4ba8303b94278952a4ed2b9e /venv/lib/python3.7/site-packages/pip-10.0.1-py3.7.egg/pip/_internal/commands/install.py
First commit
Diffstat (limited to 'venv/lib/python3.7/site-packages/pip-10.0.1-py3.7.egg/pip/_internal/commands/install.py')
-rw-r--r--venv/lib/python3.7/site-packages/pip-10.0.1-py3.7.egg/pip/_internal/commands/install.py502
1 files changed, 502 insertions, 0 deletions
diff --git a/venv/lib/python3.7/site-packages/pip-10.0.1-py3.7.egg/pip/_internal/commands/install.py b/venv/lib/python3.7/site-packages/pip-10.0.1-py3.7.egg/pip/_internal/commands/install.py
new file mode 100644
index 0000000..057a64e
--- /dev/null
+++ b/venv/lib/python3.7/site-packages/pip-10.0.1-py3.7.egg/pip/_internal/commands/install.py
@@ -0,0 +1,502 @@
1from __future__ import absolute_import
2
3import errno
4import logging
5import operator
6import os
7import shutil
8from optparse import SUPPRESS_HELP
9
10from pip._internal import cmdoptions
11from pip._internal.basecommand import RequirementCommand
12from pip._internal.cache import WheelCache
13from pip._internal.exceptions import (
14 CommandError, InstallationError, PreviousBuildDirError,
15)
16from pip._internal.locations import distutils_scheme, virtualenv_no_global
17from pip._internal.operations.check import check_install_conflicts
18from pip._internal.operations.prepare import RequirementPreparer
19from pip._internal.req import RequirementSet, install_given_reqs
20from pip._internal.resolve import Resolver
21from pip._internal.status_codes import ERROR
22from pip._internal.utils.filesystem import check_path_owner
23from pip._internal.utils.misc import ensure_dir, get_installed_version
24from pip._internal.utils.temp_dir import TempDirectory
25from pip._internal.wheel import WheelBuilder
26
27try:
28 import wheel
29except ImportError:
30 wheel = None
31
32
33logger = logging.getLogger(__name__)
34
35
36class InstallCommand(RequirementCommand):
37 """
38 Install packages from:
39
40 - PyPI (and other indexes) using requirement specifiers.
41 - VCS project urls.
42 - Local project directories.
43 - Local or remote source archives.
44
45 pip also supports installing from "requirements files", which provide
46 an easy way to specify a whole environment to be installed.
47 """
48 name = 'install'
49
50 usage = """
51 %prog [options] <requirement specifier> [package-index-options] ...
52 %prog [options] -r <requirements file> [package-index-options] ...
53 %prog [options] [-e] <vcs project url> ...
54 %prog [options] [-e] <local project path> ...
55 %prog [options] <archive url/path> ..."""
56
57 summary = 'Install packages.'
58
59 def __init__(self, *args, **kw):
60 super(InstallCommand, self).__init__(*args, **kw)
61
62 cmd_opts = self.cmd_opts
63
64 cmd_opts.add_option(cmdoptions.requirements())
65 cmd_opts.add_option(cmdoptions.constraints())
66 cmd_opts.add_option(cmdoptions.no_deps())
67 cmd_opts.add_option(cmdoptions.pre())
68
69 cmd_opts.add_option(cmdoptions.editable())
70 cmd_opts.add_option(
71 '-t', '--target',
72 dest='target_dir',
73 metavar='dir',
74 default=None,
75 help='Install packages into <dir>. '
76 'By default this will not replace existing files/folders in '
77 '<dir>. Use --upgrade to replace existing packages in <dir> '
78 'with new versions.'
79 )
80 cmd_opts.add_option(
81 '--user',
82 dest='use_user_site',
83 action='store_true',
84 help="Install to the Python user install directory for your "
85 "platform. Typically ~/.local/, or %APPDATA%\\Python on "
86 "Windows. (See the Python documentation for site.USER_BASE "
87 "for full details.)")
88 cmd_opts.add_option(
89 '--no-user',
90 dest='use_user_site',
91 action='store_false',
92 help=SUPPRESS_HELP)
93 cmd_opts.add_option(
94 '--root',
95 dest='root_path',
96 metavar='dir',
97 default=None,
98 help="Install everything relative to this alternate root "
99 "directory.")
100 cmd_opts.add_option(
101 '--prefix',
102 dest='prefix_path',
103 metavar='dir',
104 default=None,
105 help="Installation prefix where lib, bin and other top-level "
106 "folders are placed")
107
108 cmd_opts.add_option(cmdoptions.build_dir())
109
110 cmd_opts.add_option(cmdoptions.src())
111
112 cmd_opts.add_option(
113 '-U', '--upgrade',
114 dest='upgrade',
115 action='store_true',
116 help='Upgrade all specified packages to the newest available '
117 'version. The handling of dependencies depends on the '
118 'upgrade-strategy used.'
119 )
120
121 cmd_opts.add_option(
122 '--upgrade-strategy',
123 dest='upgrade_strategy',
124 default='only-if-needed',
125 choices=['only-if-needed', 'eager'],
126 help='Determines how dependency upgrading should be handled '
127 '[default: %default]. '
128 '"eager" - dependencies are upgraded regardless of '
129 'whether the currently installed version satisfies the '
130 'requirements of the upgraded package(s). '
131 '"only-if-needed" - are upgraded only when they do not '
132 'satisfy the requirements of the upgraded package(s).'
133 )
134
135 cmd_opts.add_option(
136 '--force-reinstall',
137 dest='force_reinstall',
138 action='store_true',
139 help='Reinstall all packages even if they are already '
140 'up-to-date.')
141
142 cmd_opts.add_option(
143 '-I', '--ignore-installed',
144 dest='ignore_installed',
145 action='store_true',
146 help='Ignore the installed packages (reinstalling instead).')
147
148 cmd_opts.add_option(cmdoptions.ignore_requires_python())
149 cmd_opts.add_option(cmdoptions.no_build_isolation())
150
151 cmd_opts.add_option(cmdoptions.install_options())
152 cmd_opts.add_option(cmdoptions.global_options())
153
154 cmd_opts.add_option(
155 "--compile",
156 action="store_true",
157 dest="compile",
158 default=True,
159 help="Compile Python source files to bytecode",
160 )
161
162 cmd_opts.add_option(
163 "--no-compile",
164 action="store_false",
165 dest="compile",
166 help="Do not compile Python source files to bytecode",
167 )
168
169 cmd_opts.add_option(
170 "--no-warn-script-location",
171 action="store_false",
172 dest="warn_script_location",
173 default=True,
174 help="Do not warn when installing scripts outside PATH",
175 )
176 cmd_opts.add_option(
177 "--no-warn-conflicts",
178 action="store_false",
179 dest="warn_about_conflicts",
180 default=True,
181 help="Do not warn about broken dependencies",
182 )
183
184 cmd_opts.add_option(cmdoptions.no_binary())
185 cmd_opts.add_option(cmdoptions.only_binary())
186 cmd_opts.add_option(cmdoptions.no_clean())
187 cmd_opts.add_option(cmdoptions.require_hashes())
188 cmd_opts.add_option(cmdoptions.progress_bar())
189
190 index_opts = cmdoptions.make_option_group(
191 cmdoptions.index_group,
192 self.parser,
193 )
194
195 self.parser.insert_option_group(0, index_opts)
196 self.parser.insert_option_group(0, cmd_opts)
197
198 def run(self, options, args):
199 cmdoptions.check_install_build_global(options)
200
201 upgrade_strategy = "to-satisfy-only"
202 if options.upgrade:
203 upgrade_strategy = options.upgrade_strategy
204
205 if options.build_dir:
206 options.build_dir = os.path.abspath(options.build_dir)
207
208 options.src_dir = os.path.abspath(options.src_dir)
209 install_options = options.install_options or []
210 if options.use_user_site:
211 if options.prefix_path:
212 raise CommandError(
213 "Can not combine '--user' and '--prefix' as they imply "
214 "different installation locations"
215 )
216 if virtualenv_no_global():
217 raise InstallationError(
218 "Can not perform a '--user' install. User site-packages "
219 "are not visible in this virtualenv."
220 )
221 install_options.append('--user')
222 install_options.append('--prefix=')
223
224 target_temp_dir = TempDirectory(kind="target")
225 if options.target_dir:
226 options.ignore_installed = True
227 options.target_dir = os.path.abspath(options.target_dir)
228 if (os.path.exists(options.target_dir) and not
229 os.path.isdir(options.target_dir)):
230 raise CommandError(
231 "Target path exists but is not a directory, will not "
232 "continue."
233 )
234
235 # Create a target directory for using with the target option
236 target_temp_dir.create()
237 install_options.append('--home=' + target_temp_dir.path)
238
239 global_options = options.global_options or []
240
241 with self._build_session(options) as session:
242 finder = self._build_package_finder(options, session)
243 build_delete = (not (options.no_clean or options.build_dir))
244 wheel_cache = WheelCache(options.cache_dir, options.format_control)
245
246 if options.cache_dir and not check_path_owner(options.cache_dir):
247 logger.warning(
248 "The directory '%s' or its parent directory is not owned "
249 "by the current user and caching wheels has been "
250 "disabled. check the permissions and owner of that "
251 "directory. If executing pip with sudo, you may want "
252 "sudo's -H flag.",
253 options.cache_dir,
254 )
255 options.cache_dir = None
256
257 with TempDirectory(
258 options.build_dir, delete=build_delete, kind="install"
259 ) as directory:
260 requirement_set = RequirementSet(
261 require_hashes=options.require_hashes,
262 )
263
264 try:
265 self.populate_requirement_set(
266 requirement_set, args, options, finder, session,
267 self.name, wheel_cache
268 )
269 preparer = RequirementPreparer(
270 build_dir=directory.path,
271 src_dir=options.src_dir,
272 download_dir=None,
273 wheel_download_dir=None,
274 progress_bar=options.progress_bar,
275 build_isolation=options.build_isolation,
276 )
277
278 resolver = Resolver(
279 preparer=preparer,
280 finder=finder,
281 session=session,
282 wheel_cache=wheel_cache,
283 use_user_site=options.use_user_site,
284 upgrade_strategy=upgrade_strategy,
285 force_reinstall=options.force_reinstall,
286 ignore_dependencies=options.ignore_dependencies,
287 ignore_requires_python=options.ignore_requires_python,
288 ignore_installed=options.ignore_installed,
289 isolated=options.isolated_mode,
290 )
291 resolver.resolve(requirement_set)
292
293 # If caching is disabled or wheel is not installed don't
294 # try to build wheels.
295 if wheel and options.cache_dir:
296 # build wheels before install.
297 wb = WheelBuilder(
298 finder, preparer, wheel_cache,
299 build_options=[], global_options=[],
300 )
301 # Ignore the result: a failed wheel will be
302 # installed from the sdist/vcs whatever.
303 wb.build(
304 requirement_set.requirements.values(),
305 session=session, autobuilding=True
306 )
307
308 to_install = resolver.get_installation_order(
309 requirement_set
310 )
311
312 # Consistency Checking of the package set we're installing.
313 should_warn_about_conflicts = (
314 not options.ignore_dependencies and
315 options.warn_about_conflicts
316 )
317 if should_warn_about_conflicts:
318 self._warn_about_conflicts(to_install)
319
320 # Don't warn about script install locations if
321 # --target has been specified
322 warn_script_location = options.warn_script_location
323 if options.target_dir:
324 warn_script_location = False
325
326 installed = install_given_reqs(
327 to_install,
328 install_options,
329 global_options,
330 root=options.root_path,
331 home=target_temp_dir.path,
332 prefix=options.prefix_path,
333 pycompile=options.compile,
334 warn_script_location=warn_script_location,
335 use_user_site=options.use_user_site,
336 )
337
338 possible_lib_locations = get_lib_location_guesses(
339 user=options.use_user_site,
340 home=target_temp_dir.path,
341 root=options.root_path,
342 prefix=options.prefix_path,
343 isolated=options.isolated_mode,
344 )
345 reqs = sorted(installed, key=operator.attrgetter('name'))
346 items = []
347 for req in reqs:
348 item = req.name
349 try:
350 installed_version = get_installed_version(
351 req.name, possible_lib_locations
352 )
353 if installed_version:
354 item += '-' + installed_version
355 except Exception:
356 pass
357 items.append(item)
358 installed = ' '.join(items)
359 if installed:
360 logger.info('Successfully installed %s', installed)
361 except EnvironmentError as error:
362 show_traceback = (self.verbosity >= 1)
363
364 message = create_env_error_message(
365 error, show_traceback, options.use_user_site,
366 )
367 logger.error(message, exc_info=show_traceback)
368
369 return ERROR
370 except PreviousBuildDirError:
371 options.no_clean = True
372 raise
373 finally:
374 # Clean up
375 if not options.no_clean:
376 requirement_set.cleanup_files()
377 wheel_cache.cleanup()
378
379 if options.target_dir:
380 self._handle_target_dir(
381 options.target_dir, target_temp_dir, options.upgrade
382 )
383 return requirement_set
384
385 def _handle_target_dir(self, target_dir, target_temp_dir, upgrade):
386 ensure_dir(target_dir)
387
388 # Checking both purelib and platlib directories for installed
389 # packages to be moved to target directory
390 lib_dir_list = []
391
392 with target_temp_dir:
393 # Checking both purelib and platlib directories for installed
394 # packages to be moved to target directory
395 scheme = distutils_scheme('', home=target_temp_dir.path)
396 purelib_dir = scheme['purelib']
397 platlib_dir = scheme['platlib']
398 data_dir = scheme['data']
399
400 if os.path.exists(purelib_dir):
401 lib_dir_list.append(purelib_dir)
402 if os.path.exists(platlib_dir) and platlib_dir != purelib_dir:
403 lib_dir_list.append(platlib_dir)
404 if os.path.exists(data_dir):
405 lib_dir_list.append(data_dir)
406
407 for lib_dir in lib_dir_list:
408 for item in os.listdir(lib_dir):
409 if lib_dir == data_dir:
410 ddir = os.path.join(data_dir, item)
411 if any(s.startswith(ddir) for s in lib_dir_list[:-1]):
412 continue
413 target_item_dir = os.path.join(target_dir, item)
414 if os.path.exists(target_item_dir):
415 if not upgrade:
416 logger.warning(
417 'Target directory %s already exists. Specify '
418 '--upgrade to force replacement.',
419 target_item_dir
420 )
421 continue
422 if os.path.islink(target_item_dir):
423 logger.warning(
424 'Target directory %s already exists and is '
425 'a link. Pip will not automatically replace '
426 'links, please remove if replacement is '
427 'desired.',
428 target_item_dir
429 )
430 continue
431 if os.path.isdir(target_item_dir):
432 shutil.rmtree(target_item_dir)
433 else:
434 os.remove(target_item_dir)
435
436 shutil.move(
437 os.path.join(lib_dir, item),
438 target_item_dir
439 )
440
441 def _warn_about_conflicts(self, to_install):
442 package_set, _dep_info = check_install_conflicts(to_install)
443 missing, conflicting = _dep_info
444
445 # NOTE: There is some duplication here from pip check
446 for project_name in missing:
447 version = package_set[project_name][0]
448 for dependency in missing[project_name]:
449 logger.critical(
450 "%s %s requires %s, which is not installed.",
451 project_name, version, dependency[1],
452 )
453
454 for project_name in conflicting:
455 version = package_set[project_name][0]
456 for dep_name, dep_version, req in conflicting[project_name]:
457 logger.critical(
458 "%s %s has requirement %s, but you'll have %s %s which is "
459 "incompatible.",
460 project_name, version, req, dep_name, dep_version,
461 )
462
463
464def get_lib_location_guesses(*args, **kwargs):
465 scheme = distutils_scheme('', *args, **kwargs)
466 return [scheme['purelib'], scheme['platlib']]
467
468
469def create_env_error_message(error, show_traceback, using_user_site):
470 """Format an error message for an EnvironmentError
471
472 It may occur anytime during the execution of the install command.
473 """
474 parts = []
475
476 # Mention the error if we are not going to show a traceback
477 parts.append("Could not install packages due to an EnvironmentError")
478 if not show_traceback:
479 parts.append(": ")
480 parts.append(str(error))
481 else:
482 parts.append(".")
483
484 # Spilt the error indication from a helper message (if any)
485 parts[-1] += "\n"
486
487 # Suggest useful actions to the user:
488 # (1) using user site-packages or (2) verifying the permissions
489 if error.errno == errno.EACCES:
490 user_option_part = "Consider using the `--user` option"
491 permissions_part = "Check the permissions"
492
493 if not using_user_site:
494 parts.extend([
495 user_option_part, " or ",
496 permissions_part.lower(),
497 ])
498 else:
499 parts.append(permissions_part)
500 parts.append(".\n")
501
502 return "".join(parts).strip() + "\n"