|
| 1 | +from xiblint.rules import Rule |
| 2 | +from xiblint.xibcontext import XibContext |
| 3 | + |
| 4 | + |
| 5 | +class EnforceRuntimeAttributes(Rule): |
| 6 | + """ |
| 7 | + Ensures a runtime attribute is set to one of the allowed values. |
| 8 | +
|
| 9 | + You must specify a module as part of the class name if it is a custom type. |
| 10 | +
|
| 11 | + Example configuration: |
| 12 | + { |
| 13 | + "runtime_attributes": { |
| 14 | + "SomeModule.LegacyButton": { |
| 15 | + "sizeName": ["small", "large"] |
| 16 | + }, |
| 17 | + "button": { |
| 18 | + "layer.cornerRadius": [null] |
| 19 | + } |
| 20 | + } |
| 21 | + } |
| 22 | + """ |
| 23 | + def check(self, context): # type: (XibContext) -> None |
| 24 | + runtime_attributes = self.config.get('runtime_attributes', {}) |
| 25 | + |
| 26 | + for full_class_name in runtime_attributes.keys(): |
| 27 | + enforced_attributes = runtime_attributes.get(full_class_name) |
| 28 | + |
| 29 | + # Get system or custom class elements |
| 30 | + full_class_name_split = full_class_name.split(".") |
| 31 | + if len(full_class_name_split) == 1: |
| 32 | + elements = context.tree.findall(".//{}".format(full_class_name)) |
| 33 | + elif len(full_class_name_split) == 2: |
| 34 | + elements = context.tree.findall(".//*[@customClass='{}'][@customModule='{}']" |
| 35 | + .format(full_class_name_split[1], full_class_name_split[0])) |
| 36 | + |
| 37 | + for element in elements: |
| 38 | + for attribute_keyPath in enforced_attributes.keys(): |
| 39 | + attribute_allowed_values = enforced_attributes.get(attribute_keyPath) |
| 40 | + attribute_value = None |
| 41 | + |
| 42 | + attribute_list = element.find("./userDefinedRuntimeAttributes") |
| 43 | + if attribute_list is not None: |
| 44 | + attribute_element = attribute_list.find("./userDefinedRuntimeAttribute/[@keyPath='{}']" |
| 45 | + .format(attribute_keyPath)) |
| 46 | + if attribute_element is not None: |
| 47 | + attribute_value = attribute_element.get("value") |
| 48 | + |
| 49 | + if attribute_value in attribute_allowed_values: |
| 50 | + continue |
| 51 | + |
| 52 | + options_string = '`, `'.join(map(str, attribute_allowed_values)) |
| 53 | + context.error(element, '`<{}>` runtime attribute `{}` must use `{}` instead of `{}`.' |
| 54 | + .format(full_class_name, attribute_keyPath, options_string, attribute_value)) |
0 commit comments