Пример #1
0
 def test_extras_for_editable_url_requirement(self):
     url = 'git+https://url#egg=SomeProject[ex1,ex2]'
     filename = 'filename'
     comes_from = '-r %s (line %s)' % (filename, 1)
     req = InstallRequirement.from_editable(url, comes_from=comes_from)
     assert len(req.extras) == 2
     assert req.extras == {'ex1', 'ex2'}
Пример #2
0
 def test_extras_for_editable_path_requirement(self):
     url = '.[ex1,ex2]'
     filename = 'filename'
     comes_from = '-r %s (line %s)' % (filename, 1)
     req = InstallRequirement.from_editable(url, comes_from=comes_from)
     assert len(req.extras) == 2
     assert req.extras == {'ex1', 'ex2'}
Пример #3
0
 def test_environment_marker_extras(self, data):
     """
     Test that the environment marker extras are used with
     non-wheel installs.
     """
     reqset = RequirementSet()
     req = InstallRequirement.from_editable(
         data.packages.join("LocalEnvironMarker"))
     reqset.add_requirement(req)
     finder = PackageFinder([data.find_links], [], session=PipSession())
     resolver = self._basic_resolver(finder)
     resolver.resolve(reqset)
     # This is hacky but does test both case in py2 and py3
     if sys.version_info[:2] in ((2, 7), (3, 4)):
         assert reqset.has_requirement('simple')
     else:
         assert not reqset.has_requirement('simple')
Пример #4
0
 def test_environment_marker_extras(self, data):
     """
     Test that the environment marker extras are used with
     non-wheel installs.
     """
     reqset = RequirementSet()
     req = InstallRequirement.from_editable(
         data.packages.join("LocalEnvironMarker"))
     reqset.add_requirement(req)
     finder = PackageFinder([data.find_links], [], session=PipSession())
     resolver = self._basic_resolver(finder)
     resolver.resolve(reqset)
     # This is hacky but does test both case in py2 and py3
     if sys.version_info[:2] in ((2, 7), (3, 4)):
         assert reqset.has_requirement('simple')
     else:
         assert not reqset.has_requirement('simple')
Пример #5
0
def freeze(requirement=None,
           find_links=None,
           local_only=None,
           user_only=None,
           skip_regex=None,
           isolated=False,
           wheel_cache=None,
           exclude_editable=False,
           skip=()):
    find_links = find_links or []
    skip_match = None

    if skip_regex:
        skip_match = re.compile(skip_regex).search

    dependency_links = []

    for dist in pkg_resources.working_set:
        if dist.has_metadata('dependency_links.txt'):
            dependency_links.extend(
                dist.get_metadata_lines('dependency_links.txt'))
    for link in find_links:
        if '#egg=' in link:
            dependency_links.append(link)
    for link in find_links:
        yield '-f %s' % link
    installations = {}
    for dist in get_installed_distributions(local_only=local_only,
                                            skip=(),
                                            user_only=user_only):
        try:
            req = FrozenRequirement.from_dist(dist, dependency_links)
        except RequirementParseError:
            logger.warning("Could not parse requirement: %s",
                           dist.project_name)
            continue
        if exclude_editable and req.editable:
            continue
        installations[req.name] = req

    if requirement:
        # the options that don't get turned into an InstallRequirement
        # should only be emitted once, even if the same option is in multiple
        # requirements files, so we need to keep track of what has been emitted
        # so that we don't emit it again if it's seen again
        emitted_options = set()
        # keep track of which files a requirement is in so that we can
        # give an accurate warning if a requirement appears multiple times.
        req_files = collections.defaultdict(list)
        for req_file_path in requirement:
            with open(req_file_path) as req_file:
                for line in req_file:
                    if (not line.strip() or line.strip().startswith('#')
                            or (skip_match and skip_match(line))
                            or line.startswith(
                                ('-r', '--requirement', '-Z', '--always-unzip',
                                 '-f', '--find-links', '-i', '--index-url',
                                 '--pre', '--trusted-host',
                                 '--process-dependency-links',
                                 '--extra-index-url'))):
                        line = line.rstrip()
                        if line not in emitted_options:
                            emitted_options.add(line)
                            yield line
                        continue

                    if line.startswith('-e') or line.startswith('--editable'):
                        if line.startswith('-e'):
                            line = line[2:].strip()
                        else:
                            line = line[len('--editable'):].strip().lstrip('=')
                        line_req = InstallRequirement.from_editable(
                            line,
                            isolated=isolated,
                            wheel_cache=wheel_cache,
                        )
                    else:
                        line_req = InstallRequirement.from_line(
                            COMMENT_RE.sub('', line).strip(),
                            isolated=isolated,
                            wheel_cache=wheel_cache,
                        )

                    if not line_req.name:
                        logger.info(
                            "Skipping line in requirement File [%s] because "
                            "it's not clear what it would install: %s",
                            req_file_path,
                            line.strip(),
                        )
                        logger.info(
                            "  (add #egg=PackageName to the URL to avoid"
                            " this warning)")
                    elif line_req.name not in installations:
                        # either it's not installed, or it is installed
                        # but has been processed already
                        if not req_files[line_req.name]:
                            logger.warning(
                                "Requirement File [%s] contains %s, but that "
                                "package is not installed",
                                req_file_path,
                                COMMENT_RE.sub('', line).strip(),
                            )
                        else:
                            req_files[line_req.name].append(req_file_path)
                    else:
                        yield str(installations[line_req.name]).rstrip()
                        del installations[line_req.name]
                        req_files[line_req.name].append(req_file_path)

        # Warn about requirements that were included multiple times (in a
        # single requirements File or in different requirements files).
        for name, files in six.iteritems(req_files):
            if len(files) > 1:
                logger.warning("Requirement %s included multiple times [%s]",
                               name, ', '.join(sorted(set(files))))

        yield ('## The following requirements were added by ' 'pip freeze:')
    for installation in sorted(installations.values(),
                               key=lambda x: x.name.lower()):
        if canonicalize_name(installation.name) not in skip:
            yield str(installation).rstrip()
