예제 #1
0
    def get_model(self, api_version, kind):
        """
        Return the model class for the requested object.

        :param api_version: API version string
        :param kind: The name of object type (i.e. Service, Route, Container, etc.)
        :return: class
        """

        # Handle API paths. In the case of 'batch/', remove it completely, otherwise, replace '/' with '_'.
        api = re.sub(r'batch/', '', api_version, count=0,
                     flags=re.IGNORECASE).replace('/', '_')

        camel_kind = string_utils.snake_case_to_camel(kind)
        camel_api_version = string_utils.snake_case_to_camel(api)

        # capitalize the first letter of the string without lower-casing the remainder
        name = (camel_kind[:1].capitalize() + camel_kind[1:]).replace(
            "Api", "API")
        api = camel_api_version[:1].capitalize() + camel_api_version[1:]

        model_name = api + name
        try:
            model = self.model_class_from_name(model_name)
        except AttributeError:
            raise self.get_exception_class()(
                "Error: {} was not found in client.models. "
                "Did you specify the correct Kind and API Version?".format(
                    model_name))
        return model
    def test_cannot_handle_non_string_objects(self):
        with self.assertRaises(TypeError) as raised:
            # noinspection PyTypeChecker
            snake_case_to_camel(None)

        self.assertEqual(str(raised.exception),
                         'Expected "str", received "NoneType"')

        with self.assertRaises(TypeError) as raised:
            # noinspection PyTypeChecker
            snake_case_to_camel(False)

        self.assertEqual(str(raised.exception),
                         'Expected "str", received "bool"')

        with self.assertRaises(TypeError) as raised:
            # noinspection PyTypeChecker
            snake_case_to_camel(0)

        self.assertEqual(str(raised.exception),
                         'Expected "str", received "int"')

        with self.assertRaises(TypeError) as raised:
            # noinspection PyTypeChecker
            snake_case_to_camel([])

        self.assertEqual(str(raised.exception),
                         'Expected "str", received "list"')

        with self.assertRaises(TypeError) as raised:
            # noinspection PyTypeChecker
            snake_case_to_camel({'a': 1})

        self.assertEqual(str(raised.exception),
                         'Expected "str", received "dict"')
예제 #3
0
 def copy_attribute(cls, target, src_key, src_value):
     """ copy values from src_value to target[src_key], converting src_key and sub keys to camel case """
     src_key_camel = string_utils.snake_case_to_camel(
         src_key, upper_case_first=False)
     if isinstance(src_value, dict):
         if not target.get(src_key_camel):
             target[src_key_camel] = {}
         for key, value in iteritems(src_value):
             camel_key = string_utils.snake_case_to_camel(
                 key, upper_case_first=False)
             if isinstance(value, dict):
                 target[src_key_camel][camel_key] = {}
                 cls.copy_attribute(target[src_key_camel], key, value)
             else:
                 target[src_key_camel][camel_key] = value
     elif isinstance(src_value, list):
         if not target.get(src_key_camel):
             target[src_key_camel] = []
         for element in src_value:
             if isinstance(element, dict):
                 new_item = {}
                 for key, value in iteritems(element):
                     camel_key = string_utils.snake_case_to_camel(
                         key, upper_case_first=False)
                     cls.copy_attribute(new_item, camel_key, value)
                 target[src_key_camel].append(new_item)
             else:
                 target[src_key_camel].append(element)
     else:
         target[src_key_camel] = src_value
예제 #4
0
 def copy_attribute(cls, target, src_key, src_value):
     """ copy values from src_value to target[src_key], converting src_key and sub keys to camel case """
     src_key_camel = string_utils.snake_case_to_camel(src_key, upper_case_first=False)
     if isinstance(src_value, dict):
         if not target.get(src_key_camel):
             target[src_key_camel] = {}
         for key, value in src_value.items():
             camel_key = string_utils.snake_case_to_camel(key, upper_case_first=False)
             if isinstance(value, dict):
                 target[src_key_camel][camel_key] = {}
                 cls.copy_attribute(target[src_key_camel], key, value)
             else:
                 target[src_key_camel][camel_key] = value
     elif isinstance(src_value, list):
         if not target.get(src_key_camel):
             target[src_key_camel] = []
         for element in src_value:
             if isinstance(element, dict):
                 new_item = {}
                 for key, value in element.items():
                     camel_key = string_utils.snake_case_to_camel(key, upper_case_first=False)
                     cls.copy_attribute(new_item, camel_key, value)
                 target[src_key_camel].append(new_item)
             else:
                 target[src_key_camel].append(element)
     else:
         target[src_key_camel] = src_value
