forked from CESNET/libyang-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathschema.py
More file actions
2596 lines (2047 loc) · 85.1 KB
/
schema.py
File metadata and controls
2596 lines (2047 loc) · 85.1 KB
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) 2018-2019 Robin Jarry
# Copyright (c) 2021 RACOM s.r.o.
# SPDX-License-Identifier: MIT
from contextlib import suppress
from typing import IO, Any, Dict, Iterator, List, Optional, Tuple, Union
from _libyang import ffi, lib
from .util import (
IOType,
LibyangError,
c2str,
init_output,
ly_array_iter,
ly_list_iter,
str2c,
)
# -------------------------------------------------------------------------------------
def schema_in_format(fmt_string: str) -> int:
if fmt_string == "yang":
return lib.LYS_IN_YANG
if fmt_string == "yin":
return lib.LYS_IN_YIN
raise ValueError("unknown schema input format: %r" % fmt_string)
# -------------------------------------------------------------------------------------
def schema_out_format(fmt_string: str) -> int:
if fmt_string == "yang":
return lib.LYS_OUT_YANG
if fmt_string == "yin":
return lib.LYS_OUT_YIN
if fmt_string == "tree":
return lib.LYS_OUT_TREE
raise ValueError("unknown schema output format: %r" % fmt_string)
# -------------------------------------------------------------------------------------
def printer_flags(
no_substmt: bool = False,
shrink: bool = False,
) -> int:
flags = 0
if no_substmt:
flags |= lib.LYS_PRINT_NO_SUBSTMT
if shrink:
flags |= lib.LYS_PRINT_SHRINK
return flags
# -------------------------------------------------------------------------------------
class Module:
__slots__ = ("context", "cdata", "__dict__")
def __init__(self, context: "libyang.Context", cdata):
self.context = context
self.cdata = cdata # C type: "struct lys_module *"
def name(self) -> str:
return c2str(self.cdata.name)
def prefix(self) -> str:
return c2str(self.cdata.prefix)
def description(self) -> Optional[str]:
return c2str(self.cdata.dsc)
def filepath(self) -> Optional[str]:
return c2str(self.cdata.filepath)
def implemented(self) -> bool:
return bool(self.cdata.implemented)
def feature_enable(self, name: str) -> None:
p = str2c(name)
q = ffi.new("char *[2]", [p, ffi.NULL])
ret = lib.lys_set_implemented(self.cdata, q)
if ret != lib.LY_SUCCESS:
raise self.context.error("no such feature: %r" % name)
def feature_enable_all(self) -> None:
self.feature_enable("*")
def feature_disable_all(self) -> None:
val = ffi.new("char **", ffi.NULL)
ret = lib.lys_set_implemented(self.cdata, val)
if ret != lib.LY_SUCCESS:
raise self.context.error("cannot disable all features")
def feature_state(self, name: str) -> bool:
ret = lib.lys_feature_value(self.cdata, str2c(name))
if ret == lib.LY_SUCCESS:
return True
if ret == lib.LY_ENOT:
return False
raise self.context.error("no such feature: %r" % name)
def features(self) -> Iterator["Feature"]:
features_list = []
f = ffi.NULL
idx = ffi.new("uint32_t *")
while True:
f = lib.lysp_feature_next(f, self.cdata.parsed, idx)
if f == ffi.NULL:
break
features_list.append(f)
for i in features_list:
yield Feature(self.context, i)
def get_feature(self, name: str) -> "Feature":
for f in self.features():
if f.name() == name:
return f
raise self.context.error("no such feature: %r" % name)
def revisions(self) -> Iterator["Revision"]:
for revision in ly_array_iter(self.cdata.parsed.revs):
yield Revision(self.context, revision, self)
def typedefs(self) -> Iterator["Typedef"]:
for typedef in ly_array_iter(self.cdata.parsed.typedefs):
yield Typedef(self.context, typedef)
def get_typedef(self, name: str) -> Optional["Typedef"]:
for typedef in self.typedefs():
if typedef.name() != name:
continue
return typedef
return None
def imports(self) -> Iterator["Import"]:
for i in ly_array_iter(self.cdata.parsed.imports):
yield Import(self.context, i, self)
def get_module_from_prefix(self, prefix: str) -> Optional["Module"]:
for i in self.imports():
if i.prefix() != prefix:
continue
return self.context.get_module(i.name())
return None
def __iter__(self) -> Iterator["SNode"]:
return self.children()
def children(
self, types: Optional[Tuple[int, ...]] = None, with_choice: bool = False
) -> Iterator["SNode"]:
return iter_children(
self.context, self.cdata, types=types, with_choice=with_choice
)
def parsed_children(self) -> Iterator["PNode"]:
for c in ly_list_iter(self.cdata.parsed.data):
yield PNode.new(self.context, c, self)
def groupings(self) -> Iterator["PGrouping"]:
for g in ly_list_iter(self.cdata.parsed.groupings):
yield PGrouping(self.context, g, self)
def augments(self) -> Iterator["PAugment"]:
for a in ly_array_iter(self.cdata.parsed.augments):
yield PAugment(self.context, a, self)
def actions(self) -> Iterator["PAction"]:
for a in ly_list_iter(self.cdata.parsed.rpcs):
yield PAction(self.context, a, self)
def notifications(self) -> Iterator["PNotif"]:
for n in ly_list_iter(self.cdata.parsed.notifs):
yield PNotif(self.context, n, self)
def identities(self) -> Iterator["Identity"]:
for i in ly_array_iter(self.cdata.identities):
yield Identity(self.context, i)
def parsed_identities(self) -> Iterator["PIdentity"]:
for i in ly_array_iter(self.cdata.parsed.identities):
yield PIdentity(self.context, i, self)
def extensions(self) -> Iterator["ExtensionCompiled"]:
compiled = ffi.cast("struct lysc_module *", self.cdata.compiled)
if compiled == ffi.NULL:
return
exts = ffi.cast("struct lysc_ext_instance *", self.cdata.compiled.exts)
if exts == ffi.NULL:
return
for extension in ly_array_iter(exts):
yield ExtensionCompiled(self.context, extension)
def get_extension(
self, name: str, prefix: Optional[str] = None, arg_value: Optional[str] = None
) -> Optional["ExtensionCompiled"]:
for ext in self.extensions():
if ext.name() != name:
continue
if prefix is not None and ext.module().name() != prefix:
continue
if arg_value is not None and ext.argument() != arg_value:
continue
return ext
return None
def __str__(self) -> str:
return self.name()
def print(
self,
fmt: str,
out_type: IOType,
out_target: Union[IO, str, None] = None,
printer_no_substmt: bool = False,
printer_shrink: bool = False,
) -> Union[str, bytes, None]:
fmt = schema_out_format(fmt)
flags = printer_flags(no_substmt=printer_no_substmt, shrink=printer_shrink)
out_data = ffi.new("struct ly_out **")
ret, output = init_output(out_type, out_target, out_data)
if ret != lib.LY_SUCCESS:
raise self.context.error("failed to initialize output target")
ret = lib.lys_print_module(out_data[0], self.cdata, fmt, 0, flags)
if output is not None:
tmp = output[0]
output = c2str(tmp)
lib.free(tmp)
lib.ly_out_free(out_data[0], ffi.NULL, False)
if ret != lib.LY_SUCCESS:
raise self.context.error("failed to write data")
return output
def print_mem(
self,
fmt: str = "tree",
printer_no_substmt: bool = False,
printer_shrink: bool = False,
) -> Union[str, bytes]:
return self.print(
fmt,
IOType.MEMORY,
None,
printer_no_substmt=printer_no_substmt,
printer_shrink=printer_shrink,
)
def print_file(
self,
fileobj: IO,
fmt: str = "tree",
printer_no_substmt: bool = False,
printer_shrink: bool = False,
) -> None:
return self.print(
fmt,
IOType.FD,
fileobj,
printer_no_substmt=printer_no_substmt,
printer_shrink=printer_shrink,
)
def parse_data_dict(
self,
dic: Dict[str, Any],
no_state: bool = False,
validate_present: bool = False,
validate: bool = True,
strict: bool = False,
rpc: bool = False,
rpcreply: bool = False,
notification: bool = False,
store_only: bool = False,
) -> "libyang.data.DNode":
"""
Convert a python dictionary to a DNode object following the schema of this
module. The returned value is always a top-level data node (i.e.: without
parent).
:arg dic:
The python dictionary to convert.
:arg no_state:
Consider state data not allowed and raise an error during validation if they are found.
:arg validate_present:
Validate result of the operation against schema.
:arg validate:
Run validation on result of the operation.
:arg strict:
Instead of ignoring data without schema definition, raise an error.
:arg rpc:
Data represents RPC or action input parameters.
:arg rpcreply:
Data represents RPC or action output parameters.
:arg notification:
Data represents a NETCONF notification.
"""
from .data import dict_to_dnode # circular import
return dict_to_dnode(
dic,
self,
no_state=no_state,
validate_present=validate_present,
validate=validate,
strict=strict,
rpc=rpc,
rpcreply=rpcreply,
notification=notification,
store_only=store_only,
)
# -------------------------------------------------------------------------------------
class Revision:
__slots__ = ("context", "cdata", "module", "__dict__")
def __init__(self, context: "libyang.Context", cdata, module):
self.context = context
self.cdata = cdata # C type: "struct lysp_revision *"
self.module = module
def date(self) -> str:
return c2str(self.cdata.date)
def description(self) -> Optional[str]:
return c2str(self.cdata.dsc)
def reference(self) -> Optional[str]:
return c2str(self.cdata.ref)
def extensions(self) -> Iterator["ExtensionParsed"]:
for ext in ly_array_iter(self.cdata.exts):
yield ExtensionParsed(self.context, ext, self.module)
def get_extension(
self, name: str, prefix: Optional[str] = None, arg_value: Optional[str] = None
) -> Optional["ExtensionParsed"]:
for ext in self.extensions():
if ext.name() != name:
continue
if prefix is not None and ext.module().name() != prefix:
continue
if arg_value is not None and ext.argument() != arg_value:
continue
return ext
return None
def __repr__(self):
cls = self.__class__
return "<%s.%s: %s>" % (cls.__module__, cls.__name__, str(self))
def __str__(self):
return self.date()
# -------------------------------------------------------------------------------------
class Import:
__slots__ = ("context", "cdata", "module", "__dict__")
def __init__(self, context: "libyang.Context", cdata, module):
self.context = context
self.cdata = cdata # C type: "struct lysp_import *"
self.module = module
def name(self) -> str:
return c2str(self.cdata.name)
def prefix(self) -> Optional[str]:
return c2str(self.cdata.prefix)
def description(self) -> Optional[str]:
return c2str(self.cdata.dsc)
def reference(self) -> Optional[str]:
return c2str(self.cdata.ref)
def extensions(self) -> Iterator["ExtensionParsed"]:
for ext in ly_array_iter(self.cdata.exts):
yield ExtensionParsed(self.context, ext, self.module)
def get_extension(
self, name: str, prefix: Optional[str] = None, arg_value: Optional[str] = None
) -> Optional["ExtensionParsed"]:
for ext in self.extensions():
if ext.name() != name:
continue
if prefix is not None and ext.module().name() != prefix:
continue
if arg_value is not None and ext.argument() != arg_value:
continue
return ext
return None
def __repr__(self):
cls = self.__class__
return "<%s.%s: %s>" % (cls.__module__, cls.__name__, str(self))
def __str__(self):
return self.name()
# -------------------------------------------------------------------------------------
class Extension:
__slots__ = ("context", "cdata", "__dict__")
def __init__(self, context: "libyang.Context", cdata):
self.context = context
self.cdata = cdata
def argument(self) -> Optional[str]:
return c2str(self.cdata.argument)
def name(self) -> str:
return str(self.cdata)
def __repr__(self):
cls = self.__class__
return "<%s.%s: %s>" % (cls.__module__, cls.__name__, str(self))
def __str__(self):
return self.name()
# -------------------------------------------------------------------------------------
class ExtensionParsed(Extension):
__slots__ = ("module_parent",)
def __init__(self, context: "libyang.Context", cdata, module_parent: Module = None):
super().__init__(context, cdata)
self.module_parent = module_parent
def _module_from_parsed(self) -> Module:
prefix = c2str(self.cdata.name).split(":")[0]
if self.module_parent is None:
raise self.context.error("cannot get module")
for cdata_imp_mod in ly_array_iter(self.module_parent.cdata.parsed.imports):
if ffi.string(cdata_imp_mod.prefix).decode() == prefix:
return Module(self.context, cdata_imp_mod.module)
raise self.context.error("cannot get module")
def name(self) -> str:
return c2str(self.cdata.name).split(":")[1]
def module(self) -> Module:
return self._module_from_parsed()
def parent_node(self) -> Optional[Union["PNode", "PIdentity"]]:
if self.cdata.parent_stmt == lib.LY_STMT_IDENTITY:
cdata = ffi.cast("struct lysp_ident *", self.cdata.parent)
return PIdentity(self.context, cdata, self.module_parent)
if bool(self.cdata.parent_stmt & lib.LY_STMT_NODE_MASK):
try:
return PNode.new(self.context, self.cdata.parent, self.module_parent)
except LibyangError:
return None
return None
def extensions(self) -> Iterator["ExtensionParsed"]:
for ext in ly_array_iter(self.cdata.exts):
yield ExtensionParsed(self.context, ext, self.module_parent)
# -------------------------------------------------------------------------------------
class ExtensionCompiled(Extension):
__slots__ = ("cdata_def",)
def __init__(self, context: "libyang.Context", cdata):
super().__init__(context, cdata)
self.cdata_def = getattr(cdata, "def", None)
def name(self) -> str:
return c2str(self.cdata_def.name)
def module(self) -> Module:
if not self.cdata_def.module:
raise self.context.error("cannot get module")
return Module(self.context, self.cdata_def.module)
def parent_node(self) -> Optional[Union["SNode", "Identity"]]:
if self.cdata.parent_stmt == lib.LY_STMT_IDENTITY:
cdata = ffi.cast("struct lysc_ident *", self.cdata.parent)
return Identity(self.context, cdata)
if bool(self.cdata.parent_stmt & lib.LY_STMT_NODE_MASK):
try:
return SNode.new(self.context, self.cdata.parent)
except LibyangError:
return None
return None
def extensions(self) -> Iterator["ExtensionCompiled"]:
for ext in ly_array_iter(self.cdata.exts):
yield ExtensionCompiled(self.context, ext)
# -------------------------------------------------------------------------------------
class _EnumBit:
__slots__ = ("context", "cdata", "__dict__")
def __init__(self, context: "libyang.Context", cdata):
self.context = context
self.cdata = cdata # C type "struct lys_type_bit" or "struct lys_type_enum"
def position(self) -> int:
return self.cdata.position
def value(self) -> int:
return self.cdata.value
def name(self) -> str:
return c2str(self.cdata.name)
def description(self) -> str:
return c2str(self.cdata.dsc)
def deprecated(self) -> bool:
return bool(self.cdata.flags & lib.LYS_STATUS_DEPRC)
def obsolete(self) -> bool:
return bool(self.cdata.flags & lib.LYS_STATUS_OBSLT)
def status(self) -> str:
if self.cdata.flags & lib.LYS_STATUS_OBSLT:
return "obsolete"
if self.cdata.flags & lib.LYS_STATUS_DEPRC:
return "deprecated"
return "current"
def __repr__(self):
cls = self.__class__
return "<%s.%s: %s>" % (cls.__module__, cls.__name__, self)
def __str__(self):
return self.name()
# -------------------------------------------------------------------------------------
class Enum(_EnumBit):
pass
# -------------------------------------------------------------------------------------
class Bit(_EnumBit):
pass
# -------------------------------------------------------------------------------------
class Pattern:
__slots__ = ("context", "cdata", "cdata_parsed")
def __init__(self, context: "libyang.Context", cdata, cdata_parsed=None):
self.context = context
self.cdata = cdata # C type: "struct lysc_pattern *"
self.cdata_parsed = cdata_parsed # C type: "struct lysp_restr *"
def expression(self) -> str:
if self.cdata is None and self.cdata_parsed:
return c2str(self.cdata_parsed.arg.str + 1)
return c2str(self.cdata.expr)
def inverted(self) -> bool:
if self.cdata is None and self.cdata_parsed:
return self.cdata_parsed.arg.str[0] == b"\x15"
return self.cdata.inverted
def error_message(self) -> Optional[str]:
if self.cdata is None and self.cdata_parsed:
return c2str(self.cdata_parsed.emsg)
return c2str(self.cdata.emsg) if self.cdata.emsg != ffi.NULL else None
# -------------------------------------------------------------------------------------
class Type:
__slots__ = ("context", "cdata", "cdata_parsed", "__dict__")
UNKNOWN = lib.LY_TYPE_UNKNOWN
BINARY = lib.LY_TYPE_BINARY
UINT8 = lib.LY_TYPE_UINT8
UINT16 = lib.LY_TYPE_UINT16
UINT32 = lib.LY_TYPE_UINT32
UINT64 = lib.LY_TYPE_UINT64
STRING = lib.LY_TYPE_STRING
BITS = lib.LY_TYPE_BITS
BOOL = lib.LY_TYPE_BOOL
DEC64 = lib.LY_TYPE_DEC64
EMPTY = lib.LY_TYPE_EMPTY
ENUM = lib.LY_TYPE_ENUM
IDENT = lib.LY_TYPE_IDENT
INST = lib.LY_TYPE_INST
LEAFREF = lib.LY_TYPE_LEAFREF
UNION = lib.LY_TYPE_UNION
INT8 = lib.LY_TYPE_INT8
INT16 = lib.LY_TYPE_INT16
INT32 = lib.LY_TYPE_INT32
INT64 = lib.LY_TYPE_INT64
BASENAMES = {
UNKNOWN: "unknown",
BINARY: "binary",
UINT8: "uint8",
UINT16: "uint16",
UINT32: "uint32",
UINT64: "uint64",
STRING: "string",
BITS: "bits",
BOOL: "boolean",
DEC64: "decimal64",
EMPTY: "empty",
ENUM: "enumeration",
IDENT: "identityref",
INST: "instance-id",
LEAFREF: "leafref",
UNION: "union",
INT8: "int8",
INT16: "int16",
INT32: "int32",
INT64: "int64",
}
def __init__(self, context: "libyang.Context", cdata, cdata_parsed):
self.context = context
self.cdata = cdata # C type: "struct lysc_type*"
self.cdata_parsed = cdata_parsed # C type: "struct lysp_type*"
def get_bases(self) -> Iterator["Type"]:
if self.cdata.basetype == lib.LY_TYPE_LEAFREF:
yield from self.leafref_type().get_bases()
elif self.cdata.basetype == lib.LY_TYPE_UNION:
for t in self.union_types():
yield from t.get_bases()
else: # builtin type
yield self
def name(self) -> str:
if self.cdata_parsed is not None and self.cdata_parsed.name:
return c2str(self.cdata_parsed.name)
return self.basename()
def description(self) -> Optional[str]:
typedef = self.typedef()
if typedef:
return typedef.description()
return None
def base(self) -> int:
return self.cdata.basetype
def bases(self) -> Iterator[int]:
for b in self.get_bases():
yield b.base()
def basename(self) -> str:
return self.BASENAMES.get(self.cdata.basetype, "unknown")
def basenames(self) -> Iterator[str]:
for b in self.get_bases():
yield b.basename()
def leafref_type(self) -> Optional["Type"]:
if self.cdata.basetype != self.LEAFREF:
return None
lr = ffi.cast("struct lysc_type_leafref *", self.cdata)
return Type(self.context, lr.realtype, None)
def leafref_path(self) -> Optional["str"]:
if self.cdata.basetype != self.LEAFREF:
return None
lr = ffi.cast("struct lysc_type_leafref *", self.cdata)
return c2str(lib.lyxp_get_expr(lr.path))
def identity_bases(self) -> Iterator["Identity"]:
if self.cdata.basetype != lib.LY_TYPE_IDENT:
return
ident = ffi.cast("struct lysc_type_identityref *", self.cdata)
for b in ly_array_iter(ident.bases):
yield Identity(self.context, b)
def typedef(self) -> "Typedef":
if ":" in self.name():
module_prefix, type_name = self.name().split(":")
import_module = self.module().get_module_from_prefix(module_prefix)
if import_module:
return import_module.get_typedef(type_name)
return None
def union_types(self, with_typedefs: bool = False) -> Iterator["Type"]:
if self.cdata.basetype != self.UNION:
return
typedef = self.typedef()
t = ffi.cast("struct lysc_type_union *", self.cdata)
if self.cdata_parsed and self.cdata_parsed.types != ffi.NULL:
for union_type, union_type_parsed in zip(
ly_array_iter(t.types), ly_array_iter(self.cdata_parsed.types)
):
yield Type(self.context, union_type, union_type_parsed)
elif (
with_typedefs
and typedef
and typedef.cdata
and typedef.cdata.type.types != ffi.NULL
):
for union_type, union_type_parsed in zip(
ly_array_iter(t.types), ly_array_iter(typedef.cdata.type.types)
):
yield Type(self.context, union_type, union_type_parsed)
else:
for union_type in ly_array_iter(t.types):
yield Type(self.context, union_type, None)
def enums(self) -> Iterator[Enum]:
if self.cdata.basetype != self.ENUM:
return
t = ffi.cast("struct lysc_type_enum *", self.cdata)
for enum in ly_array_iter(t.enums):
yield Enum(self.context, enum)
def all_enums(self) -> Iterator[Enum]:
for b in self.get_bases():
yield from b.enums()
def bits(self) -> Iterator[Bit]:
if self.cdata.basetype != self.BITS:
return
t = ffi.cast("struct lysc_type_bits *", self.cdata)
for bit in ly_array_iter(t.bits):
yield Enum(self.context, bit)
def all_bits(self) -> Iterator[Bit]:
for b in self.get_bases():
yield from b.bits()
NUM_TYPES = frozenset((INT8, INT16, INT32, INT64, UINT8, UINT16, UINT32, UINT64))
def range(self) -> Optional[str]:
if not self.cdata_parsed:
return None
if (
self.cdata.basetype in self.NUM_TYPES or self.cdata.basetype == self.DEC64
) and self.cdata_parsed.range != ffi.NULL:
return c2str(self.cdata_parsed.range.arg.str)
return None
def all_ranges(self) -> Iterator[str]:
if self.cdata.basetype == lib.LY_TYPE_UNION:
for t in self.union_types():
yield from t.all_ranges()
else:
rng = self.range()
if rng is not None:
yield rng
def fraction_digits(self) -> Optional[int]:
if not self.cdata_parsed:
return None
if self.cdata.basetype != self.DEC64:
return None
return self.cdata_parsed.fraction_digits
def all_fraction_digits(self) -> Iterator[int]:
if self.cdata.basetype == lib.LY_TYPE_UNION:
for t in self.union_types():
yield from t.all_fraction_digits()
else:
fd = self.fraction_digits()
if fd is not None:
yield fd
STR_TYPES = frozenset((STRING, BINARY, ENUM, IDENT, BITS))
def length(self) -> Optional[str]:
if not self.cdata_parsed:
return None
if (
self.cdata.basetype in (self.STRING, self.BINARY)
) and self.cdata_parsed.length != ffi.NULL:
return c2str(self.cdata_parsed.length.arg.str)
return None
def all_lengths(self) -> Iterator[str]:
if self.cdata.basetype == lib.LY_TYPE_UNION:
for t in self.union_types():
yield from t.all_lengths()
else:
length = self.length()
if length is not None:
yield length
def patterns(self) -> Iterator[Tuple[str, bool]]:
if not self.cdata_parsed or self.cdata.basetype != self.STRING:
return
if self.cdata_parsed.patterns == ffi.NULL:
return
for p in ly_array_iter(self.cdata_parsed.patterns):
if not p:
continue
# in case of pattern restriction, the first byte has a special meaning:
# 0x06 (ACK) for regular match and 0x15 (NACK) for invert-match
invert_match = p.arg.str[0] == b"\x15"
# yield tuples like:
# ('[a-zA-Z_][a-zA-Z0-9\-_.]*', False)
# ('[xX][mM][lL].*', True)
yield c2str(p.arg.str + 1), invert_match
def all_patterns(self) -> Iterator[Tuple[str, bool]]:
if self.cdata.basetype == lib.LY_TYPE_UNION:
for t in self.union_types():
yield from t.all_patterns()
else:
yield from self.patterns()
def pattern_details(self) -> Iterator[Pattern]:
if self.cdata.basetype != self.STRING:
return
t = ffi.cast("struct lysc_type_str *", self.cdata)
if t.patterns == ffi.NULL:
return
for p in ly_array_iter(t.patterns):
if not p:
continue
yield Pattern(self.context, p)
def all_pattern_details(self) -> Iterator[Pattern]:
if self.cdata.basetype == lib.LY_TYPE_UNION:
for t in self.union_types():
yield from t.all_pattern_details()
else:
yield from self.pattern_details()
def require_instance(self) -> Optional[bool]:
if self.cdata.basetype != self.LEAFREF:
return None
t = ffi.cast("struct lysc_type_leafref *", self.cdata)
return bool(t.require_instance)
def module(self) -> Module:
if not self.cdata_parsed:
return None
return Module(self.context, self.cdata_parsed.pmod.mod)
def extensions(self) -> Iterator[ExtensionCompiled]:
for extension in ly_array_iter(self.cdata.exts):
yield ExtensionCompiled(self.context, extension)
def get_extension(
self, name: str, prefix: Optional[str] = None, arg_value: Optional[str] = None
) -> Optional[ExtensionCompiled]:
for ext in self.extensions():
if ext.name() != name:
continue
if prefix is not None and ext.module().name() != prefix:
continue
if arg_value is not None and ext.argument() != arg_value:
continue
return ext
return None
def __repr__(self):
cls = self.__class__
return "<%s.%s: %s>" % (cls.__module__, cls.__name__, str(self))
def __str__(self):
return self.name()
def parsed(self) -> Optional["PType"]:
if self.cdata_parsed is None or self.cdata_parsed == ffi.NULL:
return None
return PType(self.context, self.cdata_parsed, self.module())
# -------------------------------------------------------------------------------------
class Typedef:
__slots__ = ("context", "cdata", "__dict__")
def __init__(self, context: "libyang.Context", cdata):
self.context = context
self.cdata = cdata # C type: "struct lysp_tpdf *"
def name(self) -> str:
return c2str(self.cdata.name)
def description(self) -> Optional[str]:
return c2str(self.cdata.dsc)
def units(self) -> Optional[str]:
return c2str(self.cdata.units)
def reference(self) -> Optional[str]:
return c2str(self.cdata.ref)
def extensions(self) -> Iterator[ExtensionCompiled]:
ext = ffi.cast("struct lysc_ext_instance *", self.cdata.exts)
if ext == ffi.NULL:
return
for extension in ly_array_iter(ext):
yield ExtensionCompiled(self.context, extension)
def get_extension(
self, name: str, prefix: Optional[str] = None, arg_value: Optional[str] = None
) -> Optional[ExtensionCompiled]:
for ext in self.extensions():
if ext.name() != name:
continue
if prefix is not None and ext.module().name() != prefix:
continue
if arg_value is not None and ext.argument() != arg_value:
continue
return ext
return None
def deprecated(self) -> bool:
return bool(self.cdata.flags & lib.LYS_STATUS_DEPRC)
def obsolete(self) -> bool:
return bool(self.cdata.flags & lib.LYS_STATUS_OBSLT)
def module(self) -> Module:
return Module(self.context, self.cdata.module)
def __str__(self):
return self.name()
# -------------------------------------------------------------------------------------
class Identity:
__slots__ = ("context", "cdata")
def __init__(self, context: "libyang.Context", cdata):
self.context = context
self.cdata = cdata # C type: "struct lysc_ident *"
def name(self) -> str:
return c2str(self.cdata.name)
def description(self) -> Optional[str]:
return c2str(self.cdata.dsc)
def reference(self) -> Optional[str]:
return c2str(self.cdata.ref)
def module(self) -> Module:
return Module(self.context, self.cdata.module)
def derived(self) -> Iterator["Identity"]:
for i in ly_array_iter(self.cdata.derived):
yield Identity(self.context, i)
def extensions(self) -> Iterator[ExtensionCompiled]:
for ext in ly_array_iter(self.cdata.exts):
yield ExtensionCompiled(self.context, ext)
def get_extension(
self, name: str, prefix: Optional[str] = None, arg_value: Optional[str] = None
) -> Optional[ExtensionCompiled]:
for ext in self.extensions():
if ext.name() != name:
continue
if prefix is not None and ext.module().name() != prefix:
continue
if arg_value is not None and ext.argument() != arg_value:
continue
return ext
return None
def deprecated(self) -> bool:
return bool(self.cdata.flags & lib.LYS_STATUS_DEPRC)
def obsolete(self) -> bool:
return bool(self.cdata.flags & lib.LYS_STATUS_OBSLT)
def status(self) -> str:
if self.cdata.flags & lib.LYS_STATUS_OBSLT:
return "obsolete"
if self.cdata.flags & lib.LYS_STATUS_DEPRC:
return "deprecated"
return "current"
def __repr__(self):
cls = self.__class__
return "<%s.%s: %s>" % (cls.__module__, cls.__name__, str(self))
def __str__(self):
return self.name()
# -------------------------------------------------------------------------------------
class Feature:
__slots__ = ("context", "cdata", "__dict__")
def __init__(self, context: "libyang.Context", cdata):
self.context = context
self.cdata = cdata # C type: "struct lysp_feature *"
def name(self) -> str:
return c2str(self.cdata.name)
def description(self) -> Optional[str]:
return c2str(self.cdata.dsc)