Coverage for lib/lottie/parsers/sif/xml/utils.py: 96%

54 statements  

« prev     ^ index     » next       coverage.py v7.2.2, created at 2023-03-20 16:17 +0100

1from xml.dom import minidom 

2from distutils.util import strtobool 

3 

4from lottie.nvector import NVector 

5from lottie.parsers.sif.sif.frame_time import FrameTime 

6 

7 

8class _tag: 

9 def __init__(self, type): 

10 self.type = type 

11 

12 def __call__(self, v): 

13 return self.type(v) 

14 

15 

16bool_str = _tag(bool) 

17 

18 

19def str_to_bool(strval): 

20 return bool(strtobool(strval)) 

21 

22 

23def value_from_xml_string(xml_str, type, registry): 

24 if type in (bool_str, bool): 

25 return str_to_bool(xml_str) 

26 elif type is NVector: 

27 return NVector(*map(float, xml_str.split())) 

28 if type is FrameTime: 

29 return FrameTime.parse_string(xml_str, registry) 

30 return type(xml_str) 

31 

32 

33def value_to_xml_string(value, type): 

34 if type is bool: 

35 return "1" if value else "0" 

36 if type is bool_str: 

37 return "true" if value else "false" 

38 elif type is NVector: 

39 return " ".join(map(str, value)) 

40 return str(value) 

41 

42 

43def value_isinstance(value, type): 

44 if isinstance(type, _tag): 

45 type = type.type 

46 return isinstance(value, type) 

47 

48 

49def xml_text(node): 

50 return "".join( 

51 x.nodeValue 

52 for x in node.childNodes 

53 if x.nodeType in {minidom.Node.TEXT_NODE, minidom.Node.CDATA_SECTION_NODE} 

54 ) 

55 

56 

57def xml_make_text(dom: minidom.Document, tag_name, text): 

58 e = dom.createElement(tag_name) 

59 e.appendChild(dom.createTextNode(text)) 

60 return e 

61 

62 

63def xml_element_matches(ch: minidom.Node, tagname=None): 

64 if ch.nodeType != minidom.Node.ELEMENT_NODE: 

65 return False 

66 

67 if tagname is not None and ch.tagName != tagname: 

68 return False 

69 

70 return True 

71 

72 

73def xml_child_elements(xml: minidom.Node, tagname=None): 

74 for ch in xml.childNodes: 

75 if xml_element_matches(ch, tagname): 

76 yield ch 

77 

78 

79def xml_first_element_child(xml: minidom.Node, tagname=None, allow_none=False): 

80 for ch in xml_child_elements(xml, tagname): 

81 return ch 

82 

83 if allow_none: 83 ↛ 85line 83 didn't jump to line 85, because the condition on line 83 was never false

84 return None 

85 raise ValueError("No %s in %s" % (tagname or "child element", getattr(xml, "tagName", "node")))