summaryrefslogtreecommitdiff
path: root/interfaces.py
blob: e0a904abf96a9f66da792290edc3ca3ac4c97bf0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
"""Module containing various interfaces."""

from abc import ABCMeta, abstractmethod, abstractclassmethod
import xml.etree.ElementTree as et

class XMLSerializable(metaclass=ABCMeta):
    """Interface for XML-serializable Workspace components."""
    @staticmethod
    def int_or_none(v):
        if v is None: 
            return None

        try:
            v = int(v)
        except (ValueError, TypeError):
            return None

        return v

    @staticmethod
    def indent(elem, indent=4, level=0):
        """Pretty-indent the XML tree."""
        i = "\n" + level*(indent*' ')
        if len(elem) > 0:
            if not elem.text or not elem.text.strip():
                elem.text = i + (' '*indent)
            if not elem.tail or not elem.tail.strip():
                elem.tail = i
            for elem in elem:
                XMLSerializable.indent(elem, indent=indent, level=level+1)
            if not elem.tail or not elem.tail.strip():
                elem.tail = i
        else:
            if level and (not elem.tail or not elem.tail.strip()):
                elem.tail = i

    @abstractmethod
    def serialize(self) -> et.Element:
        """Serialize the object into an XML element."""

    @abstractclassmethod
    def deserialize(cls, w: "Workspace", e: et.Element):
        """Deserialize the object from an XML element.
        
        This function may assume that all dependencies have already been loaded into the 
        passed workspace.
        """