Convert a deps instance into requirements.
189383
def pydeps2reqs(deps):
    
    reqs = defaultdict(set)
    for k, v in list(deps.items()):
        # not a built-in
        p = v['path']
        if p and not p.startswith(sys.real_prefix):
            if p.startswith(sys.prefix) and 'site-packages' in p:
                if not p.endswith('.pyd'):
                    if '/win32/' in p.replace('\\', '/'):
                        reqs['win32'] |= set(v['imported_by'])
                    else:
                        name = k.split('.', 1)[0]
                        if name not in skiplist:
                            reqs[name] |= set(v['imported_by'])

    if '_dummy' in reqs:
        del reqs['_dummy']
    return '\n'.join(dep2req(name, reqs[name]) for name in sorted(reqs))
801771
def pip(filename):
    """"""
    requirements = []
    for line in open(join(ROOT, 'requirements', filename)):
        line = line.strip()
        if not line or '://' in line:
            continue
        match = RE_REQUIREMENT.match(line)
        if match:
            requirements.extend(pip(match.group('filename')))
        else:
            requirements.append(line)
    return requirements
617161
def _finalize_requires(self):
        
        if getattr(self, 'python_requires', None):
            self.metadata.python_requires = self.python_requires

        if getattr(self, 'extras_require', None):
            for extra in self.extras_require.keys():
                # Since this gets called multiple times at points where the
                # keys have become 'converted' extras, ensure that we are only
                # truly adding extras we haven't seen before here.
                extra = extra.split(':')[0]
                if extra:
                    self.metadata.provides_extras.add(extra)

        self._convert_extras_requirements()
        self._move_install_requirements_markers()
1012018
def convert_deps_to_pip(deps, project=None, r=True, include_index=True):
    """""""
    from .vendor.requirementslib.models.requirements import Requirement

    dependencies = []
    for dep_name, dep in deps.items():
        if project:
            project.clear_pipfile_cache()
        indexes = getattr(project, "pipfile_sources", []) if project is not None else []
        new_dep = Requirement.from_pipfile(dep_name, dep)
        if new_dep.index:
            include_index = True
        req = new_dep.as_line(sources=indexes if include_index else None).strip()
        dependencies.append(req)
    if not r:
        return dependencies

    # Write requirements.txt to tmp directory.
    from .vendor.vistir.path import create_tracked_tempfile
    f = create_tracked_tempfile(suffix="-requirements.txt", delete=False)
    f.write("\n".join(dependencies).encode("utf-8"))
    f.close()
    return f.name
640760
def _generate_requirements(self):
        """"""
        if not self._pip_packages:
            return

        reqs = ''
        for req in self._pip_packages:
                reqs += "{}\n".format(req)
        reqs_include = {
            'contents': reqs,
            'target':'opt/python/streams',
            'name': 'requirements.txt'}

        if 'opt' not in self._files:
             self._files['opt'] = [reqs_include]
        else:
             self._files['opt'].append(reqs_include)
420228
def requires(self, extras=()):
        """"""
        dm = self._dep_map
        deps = []
        deps.extend(dm.get(None, ()))
        for ext in extras:
            try:
                deps.extend(dm[safe_extra(ext)])
            except KeyError:
                raise UnknownExtra(
                    "%s has no such extra feature %r" % (self, ext)
                )
        return deps
23381
def _compute_dependencies(self):
        """"""
        dm = self.__dep_map = {None: []}

        reqs = []
        # Including any condition expressions
        for req in self._parsed_pkg_info.get_all('Requires-Dist') or []:
            reqs.extend(parse_requirements(req))

        def reqs_for_extra(extra):
            for req in reqs:
                if not req.marker or req.marker.evaluate({'extra': extra}):
                    yield req

        common = frozenset(reqs_for_extra(None))
        dm[None].extend(common)

        for extra in self._parsed_pkg_info.get_all('Provides-Extra') or []:
            s_extra = safe_extra(extra.strip())
            dm[s_extra] = list(frozenset(reqs_for_extra(extra)) - common)

        return dm
151416
def trace_requirements(requirements):
    
    requirements = tuple(pretty_req(r) for r in requirements)
    working_set = fresh_working_set()

    # breadth-first traversal:
    from collections import deque
    queue = deque(requirements)
    queued = {_package_req_to_pkg_resources_req(req.req) for req in queue}
    errors = []
    result = []
    while queue:
        req = queue.popleft()

        logger.debug('tracing: %s', req)
        try:
            dist = working_set.find_normalized(_package_req_to_pkg_resources_req(req.req))
        except pkg_resources.VersionConflict as conflict:
            dist = conflict.args[0]
            errors.append('Error: version conflict: {} ({}) <-> {}'.format(
                dist, timid_relpath(dist.location), req
            ))

        assert dist is not None, 'Should be unreachable in pip8+'
        result.append(dist_to_req(dist))

        # TODO: pip does no validation of extras. should we?
        extras = [extra for extra in req.extras if extra in dist.extras]
        for sub_req in sorted(dist.requires(extras=extras), key=lambda req: req.key):
            sub_req = InstallRequirement(sub_req, req)

            if req_cycle(sub_req):
                logger.warning('Circular dependency! %s', sub_req)
                continue
            elif sub_req.req in queued:
                logger.debug('already queued: %s', sub_req)
                continue
            else:
                logger.debug('adding sub-requirement %s', sub_req)
                queue.append(sub_req)
                queued.add(sub_req.req)

    if errors:
        raise InstallationError('\n'.join(errors))

    return result
