[elbe-devel] [PATCH 2/6] elbepack: treeutils: validate values of boolean attributes

Thomas Weißschuh thomas.weissschuh at linutronix.de
Tue May 28 10:26:22 CEST 2024


According to the XML schema specification, boolean attributes have a
very limited set of valid values:

  3.2.2.1 Lexical representation
  An instance of a datatype that is defined as ·boolean· can have the
  following legal literals {true, false, 1, 0}.

  3.2.2.2 Canonical representation
  The canonical representation for boolean is the set of
  literals {true, false}.

Reflect this logic in the helper function.

While it won't make a difference at runtime, it is clearer to
understand.

Also return None if the attribute is missing.
The helper is split into its own toplevel function, as not all parts of
elbe use the etree objects but still need the functionality.

Signed-off-by: Thomas Weißschuh <thomas.weissschuh at linutronix.de>
---
 elbepack/treeutils.py | 15 +++++++++++----
 1 file changed, 11 insertions(+), 4 deletions(-)

diff --git a/elbepack/treeutils.py b/elbepack/treeutils.py
index 9df3e85d56e1..e4588bb0c488 100644
--- a/elbepack/treeutils.py
+++ b/elbepack/treeutils.py
@@ -10,6 +10,16 @@ from lxml.etree import XMLParser, parse, tostring
 # ElementTree helpers
 
 
+def xml_bool(value):
+    if value is None:
+        return None
+    if value in ('true', '1'):
+        return True
+    if value in ('false', '0'):
+        return False
+    raise ValueError(value)
+
+
 class eiter:
     def __init__(self, it):
         self.it = it
@@ -96,10 +106,7 @@ class elem(ebase):
         self.et.remove(child.et)
 
     def bool_attr(self, attrname):
-        attr = self.et.attrib.get(attrname)
-        if attr in ('true', '1'):
-            return True
-        return False
+        return xml_bool(self.et.attrib.get(attrname))
 
     def get_parent(self):
         return elem(self.et.getparent())

-- 
2.45.1



More information about the elbe-devel mailing list