Decorator that can be used to require requirements.

    :param requirements: List of requirements that should be verified
    :param none_on_failure: If true, does not raise a PrerequisiteFailedError, but instead returns None
484654
def require(*requirements, **kwargs):
    
    # TODO: require(*requirements, none_on_failure=False) is not supported by Python 2
    none_on_failure = kwargs.get('none_on_failure', False)

    def inner(f):
        @functools.wraps(f)
        def wrapper(*args, **kwargs):
            for req in requirements:
                if none_on_failure:
                    if not getattr(req, 'is_available'):
                        return None
                else:
                    getattr(req, 'require')()
            return f(*args, **kwargs)
        return wrapper
    return inner
1029700
def check_requirements(self, request=None, response=None, context=None):
        
        for requirement in self.requires:
            conclusion = requirement(response=response, request=request, context=context, module=self.api.module)
            if conclusion and conclusion is not True:
                return conclusion
851396
def pip_install_requirements(requirements, constraints=None, **options):
    
    command = ["install"]

    available_options = ('proxy', 'src', 'log', )
    for option in parse_options(options, available_options):
        command.append(option)

    command.append("-r {0}".format(requirements))
    if constraints:
        command.append("-c {0}".format(constraints))
        log("Installing from file: {} with constraints {} "
            "and options: {}".format(requirements, constraints, command))
    else:
        log("Installing from file: {} with options: {}".format(requirements,
                                                               command))
    pip_execute(command)
48195
def update_changed_requirements():
    
    reqs_path = join(env.proj_path, env.reqs_path)
    get_reqs = lambda: run("cat %s" % reqs_path, show=False)
    old_reqs = get_reqs() if env.reqs_path else ""
    yield
    if old_reqs:
        new_reqs = get_reqs()
        if old_reqs == new_reqs:
            # Unpinned requirements should always be checked.
            for req in new_reqs.split("\n"):
                if req.startswith("-e"):
                    if "@" not in req:
                        # Editable requirement without pinned commit.
                        break
                elif req.strip() and not req.startswith("#"):
                    if not set(">=<") & set(req):
                        # PyPI requirement without version.
                        break
            else:
                # All requirements are pinned.
                return
        pip("-r %s/%s" % (env.proj_path, env.reqs_path))
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)
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)
736691
def _process_requirements(requirements, cmd, cwd, saltenv, user):
    '''
    
    '''
    cleanup_requirements = []

    if requirements is not None:
        if isinstance(requirements, six.string_types):
            requirements = [r.strip() for r in requirements.split(',')]
        elif not isinstance(requirements, list):
            raise TypeError('requirements must be a string or list')

        treq = None

        for requirement in requirements:
            logger.debug('TREQ IS: %s', treq)
            if requirement.startswith('salt://'):
                cached_requirements = _get_cached_requirements(
                    requirement, saltenv
                )
                if not cached_requirements:
                    ret = {'result': False,
                           'comment': 'pip requirements file \'{0}\' not found'
                                      .format(requirement)}
                    return None, ret
                requirement = cached_requirements

            if user:
                # Need to make a temporary copy since the user will, most
                # likely, not have the right permissions to read the file

                if not treq:
                    treq = tempfile.mkdtemp()

                __salt__['file.chown'](treq, user, None)
                # In Windows, just being owner of a file isn't enough. You also
                # need permissions
                if salt.utils.platform.is_windows():
                    __utils__['dacl.set_permissions'](
                        obj_name=treq,
                        principal=user,
                        permissions='read_execute')

                current_directory = None

                if not current_directory:
                    current_directory = os.path.abspath(os.curdir)

                logger.info('_process_requirements from directory, '
                            '%s -- requirement: %s', cwd, requirement)

                if cwd is None:
                    r = requirement
                    c = cwd

                    requirement_abspath = os.path.abspath(requirement)
                    cwd = os.path.dirname(requirement_abspath)
                    requirement = os.path.basename(requirement)

                    logger.debug('\n\tcwd: %s -> %s\n\trequirement: %s -> %s\n',
                                 c, cwd, r, requirement
                                 )

                os.chdir(cwd)

                reqs = _resolve_requirements_chain(requirement)

                os.chdir(current_directory)

                logger.info('request files: %s', reqs)

                for req_file in reqs:
                    if not os.path.isabs(req_file):
                        req_file = os.path.join(cwd, req_file)

                    logger.debug('TREQ N CWD: %s -- %s -- for %s', treq, cwd, req_file)
                    target_path = os.path.join(treq, os.path.basename(req_file))

                    logger.debug('S: %s', req_file)
                    logger.debug('T: %s', target_path)

                    target_base = os.path.dirname(target_path)

                    if not os.path.exists(target_base):
                        os.makedirs(target_base, mode=0o755)
                        __salt__['file.chown'](target_base, user, None)

                    if not os.path.exists(target_path):
                        logger.debug(
                            'Copying %s to %s', req_file, target_path
                        )
                        __salt__['file.copy'](req_file, target_path)

                    logger.debug(
                        'Changing ownership of requirements file \'%s\' to '
                        'user \'%s\'', target_path, user
                    )

                    __salt__['file.chown'](target_path, user, None)

            req_args = os.path.join(treq, requirement) if treq else requirement
            cmd.extend(['--requirement', req_args])

        cleanup_requirements.append(treq)

    logger.debug('CLEANUP_REQUIREMENTS: %s', cleanup_requirements)
    return cleanup_requirements, None