1115198
def get_dependencies(requirement, sources):
    
    getters = [
        _get_dependencies_from_cache,
        _cached(_get_dependencies_from_json, sources=sources),
        _cached(_get_dependencies_from_pip, sources=sources),
    ]
    ireq = requirement.as_ireq()
    last_exc = None
    for getter in getters:
        try:
            result = getter(ireq)
        except Exception as e:
            last_exc = sys.exc_info()
            continue
        if result is not None:
            deps, pyreq = result
            reqs = [requirementslib.Requirement.from_line(d) for d in deps]
            return reqs, pyreq
    if last_exc:
        six.reraise(*last_exc)
    raise RuntimeError("failed to get dependencies for {}".format(
        requirement.as_line(),
    ))
163976
def update_deps(self):
        
        onelist, dependencies = [], []
        onelist = Utils().dimensional_list(self.deps)
        dependencies = Utils().remove_dbs(onelist)
        for dep in dependencies:
            deps = Requires(self.flag).sbo(dep)
            self.deps_dict[dep] = self.one_for_all(deps)
393300
def consolidate_dependencies(needs_ipython, child_program,
                             requirement_files, manual_dependencies):
    """"""
    # We get the logger here because it's not defined at module level
    logger = logging.getLogger('fades')

    if needs_ipython:
        logger.debug("Adding ipython dependency because --ipython was detected")
        ipython_dep = parsing.parse_manual(['ipython'])
    else:
        ipython_dep = {}

    if child_program:
        srcfile_deps = parsing.parse_srcfile(child_program)
        logger.debug("Dependencies from source file: %s", srcfile_deps)
        docstring_deps = parsing.parse_docstring(child_program)
        logger.debug("Dependencies from docstrings: %s", docstring_deps)
    else:
        srcfile_deps = {}
        docstring_deps = {}

    all_dependencies = [ipython_dep, srcfile_deps, docstring_deps]

    if requirement_files is not None:
        for rf_path in requirement_files:
            rf_deps = parsing.parse_reqfile(rf_path)
            logger.debug('Dependencies from requirements file %r: %s', rf_path, rf_deps)
            all_dependencies.append(rf_deps)

    manual_deps = parsing.parse_manual(manual_dependencies)
    logger.debug("Dependencies from parameters: %s", manual_deps)
    all_dependencies.append(manual_deps)

    # Merge dependencies
    indicated_deps = {}
    for dep in all_dependencies:
        for repo, info in dep.items():
            indicated_deps.setdefault(repo, set()).update(info)

    return indicated_deps
403836
def requirements(self):
        """"""
        class dotdict(dict):  # pylint: disable=invalid-name
            """Dot notation access to dictionary attributes."""

            def __getattr__(self, attr):
                value = self.get(attr)
                return dotdict(value) if isinstance(value, dict) else value

        return dotdict(self._meta.metadata.requirements)
961773
def get_requirements():
    """"""

    install_requires = []
    with open("requirements/project.txt") as f:
        for line in f:
            if not line.startswith("#"):
                install_requires.append(line.strip())
    return install_requires
577387
def parse_requirements(fname='requirements.txt'):
    
    from os.path import dirname, join, exists
    import re
    require_fpath = join(dirname(__file__), fname)
    # This breaks on pip install, so check that it exists.
    if exists(require_fpath):
        with open(require_fpath, 'r') as f:
            packages = []
            for line in f.readlines():
                line = line.strip()
                if line and not line.startswith('#'):
                    if line.startswith('-e '):
                        package = line.split('#egg=')[1]
                        packages.append(package)
                    else:
                        pat = '|'.join(['>', '>=', '=='])
                        package = re.split(pat, line)[0]
                        packages.append(package)
            return packages
    return []
1298950
def _parse_requirements(self, input):
        

        results = []

        for line in input:
            (package, version) = self._parse_line(line)
            if package:
                results.append((package, version))

        return tuple(results)
948930
def requirement_spec(package_name, *args):
    """"""
    if not args or args == (None,):
        return package_name
    version_specs = []
    for version_spec in args:
        if isinstance(version_spec, (list, tuple)):
            operator, version = version_spec
        else:
            assert isinstance(version_spec, str)
            operator = "=="
            version = version_spec
        version_specs.append("%s%s" % (operator, version))
    return "%s%s" % (package_name, ",".join(version_specs))
193386
def parse_requirements(requirements_filename):
    
    dependencies, dependency_links = [], []
    requirements_dir = os.path.dirname(requirements_filename)
    with open(requirements_filename, 'r') as stream:
        for line in stream:
            line = line.strip()
            if line.startswith("-r"):
                filename = os.path.join(requirements_dir, line[2:].strip())
                _dependencies, _dependency_links = parse_requirements(filename)
                dependencies.extend(_dependencies)
                dependency_links.extend(_dependency_links)
            elif line.startswith("http"):
                dependency_links.append(line)
            else:
                package = line.split('#')[0]
                if package:
                    dependencies.append(package)
    return dependencies, dependency_links