예제 #5
0
    def object_from_params(self, module_params, obj=None):
        """
        Update a model object with Ansible module param values. Optionally pass an object
        to update, otherwise a new object will be created.
        :param module_params: dict of key:value pairs
        :param obj: model object to update
        :return: updated model object
        """
        if not obj:
            obj = self.model()
            obj.kind = string_utils.snake_case_to_camel(self.kind, upper_case_first=False)
            obj.api_version = self.api_version.lower()
        for param_name, param_value in module_params.items():
            spec = self.find_arg_spec(param_name)
            if param_value is not None and spec.get('property_path'):
                prop_path = copy.copy(spec['property_path'])
                self.__set_obj_attribute(obj, prop_path, param_value, param_name)

        if self.kind.lower() == 'project' and (module_params.get('display_name') or
                                               module_params.get('description')):
            if not obj.metadata.annotations:
                obj.metadata.annotations = {}
            if module_params.get('display_name'):
                obj.metadata.annotations['openshift.io/display-name'] = module_params['display_name']
            if module_params.get('description'):
                obj.metadata.annotations['openshift.io/description'] = module_params['description']

        logger.debug("Object from params:")
        logger.debug(json.dumps(obj.to_dict(), indent=4))
        return obj
예제 #6
0
def to_camel_case(s):
    if not su.is_string(s):
        return s
    if not su.is_full_string(s):
        return s
    if su.is_camel_case(s):
        return s[0].lower()+s[1:]
    return su.snake_case_to_camel(re.sub('^[0-9_]+', '', to_snake_case(s)), upper_case_first=False)
 def __property_name_to_camel(param_name, property_name):
     new_name = property_name
     if 'annotations' not in param_name and 'labels' not in param_name and 'selector' not in param_name:
         camel_name = string_utils.snake_case_to_camel(
             property_name, upper_case_first=False)
         new_name = camel_name[1:] if camel_name.startswith(
             '_') else camel_name
     return new_name
 def test_returns_camel_case_from_correct_snake_case(self):
     self.assertEqual(snake_case_to_camel('hello_world'), 'HelloWorld')
     self.assertEqual(snake_case_to_camel('the_snake_is_green'),
                      'TheSnakeIsGreen')
     self.assertEqual(snake_case_to_camel('the_number_of_the_beast_is_666'),
                      'TheNumberOfTheBeastIs666')
     self.assertEqual(snake_case_to_camel('a_b_c_d'), 'ABCD')
     self.assertEqual(snake_case_to_camel('_one'), 'One')
     self.assertEqual(snake_case_to_camel('__one'), 'One')
     self.assertEqual(snake_case_to_camel('one_'), 'One')
     self.assertEqual(snake_case_to_camel('_one_'), 'One')
예제 #9
0
def to_class_case(s):
    if not su.is_string(s):
        return s
    if not su.is_full_string(s):
        return s
    if su.is_camel_case(s):
        return s[0].upper() + s[1:]
    sub = re.sub('^[0-9_]+', '', to_snake_case(s))
    camel = su.snake_case_to_camel(sub)
    return camel[0].upper() + camel[1:]
 def test_should_not_capitalize_first_letter_if_specified(self):
     self.assertEqual(
         snake_case_to_camel('this_will_starts_lower_case', False),
         'thisWillStartsLowerCase')
     self.assertEqual(snake_case_to_camel('hello_world', False),
                      'helloWorld')
     self.assertEqual(snake_case_to_camel('the_snake_is_green', False),
                      'theSnakeIsGreen')
     self.assertEqual(
         snake_case_to_camel('the_number_of_the_beast_is_666', False),
         'theNumberOfTheBeastIs666')
     self.assertEqual(snake_case_to_camel('a_b_c_d', False), 'aBCD')
     self.assertEqual(snake_case_to_camel('_one', False), 'one')
     self.assertEqual(snake_case_to_camel('__one', False), 'one')
     self.assertEqual(snake_case_to_camel('one_', False), 'one')
     self.assertEqual(snake_case_to_camel('_one_', False), 'one')
 def test_returns_original_string_if_not_snake_case(self):
     self.assertEqual(snake_case_to_camel(''), '')
     self.assertEqual(snake_case_to_camel('foo'), 'foo')
     self.assertEqual(snake_case_to_camel('foo bar baz'), 'foo bar baz')
     self.assertEqual(snake_case_to_camel('not_snake_!'), 'not_snake_!')
     self.assertEqual(snake_case_to_camel('(not_snake)'), '(not_snake)')
     self.assertEqual(snake_case_to_camel('123not_snake'), '123not_snake')
