示例#1
0
def domainname(string):
    """Return just the domain portion of *string* or ``Undefined``."""
    from jinja2.runtime import Undefined

    try:
        return string.split('.', 1)[1]
    except IndexError:
        return Undefined(hint=f"No domain in {string!r}")
示例#2
0
 def second(self, input_value):
     try:
         i = iter(input_value)
         i.next()
         return i.next()
     except StopIteration:
         # FIXME: supposed to raise an exception but it doesn't happen
         return Undefined()
示例#3
0
 def test_xproto_first_non_empty(self):
     self.assertEqual(xproto_first_non_empty(["a"]), "a")
     self.assertEqual(xproto_first_non_empty([None, "a"]), "a")
     self.assertEqual(xproto_first_non_empty([None]), None)
     self.assertEqual(xproto_first_non_empty([]), None)
     self.assertEqual(xproto_first_non_empty([False, True]), False)
     self.assertEqual(xproto_first_non_empty([None, "Foo", True]), "Foo")
     self.assertEqual(xproto_first_non_empty(["", "Foo", True]), "Foo")
     self.assertEqual(xproto_first_non_empty([Undefined(), "Foo", True]),
                      "Foo")
示例#4
0
    def raw_get(self, host_name):
        '''
        Similar to __getitem__, however the returned data is not run through
        the templating engine to expand variables in the hostvars.
        '''
        host = self._find_host(host_name)
        if host is None:
            return Undefined(name="hostvars['%s']" % host_name)

        return self._variable_manager.get_vars(host=host, include_hostvars=False)
示例#5
0
    def _readable_size(self, size, precision, multiple, prefixes):
        if not size:
            return Undefined()

        index = 0
        while size >= multiple:
            size /= multiple
            index += 1

        return ("%%0.%df %%sB" % precision) % (size, prefixes[index])
示例#6
0
    def test_assert_defined(self):
        with self.assertRaises(AssertionError):
            assert_defined(Undefined())

        value = R.string.test_message
        returned_value = assert_defined(value)
        self.assertEqual(value, returned_value)

        value = R.dimen.test_int
        returned_value = assert_defined(value)
        self.assertEqual(value, returned_value)
示例#7
0
 def __getattr__(self, attribute):
     instance = self._get_instance()
     if hasattr(instance, "get_attribute"):
         try:
             value = instance.get_attribute(attribute).get_value()
             return JinjaDynamicProxy.return_value(value)
         except (OptionalValueException, NotFoundException):
             return Undefined("variable %s not set on %s" % (attribute, instance), instance, attribute)
     else:
         # A native python object such as a dict
         return getattr(instance, attribute)
示例#8
0
def exclude_join(value):
    '''Return a string representation of the list of values in the
    exclude field of the passed dict.

    Ansible does not provide us an easy way to omit the value directly in
    existing Jinja filters if there is no list while also joining the
    values together when there is a list. Returning "Undefined" from here
    allows us to default to omitting the value while stlil getting the
    joined string if the value is defined'''
    if 'exclude' in value:
        return ' '.join(value['exclude'])
    return Undefined()
示例#9
0
    def lang_text(source, language, order=None):
        text = None
        if source and isinstance(source, dict):
            text = source.get(language)
            if not text:
                for key in (order or sorted(source.keys())):
                    text = source.get(key)
                    if text:
                        break
        if not text:
            text = Undefined()

        return text
    def selectattr2(self, environment, seq, attr, func_name, *args, **kwargs):
        """Filter a sequence of objects by applying a test to the specified
        attribute of each object, and only selecting the objects with the test
        succeeding.

        The filter works much like the 'selectattr', but it does not fail in
        case an attribute doesn't exists. In case an attribute is missing, a
        default value is used. The default value can be specified as a
        keyed-arg.

        Args:
            seq (Iterable): The sequence to be filtered.
            attr (str): The attribute used for filtering.
            func_name (str): The name of filter function.

        Raises:
            errors.AnsibleFilterError: Raised if 'seq' is not an iterable and
            doesn't contain a mapping.

        Yields:
            The next item of the sequence, that passes the test.

        Examples:
            {{ users | selectattr2('state', '==', 'present', default='present') | list }}
        """
        if not isinstance(seq, Iterable):
            raise errors.AnsibleFilterError(
                "'{}' is not an iterable".format(seq))

        default = kwargs.pop('default', Undefined())
        attr = [int(x) if x.isdigit() else x for x in attr.split(".")]

        def func(item):
            if not isinstance(item, dict):
                raise errors.AnsibleFilterError(
                    "'{}' is not a mapping".format(item))

            for part in attr:
                item = environment.getitem(item, part)
                if isinstance(item, Undefined):
                    item = default
                    break

            return environment.call_test(func_name, item, args, kwargs)

        if seq:
            for item in seq:
                if func(item):
                    yield item
示例#11
0
def extract(item, container, morekeys=None):
    from jinja2.runtime import Undefined

    value = container[item]

    if value is not Undefined and morekeys is not None:
        if not isinstance(morekeys, list):
            morekeys = [morekeys]

        try:
            value = reduce(lambda d, k: d[k], morekeys, value)
        except KeyError:
            value = Undefined()

    return value
示例#12
0
def context_call(self, context_obj, *args, **kwargs):
    # 一般只是本地的 jade 才会调用到,外部的实际走evn_call
    if not hasattr(context_obj, '__call__'):  # 不可 call, 可能仅仅是 property
        return context_obj
    if isinstance(context_obj, Undefined):
        return ''
    try:
        value = old_context_call(self, context_obj, *args, **kwargs)
        if value is None:
            value = Undefined()
        return value
    except HTTPException as e:
        raise e
    except TemplateDebugException as e:
        raise e
    except TypeError as e:
        if hasattr(e, 'message') and 'not callable' in e.message:
            # 被调用的函数不可被call,返回原始值
            return context_obj
        else:
            # sentry_client.captureException()
            message = getattr(e, 'message', None) or ''
            if message:
                return message
            error_info = 'context_call error:* %s, ** %s; %s' % (
                smart_unicode(args), smart_unicode(kwargs), message)
            return error_info
    except Exception as e:
        if isinstance(context_obj, Macro):
            pass
        else:
            if sentry_client:
                sentry_client.captureException()  # todo 目前这个错误还是会进行捕获

        message = getattr(e, 'message', None) or ''
        object_name = getattr(context_obj, '__name__', None) or ''
        if DEBUG:
            print 'context_call error\n', context_obj, args, kwargs
        if message:
            error_info = message
        else:
            error_info = 'context_call error: %s, * %s, ** %s; %s' % (
                object_name, smart_unicode(args), smart_unicode(kwargs),
                message)

        return '<error>%s</error>' % error_info
示例#13
0
 def __init__(self, *args, **kwargs):
     self._empty_list = []
     Undefined.__init__(self, *args, **kwargs)