[PATCH net-next 3/7] tools: ynl: support ignore-index in indexed-array encoding

Asbjørn Sloth Tønnesen posted 7 patches 3 months, 2 weeks ago
[PATCH net-next 3/7] tools: ynl: support ignore-index in indexed-array encoding
Posted by Asbjørn Sloth Tønnesen 3 months, 2 weeks ago
When parsing indexed-array attributes to cli.py's --json, then
previously the index would always be set incrementally.

This patch adds support for setting arbitrary indexes, when
`ignore-index` is set to false or is unspecified.

When `ignore-index` is set to true, then it retains the current
input format, and it's alignment with the output from cli.py.

The below examples are fictive as `rates` is not used in requests.
The implementation have been tested with a newer version of the
previously posted wireguard spec[1].

When `rates` have `ignore-index` set to false (or unspecified):
  --json '{"rates":[ [0,{"rate":60}], [42,{"rate":90}] ]}'

When `rates` have `ignore-index` set to true:
  --json '{"rates":[ {"rate":60}, {"rate":90} ]}'

[1] https://lore.kernel.org/netdev/20250904-wg-ynl-rfc@fiberby.net/

Signed-off-by: Asbjørn Sloth Tønnesen <ast@fiberby.net>
---
 tools/net/ynl/pyynl/lib/ynl.py | 7 +++++--
 1 file changed, 5 insertions(+), 2 deletions(-)

diff --git a/tools/net/ynl/pyynl/lib/ynl.py b/tools/net/ynl/pyynl/lib/ynl.py
index 14c7e51db6f5c..a284bc2ad3440 100644
--- a/tools/net/ynl/pyynl/lib/ynl.py
+++ b/tools/net/ynl/pyynl/lib/ynl.py
@@ -566,8 +566,9 @@ class YnlFamily(SpecFamily):
         elif attr['type'] == 'indexed-array' and attr['sub-type'] == 'nest':
             nl_type |= Netlink.NLA_F_NESTED
             sub_space = attr['nested-attributes']
+            ignore_idx = attr.get('ignore-index', False)
             attr_payload = self._encode_indexed_array(value, sub_space,
-                                                      search_attrs)
+                                                      search_attrs, ignore_idx)
         elif attr["type"] == 'flag':
             if not value:
                 # If value is absent or false then skip attribute creation.
@@ -635,9 +636,11 @@ class YnlFamily(SpecFamily):
                                            sub_attrs)
         return attr_payload
 
-    def _encode_indexed_array(self, vals, sub_space, search_attrs):
+    def _encode_indexed_array(self, vals, sub_space, search_attrs, ignore_idx):
         attr_payload = b''
         for i, val in enumerate(vals):
+            if not ignore_idx:
+                i, val = val[0], val[1]
             idx = i | Netlink.NLA_F_NESTED
             val_payload = self._add_nest_attrs(val, sub_space, search_attrs)
             attr_payload += self._add_attr_raw(idx, val_payload)
-- 
2.51.0