예제 #12
0
파일: db.py 프로젝트: cvriel/schema-tools
def _serialize(obj, camelize=True):
    results = {}
    for attr in inspect(obj).attrs:
        value = attr.value
        key = attr.key
        if camelize:
            key = snake_case_to_camel(key, upper_case_first=False)
        if value is None:
            continue
        if hasattr(value, "isoformat"):
            value = attr.value.isoformat()
        results[key] = value
    return results
예제 #13
0
def to_class_case(s):
    if not su.is_string(s):
        logger.debug('{s} is not a string'.format(s=s))
        return s
    if not su.is_full_string(s):
        logger.debug('string is blank'.format(s=s))
        return s
    if su.is_camel_case(s):
        logger.debug('string is already camel case'.format(s=s))
        return s[0].upper()+s[1:]
    sub = re.sub('^[0-9_]+', '', to_snake_case(s))
    logger.debug('sub = {sub}'.format(sub=sub))
    camel = su.snake_case_to_camel(sub)
    return camel[0].upper()+camel[1:]
예제 #14
0
파일: core.py 프로젝트: fx-kirin/kanimysql
def TableDict(table_name, conn=None):
    replace_dict = {'_table_name': table_name, '__repr__': __repr__, '__getattr__': __custom_getattr__}
    if conn:
        columns = [list(column_name.values())[0] for column_name in conn.column_name(table_name)]
        replace_dict['__init__'] = __init__
        replace_dict['__setattr__'] = __setattr__
        replace_dict['columns'] = columns
        replace_dict['_is_modified'] = False
    if isinstance(table_name, six.string_types):
        table_class_name = string_utils.snake_case_to_camel(table_name)
    else:
        table_class_name = 'TableDict'
    if six.PY2:
        table_class_name = bytes(table_name)
    return type(table_class_name, (AttrDict,), replace_dict)
예제 #15
0
def get_valid_class_name(name: str):
    name = name.replace(" ", "_")
    name = string_utils.snake_case_to_camel(name)
    if not string_utils.is_camel_case(name):
        name = name.capitalize()

    # SADL function name fix
    if name == 'sum':
        name = 'c_' + name

    first_char_ord = ord(name[0])
    if 48 <= first_char_ord <= 57:
        name = "c_" + name

    return name
예제 #16
0
    def get_model(self, api_version, kind):
        """
        Return the model class for the requested object.

        :param api_version: API version string
        :param kind: The name of object type (i.e. Service, Route, Container, etc.)
        :return: class
        """
        camel_kind = string_utils.snake_case_to_camel(kind)
        camel_api_version = string_utils.snake_case_to_camel(api_version)
        # capitalize the first letter of the string without lower-casing the remainder
        name = (camel_kind[:1].capitalize() + camel_kind[1:]).replace(
            "Api", "API")
        api = camel_api_version[:1].capitalize() + camel_api_version[1:]

        model_name = api + name
        try:
            model = self.model_class_from_name(model_name)
        except AttributeError:
            raise self.get_exception_class()(
                "Error: {} was not found in client.models. "
                "Did you specify the correct Kind and API Version?".format(
                    model_name))
        return model
    def object_from_params(self, module_params, obj=None):
        """
        Update a model object with Ansible module param values. Optionally pass an object
        to update, otherwise a new object will be created.
        :param module_params: dict of key:value pairs
        :param obj: model object to update
        :return: updated model object
        """
        if not obj:
            obj = self.model()
            obj.kind = string_utils.snake_case_to_camel(self.kind,
                                                        upper_case_first=False)
            obj.api_version = self.api_version.lower()
        for param_name, param_value in module_params.items():
            spec = self.find_arg_spec(param_name)
            if param_value is not None and spec.get('property_path'):
                prop_path = copy.copy(spec['property_path'])
                self.__set_obj_attribute(obj, prop_path, param_value,
                                         param_name)

        if self.kind.lower() == 'project' and (
                module_params.get('display_name')
                or module_params.get('description')):
            if not obj.metadata.annotations:
                obj.metadata.annotations = {}
            if module_params.get('display_name'):
                obj.metadata.annotations[
                    'openshift.io/display-name'] = module_params[
                        'display_name']
            if module_params.get('description'):
                obj.metadata.annotations[
                    'openshift.io/description'] = module_params['description']
        elif (self.kind.lower() == 'secret'
              and getattr(obj, 'string_data', None) and hasattr(obj, 'data')):
            if obj.data is None:
                obj.data = {}

            # Do a base64 conversion of `string_data` and place it in
            # `data` so that later comparisons to existing objects
            # (if any) do not result in requiring an unnecessary change.
            for key, value in obj.string_data.items():
                obj.data[key] = base64.b64encode(value)

            obj.string_data = None

        logger.debug("Object from params:")
        logger.debug(obj.to_str())
        return obj
