Skip to content

Commit 6502d47

Browse files
stewegsamuel-gauthier
authored andcommitted
context: add root_node to find_path
This patch enhances the context find_path function to allow using relative paths as well, by adding an optional root_node attribute, from which the relative path is being evaluated. Fixes: #82 Signed-off-by: Stefan Gula <steweg@gmail.com> Signed-off-by: Samuel Gauthier <samuel.gauthier@6wind.com>
1 parent 3428ea0 commit 6502d47

File tree

2 files changed

+17
-5
lines changed

2 files changed

+17
-5
lines changed

libyang/context.py

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -175,17 +175,27 @@ def get_module(self, name: str) -> Module:
175175

176176
return Module(self, mod)
177177

178-
def find_path(self, path: str, output: bool = False) -> Iterator[SNode]:
178+
def find_path(
179+
self,
180+
path: str,
181+
output: bool = False,
182+
root_node: Optional["libyang.SNode"] = None,
183+
) -> Iterator[SNode]:
179184
if self.cdata is None:
180185
raise RuntimeError("context already destroyed")
181186

187+
if root_node is not None:
188+
ctx_node = root_node.cdata
189+
else:
190+
ctx_node = ffi.NULL
191+
182192
flags = 0
183193
if output:
184194
flags |= lib.LYS_FIND_XP_OUTPUT
185195

186196
node_set = ffi.new("struct ly_set **")
187197
if (
188-
lib.lys_find_xpath(self.cdata, ffi.NULL, str2c(path), 0, node_set)
198+
lib.lys_find_xpath(self.cdata, ctx_node, str2c(path), 0, node_set)
189199
!= lib.LY_SUCCESS
190200
):
191201
raise self.error("cannot find path")

tests/test_context.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
import os
55
import unittest
66

7-
from libyang import Context, LibyangError, Module, SRpc
7+
from libyang import Context, LibyangError, Module, SLeaf, SLeafList
88

99

1010
YANG_DIR = os.path.join(os.path.dirname(__file__), "yang")
@@ -82,8 +82,10 @@ def test_ctx_load_invalid_module(self):
8282
def test_ctx_find_path(self):
8383
with Context(YANG_DIR) as ctx:
8484
ctx.load_module("yolo-system")
85-
node = next(ctx.find_path("/yolo-system:format-disk"))
86-
self.assertIsInstance(node, SRpc)
85+
node = next(ctx.find_path("/yolo-system:conf/offline"))
86+
self.assertIsInstance(node, SLeaf)
87+
node2 = next(ctx.find_path("../number", root_node=node))
88+
self.assertIsInstance(node2, SLeafList)
8789

8890
def test_ctx_iter_modules(self):
8991
with Context(YANG_DIR) as ctx:

0 commit comments

Comments
 (0)