Пример #6
0
def freeze(
        requirement=None,
        find_links=None, local_only=None, user_only=None, skip_regex=None,
        isolated=False,
        wheel_cache=None,
        exclude_editable=False,
        skip=()):
    find_links = find_links or []
    skip_match = None

    if skip_regex:
        skip_match = re.compile(skip_regex).search

    dependency_links = []

    for dist in pkg_resources.working_set:
        if dist.has_metadata('dependency_links.txt'):
            dependency_links.extend(
                dist.get_metadata_lines('dependency_links.txt')
            )
    for link in find_links:
        if '#egg=' in link:
            dependency_links.append(link)
    for link in find_links:
        yield '-f %s' % link
    installations = {}
    for dist in get_installed_distributions(local_only=local_only,
                                            skip=(),
                                            user_only=user_only):
        try:
            req = FrozenRequirement.from_dist(
                dist,
                dependency_links
            )
        except RequirementParseError:
            logger.warning(
                "Could not parse requirement: %s",
                dist.project_name
            )
            continue
        if exclude_editable and req.editable:
            continue
        installations[req.name] = req

    if requirement:
        # the options that don't get turned into an InstallRequirement
        # should only be emitted once, even if the same option is in multiple
        # requirements files, so we need to keep track of what has been emitted
        # so that we don't emit it again if it's seen again
        emitted_options = set()
        # keep track of which files a requirement is in so that we can
        # give an accurate warning if a requirement appears multiple times.
        req_files = collections.defaultdict(list)
        for req_file_path in requirement:
            with open(req_file_path) as req_file:
                for line in req_file:
                    if (not line.strip() or
                            line.strip().startswith('#') or
                            (skip_match and skip_match(line)) or
                            line.startswith((
                                    '-r', '--requirement',
                                    '-Z', '--always-unzip',
                                    '-f', '--find-links',
                                    '-i', '--index-url',
                                    '--pre',
                                    '--trusted-host',
                                    '--process-dependency-links',
                                    '--extra-index-url'))):
                        line = line.rstrip()
                        if line not in emitted_options:
                            emitted_options.add(line)
                            yield line
                        continue

                    if line.startswith('-e') or line.startswith('--editable'):
                        if line.startswith('-e'):
                            line = line[2:].strip()
                        else:
                            line = line[len('--editable'):].strip().lstrip('=')
                        line_req = InstallRequirement.from_editable(
                            line,
                            isolated=isolated,
                            wheel_cache=wheel_cache,
                        )
                    else:
                        line_req = InstallRequirement.from_line(
                            COMMENT_RE.sub('', line).strip(),
                            isolated=isolated,
                            wheel_cache=wheel_cache,
                        )

                    if not line_req.name:
                        logger.info(
                            "Skipping line in requirement file [%s] because "
                            "it's not clear what it would install: %s",
                            req_file_path, line.strip(),
                        )
                        logger.info(
                            "  (add #egg=PackageName to the URL to avoid"
                            " this warning)"
                        )
                    elif line_req.name not in installations:
                        # either it's not installed, or it is installed
                        # but has been processed already
                        if not req_files[line_req.name]:
                            logger.warning(
                                "Requirement file [%s] contains %s, but that "
                                "package is not installed",
                                req_file_path,
                                COMMENT_RE.sub('', line).strip(),
                            )
                        else:
                            req_files[line_req.name].append(req_file_path)
                    else:
                        yield str(installations[line_req.name]).rstrip()
                        del installations[line_req.name]
                        req_files[line_req.name].append(req_file_path)

        # Warn about requirements that were included multiple times (in a
        # single requirements file or in different requirements files).
        for name, files in six.iteritems(req_files):
            if len(files) > 1:
                logger.warning("Requirement %s included multiple times [%s]",
                               name, ', '.join(sorted(set(files))))

        yield (
            '## The following requirements were added by '
            'pip freeze:'
        )
    for installation in sorted(
            installations.values(), key=lambda x: x.name.lower()):
        if canonicalize_name(installation.name) not in skip:
            yield str(installation).rstrip()