예제 #18
0
 def __add_path_to_dict(self, request_dict, param_name, param_value, path):
     local_path = copy.copy(path)
     spec = self.find_arg_spec(param_name)
     while len(local_path):
         p = string_utils.snake_case_to_camel(local_path.pop(0), upper_case_first=False)
         if len(local_path):
             if request_dict.get(p, None) is None:
                 request_dict[p] = {}
             self.__add_path_to_dict(request_dict[p], param_name, param_value, local_path)
             break
         else:
             param_type = spec.get('type', 'str')
             if param_type == 'dict':
                 request_dict[p] = self.__dict_keys_to_camel(param_name, param_value)
             elif param_type == 'list':
                 request_dict[p] = self.__list_keys_to_camel(param_name, param_value)
             else:
                 request_dict[p] = param_value
예제 #19
0
 def __add_path_to_dict(self, request_dict, param_name, param_value, path):
     local_path = copy.copy(path)
     spec = self.find_arg_spec(param_name)
     while len(local_path):
         p = string_utils.snake_case_to_camel(local_path.pop(0), upper_case_first=False)
         if len(local_path):
             if request_dict.get(p, None) is None:
                 request_dict[p] = {}
             self.__add_path_to_dict(request_dict[p], param_name, param_value, local_path)
             break
         else:
             param_type = spec.get('type', 'str')
             if param_type == 'dict':
                 request_dict[p] = self.__dict_keys_to_camel(param_name, param_value)
             elif param_type == 'list':
                 request_dict[p] = self.__list_keys_to_camel(param_name, param_value)
             else:
                 request_dict[p] = param_value
예제 #20
0
    def object_from_params(self, module_params, obj=None):
        """
        Update a model object with Ansible module param values. Optionally pass an object
        to update, otherwise a new object will be created.
        :param module_params: dict of key:value pairs
        :param obj: model object to update
        :return: updated model object
        """
        if not obj:
            obj = self.model()
            obj.kind = string_utils.snake_case_to_camel(self.kind, upper_case_first=False)
            obj.api_version = self.api_version.lower()
        for param_name, param_value in iteritems(module_params):
            spec = self.find_arg_spec(param_name)
            if param_value is not None and spec.get('property_path'):
                prop_path = copy.copy(spec['property_path'])
                self.__set_obj_attribute(obj, prop_path, param_value, param_name)

        if self.kind.lower() == 'project' and (module_params.get('display_name') or
                                               module_params.get('description')):
            if not obj.metadata.annotations:
                obj.metadata.annotations = {}
            if module_params.get('display_name'):
                obj.metadata.annotations['openshift.io/display-name'] = module_params['display_name']
            if module_params.get('description'):
                obj.metadata.annotations['openshift.io/description'] = module_params['description']
        elif (self.kind.lower() == 'secret' and getattr(obj, 'string_data', None)
                and hasattr(obj, 'data')):
            if obj.data is None:
                obj.data = {}

            # Do a base64 conversion of `string_data` and place it in
            # `data` so that later comparisons to existing objects
            # (if any) do not result in requiring an unnecessary change.
            for key, value in iteritems(obj.string_data):
                obj.data[key] = base64.b64encode(value)

            obj.string_data = None
        return obj
예제 #21
0
def snake_case_to_capword(base):
    if not string_utils.is_snake_case(base) or base.isupper():
        base = "".join(c.upper() if i == 0 else c for i, c in enumerate(base))
        return base

    return string_utils.snake_case_to_camel(base).title()
 def snake_case(name):
     result = string_utils.snake_case_to_camel(name.replace(
         '_params', ''),
                                               upper_case_first=True)
     return result[:1].upper() + result[1:]
예제 #23
0
import os
import glob
import string_utils

font_directory = os.path.join(
    os.path.abspath(os.path.dirname(__file__)), 'files')

font_files = {
    # Gohufont11
    # Gohufont14
    # GohufontUni11
    # GohufontUni14
}

for font in list(glob.glob(os.path.join(font_directory, "*.ttf"))):
    font_name = string_utils.snake_case_to_camel(
        os.path.basename(font).replace(".ttf", ""), separator="-")
    font_files[font_name] = font
    globals()[font_name] = font
