|
| 1 | +from abc import ABC, abstractmethod |
| 2 | +from typing import Any, Dict |
| 3 | + |
| 4 | + |
| 5 | +class Action(ABC): |
| 6 | + """ |
| 7 | + Base class for Resolver function actions. Each Resolver function must subclass this, |
| 8 | + override the , and provide a execute() method |
| 9 | + """ |
| 10 | + |
| 11 | + @abstractmethod |
| 12 | + def execute(self, template: Dict[str, Any]) -> Dict[str, Any]: |
| 13 | + pass |
| 14 | + |
| 15 | + |
| 16 | +class ResolveDependsOn(Action): |
| 17 | + DependsOn = "DependsOn" |
| 18 | + |
| 19 | + def __init__(self, resolution_data: Dict[str, str]): |
| 20 | + """ |
| 21 | + Initializes ResolveDependsOn. Where data necessary to resolve execute can be provided. |
| 22 | +
|
| 23 | + :param resolution_data: Extra data necessary to resolve execute properly. |
| 24 | + """ |
| 25 | + self.resolution_data = resolution_data |
| 26 | + |
| 27 | + def execute(self, template: Dict[str, Any]) -> Dict[str, Any]: |
| 28 | + """ |
| 29 | + Resolve DependsOn when logical ids get changed when transforming (ex: AWS::Serverless::LayerVersion) |
| 30 | +
|
| 31 | + :param input_dict: Chunk of the template that is attempting to be resolved |
| 32 | + :param resolution_data: Dictionary of the original and changed logical ids |
| 33 | + :return: Modified dictionary with values resolved |
| 34 | + """ |
| 35 | + # Checks if input dict is resolvable |
| 36 | + if template is None or not self._can_handle_depends_on(input_dict=template): |
| 37 | + return template |
| 38 | + # Checks if DependsOn is valid |
| 39 | + if not (isinstance(template[self.DependsOn], (list, str))): |
| 40 | + return template |
| 41 | + # Check if DependsOn matches the original value of a changed_logical_id key |
| 42 | + for old_logical_id, changed_logical_id in self.resolution_data.items(): |
| 43 | + # Done like this as there is no other way to know if this is a DependsOn vs some value named the |
| 44 | + # same as the old logical id. (ex LayerName is commonly the old_logical_id) |
| 45 | + if isinstance(template[self.DependsOn], list): |
| 46 | + for index, value in enumerate(template[self.DependsOn]): |
| 47 | + if value == old_logical_id: |
| 48 | + template[self.DependsOn][index] = changed_logical_id |
| 49 | + elif template[self.DependsOn] == old_logical_id: |
| 50 | + template[self.DependsOn] = changed_logical_id |
| 51 | + return template |
| 52 | + |
| 53 | + def _can_handle_depends_on(self, input_dict: Dict[str, Any]) -> bool: |
| 54 | + """ |
| 55 | + Checks if the input dictionary is of length one and contains "DependsOn" |
| 56 | +
|
| 57 | + :param input_dict: the Dictionary that is attempting to be resolved |
| 58 | + :return boolean value of validation attempt |
| 59 | + """ |
| 60 | + return isinstance(input_dict, dict) and self.DependsOn in input_dict |
0 commit comments