1358530
def check_requirements(dist, attr, value):
    """"""
    try:
        list(pkg_resources.parse_requirements(value))
    except (TypeError,ValueError):
        raise DistutilsSetupError(
            "%r must be a string or list of strings "
            "containing valid project/version requirement specifiers" % (attr,)
        )
369784
def _install_requirements(self):
        '''
        
        '''
        if not hasattr(self, '_pkg_venv'):
            err = 'Must call build_new_virtualenv before install_requirements'
            raise Exception(err)

        cmd = None
        if self._requirements:
            LOG.debug("Installing requirements found %s in config"
                      % self._requirements)
            cmd = [os.path.join(self._pkg_venv, self._venv_pip),
                   'install'] + self._requirements

        elif _isfile(self._requirements_file):
            # Pip install
            LOG.debug("Installing requirements from requirements.txt file")
            cmd = [os.path.join(self._pkg_venv, self._venv_pip),
                   "install", "-r",
                   self._requirements_file]

        if cmd is not None:
            prc = Popen(cmd, stdout=PIPE, stderr=PIPE)
            stdout, stderr = prc.communicate()
            LOG.debug("Pip stdout: %s" % stdout)
            LOG.debug("Pip stderr: %s" % stderr)

            if prc.returncode is not 0:
                raise Exception('pip returned unsuccessfully')
1291825
def find_known_dependencies(self, requirement):
        
        logger.info("Checking for known dependencies of %s ..", requirement.name)
        known_dependencies = sorted(self.dependencies.get(requirement.name.lower(), []))
        if known_dependencies:
            logger.info("Found %s: %s", pluralize(len(known_dependencies), "known dependency", "known dependencies"),
                        concatenate(known_dependencies))
        else:
            logger.info("No known dependencies... Maybe you have a suggestion?")
        return known_dependencies
984077
def matches(self, requirement):
    """"""
    try:
      requirement = self.parse_requirement(requirement, self._interpreter)
    except ValueError as e:
      raise self.UnknownRequirement(str(e))
    return self.distribution in requirement
255497
def validate_required(self, value):
        ''' 
        '''
        if self.required and (value is None or value==''):
            raise MissingFieldError(self.name)
1175034
def parse_pip_requirements(requirement_file_path):
    
    return sorted(
        str(r.req)
        for r in parse_requirements(requirement_file_path,
                                    session=PipSession())
        if r.req
    )
248757
def _build_from_requirements(cls, req_spec):
        
        # try it without defaults already on sys.path
        # by starting with an empty path
        ws = cls([])
        reqs = parse_requirements(req_spec)
        dists = ws.resolve(reqs, Environment())
        for dist in dists:
            ws.add(dist)

        # add any missing entries from sys.path
        for entry in sys.path:
            if entry not in ws.entries:
                ws.add_entry(entry)

        # then copy back to sys.path
        sys.path[:] = ws.entries
        return ws
837168
def is_valid(self):
        
        return (
            self.requirement is not None and self.requirement.optional
        ) or bool(self._future_value)
202779
def requirements(fname):
        
        packages = Setup.read(fname, fail_silently=True).split('\n')
        packages = (p.strip() for p in packages)
        packages = (p for p in packages if p and not p.startswith('#'))
        return list(packages)
42816
def _install_requirements(path):
    
    locations = [os.path.join(path, "_blueprint"), os.path.join(path, "_base"), path]
    success = True

    for location in locations:
        try:
            with open(os.path.join(location, "requirements.txt")):
                puts("\nRequirements file found at {0}".format(os.path.join(location, "requirements.txt")))
                install_reqs = raw_input("Install requirements now with pip install -r requirements.txt? [Y/n] ")
                if not install_reqs or install_reqs.lower() == 'y':
                    pip = sh.pip.bake(_cwd=location)
                    puts("\nInstalling requirements...")
                    puts(pip("install", "-r", "requirements.txt"))
                else:
                    success = False
                    puts("Not installing requirements. This may break everything! Vaya con dios.")
        except IOError:
            pass

    return success