예제 #24
0
 def snake_case(name):
     result = string_utils.snake_case_to_camel(name.replace('_params', ''), upper_case_first=True)
     return result[:1].upper() + result[1:]
 def test_should_consider_custom_separator(self):
     s = 'snake-case-using-dashes'
     self.assertEqual(snake_case_to_camel(s), s)
     self.assertEqual(snake_case_to_camel(s, separator='-'),
                      'SnakeCaseUsingDashes')
예제 #26
0
 def __property_name_to_camel(param_name, property_name):
     new_name = property_name
     if 'annotations' not in param_name and 'labels' not in param_name and 'selector' not in param_name:
         camel_name = string_utils.snake_case_to_camel(property_name, upper_case_first=False)
         new_name = camel_name[1:] if camel_name.startswith('_') else camel_name
     return new_name
def strip_tags_from_operation_id(operation, _, **kwargs):
    operation_id = operation['operationId']
    if 'tags' in operation:
        for t in operation['tags']:
            operation_id = operation_id.replace(string_utils.snake_case_to_camel(t), '')
        operation['operationId'] = operation_id
예제 #28
0
    def __get_attributes(self, model_class, doc_key=None):
        """
        Recursively inspect the attributes of a given class

        :param model_class: model class
        :param doc_key: pointer to the current position in doc_string dict
        :return: None
        """
        model_name = self.helper.get_base_model_name_snake(model_class.__name__)
        for raw_attribute in dir(model_class):
            attribute = PYTHON_KEYWORD_MAPPING.get(raw_attribute, raw_attribute)
            if isinstance(getattr(model_class, raw_attribute), property):
                kind = model_class.swagger_types[raw_attribute]
                docs = inspect.getdoc(getattr(model_class, raw_attribute))
                string_list = self.__doc_clean_up(docs.split('\n'))
                if kind in ('str', 'int', 'bool', 'object', 'float'):
                    doc_key[attribute] = CommentedMap()
                    doc_key[attribute]['description'] = string_list
                    doc_key[attribute]['type'] = kind
                elif attribute.endswith('params'):
                    # Parameters are associate with a 'type' property. If the object has a 'type', then
                    #  it will also contain one or more 'param' objects, where each describes its
                    #  associated type. Rather than list every property of each param object, the
                    #  following attempts to summarize.
                    snake_name = string_utils.snake_case_to_camel(attribute.replace('_params', ''))
                    cap_snake_name = snake_name[:1].capitalize() + snake_name[1:]
                    model_name_text = ' '.join(model_name.split('_')).capitalize()
                    doc_key[attribute] = CommentedMap()
                    doc_key[attribute]['description'] = (
                        model_name_text + ' parameters when I(type) is {}.'.format(cap_snake_name)
                    )
                    doc_key[attribute]['type'] = 'complex'
                    doc_key[attribute]['returned'] = 'when I(type) is {}'.format(cap_snake_name)
                elif kind.startswith('list['):
                    class_name = kind.replace('list[', '').replace(']', '')
                    doc_key[attribute] = CommentedMap()
                    doc_key[attribute]['description'] = string_list
                    doc_key[attribute]['type'] = 'list'
                    sub_model_class = None
                    try:
                        sub_model_class = self.get_model_class(class_name)
                    except (AttributeError, KubernetesException):
                        pass
                    if sub_model_class:
                        doc_key[attribute]['contains'] = CommentedMap()
                        self.__get_attributes(sub_model_class, doc_key=doc_key[attribute]['contains'])
                    else:
                        doc_key[attribute]['contains'] = class_name
                elif kind.startswith('dict('):
                    class_name = kind.replace('dict(', '').replace(')', '')
                    doc_key[attribute] = CommentedMap()
                    doc_key[attribute]['description'] = string_list
                    doc_key[attribute]['type'] = 'complex'
                    sub_model_class = None
                    try:
                        sub_model_class = self.get_model_class(class_name)
                    except (AttributeError, KubernetesException):
                        pass
                    if sub_model_class:
                        doc_key[attribute]['contains'] = CommentedMap()
                        self.__get_attributes(sub_model_class, doc_key=doc_key[attribute]['contains'])
                    else:
                        doc_key[attribute]['contains'] = class_name
                elif kind == 'datetime':
                    doc_key[attribute] = CommentedMap()
                    doc_key[attribute]['description'] = string_list
                    doc_key[attribute]['type'] = 'complex'
                    doc_key[attribute]['contains'] = CommentedMap()
                else:
                    doc_key[attribute] = CommentedMap()
                    doc_key[attribute]['description'] = string_list
                    doc_key[attribute]['type'] = 'complex'