Пример #7
0
 def test_url_preserved_editable_req(self):
     """Confirm the url is preserved in a editable requirement"""
     url = 'git+http://foo.com@ref#egg=foo'
     req = InstallRequirement.from_editable(url)
     assert req.link.url == url
Пример #8
0
 def test_url_preserved_editable_req(self):
     """Confirm the url is preserved in a editable requirement"""
     url = 'git+http://foo.com@ref#egg=foo'
     req = InstallRequirement.from_editable(url)
     assert req.link.url == url
Пример #9
0
    def populate_requirement_set(requirement_set, args, options, finder,
                                 session, name, wheel_cache):
        """
        Marshal cmd line args into a requirement set.
        """
        # NOTE: As a side-effect, options.require_hashes and
        #       requirement_set.require_hashes may be updated

        for filename in options.constraints:
            for req in parse_requirements(
                    filename,
                    constraint=True, finder=finder, options=options,
                    session=session, wheel_cache=wheel_cache):
                requirement_set.add_requirement(req)

        for req in args:
            requirement_set.add_requirement(
                InstallRequirement.from_line(
                    req, None, isolated=options.isolated_mode,
                    wheel_cache=wheel_cache
                )
            )

        for req in options.editables:
            requirement_set.add_requirement(
                InstallRequirement.from_editable(
                    req,
                    isolated=options.isolated_mode,
                    wheel_cache=wheel_cache
                )
            )

        for filename in options.requirements:
            for req in parse_requirements(
                    filename,
                    finder=finder, options=options, session=session,
                    wheel_cache=wheel_cache):
                requirement_set.add_requirement(req)
        # If --require-hashes was a line in a requirements file, tell
        # RequirementSet about it:
        requirement_set.require_hashes = options.require_hashes

        if not (args or options.editables or options.requirements):
            opts = {'name': name}
            if options.find_links:
                raise CommandError(
                    'You must give at least one requirement to %(name)s '
                    '(maybe you meant "pip %(name)s %(links)s"?)' %
                    dict(opts, links=' '.join(options.find_links)))
            else:
                raise CommandError(
                    'You must give at least one requirement to %(name)s '
                    '(see "pip help %(name)s")' % opts)

        # On Windows, any operation modifying pip should be run as:
        #     python -m pip ...
        # See https://github.com/pypa/pip/issues/1299 for more discussion
        should_show_use_python_msg = (
            WINDOWS and
            requirement_set.has_requirement('pip') and
            "pip" in os.path.basename(sys.argv[0])
        )
        if should_show_use_python_msg:
            new_command = [
                sys.executable, "-m", "pip"
            ] + sys.argv[1:]
            raise CommandError(
                'To modify pip, please run the following command:\n{}'
                .format(" ".join(new_command))
            )
Пример #10
-1
 def test_extras_for_editable_url_requirement(self):
     url = 'git+https://url#egg=SomeProject[ex1,ex2]'
     filename = 'filename'
     comes_from = '-r %s (line %s)' % (filename, 1)
     req = InstallRequirement.from_editable(url, comes_from=comes_from)
     assert len(req.extras) == 2
     assert req.extras == set(['ex1', 'ex2'])
Пример #11
-1
 def test_extras_for_editable_path_requirement(self):
     url = '.[ex1,ex2]'
     filename = 'filename'
     comes_from = '-r %s (line %s)' % (filename, 1)
     req = InstallRequirement.from_editable(url, comes_from=comes_from)
     assert len(req.extras) == 2
     assert req.extras == set(['ex1', 'ex2'])