blob: 7ed7159dc102573a8691b7b62a1ebf15468d26a2 [file] [log] [blame]
Javi Merinoaace7c02015-08-10 14:10:47 +01001# Copyright 2015-2015 ARM Limited
Kapileshwar Singhfb8fa1a2015-02-11 17:21:04 +00002#
Javi Merinoaace7c02015-08-10 14:10:47 +01003# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14#
15
Kapileshwar Singhfb8fa1a2015-02-11 17:21:04 +000016
17"""The idea is to create a wrapper class that
18returns a Type of a Class dynamically created based
19on the input parameters. Similar to a factory design
20pattern
21"""
22from cr2.base import Base
23import re
24from cr2.run import Run
25
26
Javi Merino6f34d902015-02-21 11:39:09 +000027def default_init(self):
Kapileshwar Singhfb8fa1a2015-02-11 17:21:04 +000028 """Default Constructor for the
29 Dynamic MetaClass
30 """
31
32 super(type(self), self).__init__(
Kapileshwar Singhfb8fa1a2015-02-11 17:21:04 +000033 unique_word=self.unique_word,
Kapileshwar Singh7a709132015-03-27 17:45:22 +000034 parse_raw=self.parse_raw
Kapileshwar Singhfb8fa1a2015-02-11 17:21:04 +000035 )
36
37
38class DynamicTypeFactory(type):
39
40 """Override the type class to create
41 a dynamic type on the fly
42 """
43
44 def __new__(mcs, name, bases, dct):
45 """Override the new method"""
46 return type.__new__(mcs, name, bases, dct)
47
48 def __init__(cls, name, bases, dct):
49 """Override the constructor"""
50 super(DynamicTypeFactory, cls).__init__(name, bases, dct)
51
52
53def _get_name(name):
54 """Internal Method to Change camelcase to
55 underscores. CamelCase -> camel_case
56 """
57 return re.sub('(?!^)([A-Z]+)', r'_\1', name).lower()
58
59
Kapileshwar Singh7a709132015-03-27 17:45:22 +000060def register_dynamic(class_name, unique_word, scope="all",
61 parse_raw=False):
Kapileshwar Singhfb8fa1a2015-02-11 17:21:04 +000062 """Create a Dynamic Type and register
63 it with the cr2 Framework"""
64
65 dyn_class = DynamicTypeFactory(
66 class_name, (Base,), {
67 "__init__": default_init,
68 "unique_word": unique_word,
Kapileshwar Singh7a709132015-03-27 17:45:22 +000069 "name": _get_name(class_name),
70 "parse_raw" : parse_raw
Kapileshwar Singhfb8fa1a2015-02-11 17:21:04 +000071 }
72 )
73 Run.register_class(dyn_class, scope)
74 return dyn_class
75
76
77def register_class(cls):
78 """Register a new class implementation
79 Should be used when the class has
80 complex helper methods and does not
81 expect to use the default constructor
82 """
83
84 # Check the argspec of the class
85 Run.register_class(cls)