-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathcore.py
More file actions
1563 lines (1340 loc) · 53.5 KB
/
Copy pathcore.py
File metadata and controls
1563 lines (1340 loc) · 53.5 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
# SPDX-FileCopyrightText: Copyright DB InfraGO AG
# SPDX-License-Identifier: Apache-2.0
"""Helps loading Capella models (including fragmented variants)."""
from __future__ import annotations
__all__ = [
"CorruptModelError",
"FragmentType",
"MelodyLoader",
"ModelFile",
]
import collections
import collections.abc as cabc
import contextlib
import enum
import itertools
import logging
import operator
import os
import pathlib
import re
import shutil
import sys
import tempfile
import typing as t
import urllib.parse
import warnings
from lxml import builder, etree
import capellambse._namespaces as _n
from capellambse import filehandler, helpers
from capellambse.aird._common import XP_SEMANTIC_RESOURCES
from capellambse.loader import exs
from capellambse.loader.modelinfo import ModelInfo
if sys.version_info >= (3, 13):
from warnings import deprecated
else:
from typing_extensions import deprecated
_UnspecifiedType = t.NewType("_UnspecifiedType", object)
_NOT_SPECIFIED = _UnspecifiedType(object())
E = builder.ElementMaker()
LOGGER = logging.getLogger(__name__)
PROJECT_NATURE = "org.polarsys.capella.project.nature"
VISUAL_EXTS = frozenset(
{
".aird",
".airdfragment",
}
)
SEMANTIC_EXTS = frozenset(
{
".capella",
".capellafragment",
".melodyfragment",
".melodymodeller",
}
)
VALID_EXTS = VISUAL_EXTS | SEMANTIC_EXTS | {".afm"}
IDTYPES = frozenset({"id", "uid", "xmi:id"})
IDTYPES_RESOLVED = frozenset(helpers.resolve_namespace(t) for t in IDTYPES)
IDTYPES_PER_FILETYPE: t.Final[dict[str, frozenset]] = {
".afm": frozenset(),
".aird": frozenset({"uid", helpers.resolve_namespace("xmi:id")}),
".airdfragment": frozenset({"uid", helpers.resolve_namespace("xmi:id")}),
".capella": frozenset({"id"}),
".capellafragment": frozenset({"id"}),
".melodymodeller": frozenset({"id"}),
".melodyfragment": frozenset({"id"}),
}
RE_VALID_ID = re.compile(
r"([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})"
)
CAP_VERSION = re.compile(r"Capella_Version_([\d.]+)")
METADATA_TAG = f"{{{_n.NAMESPACES['metadata']}}}Metadata"
_ROOT_NS = "org.polarsys.capella.core.data.capellamodeller"
def _derive_entrypoint(
path: str | os.PathLike | filehandler.FileHandler,
entrypoint: str | pathlib.PurePosixPath | None = None,
**kwargs: t.Any,
) -> tuple[filehandler.FileHandler, pathlib.PurePosixPath]:
if entrypoint:
if not isinstance(path, filehandler.FileHandler):
path = filehandler.get_filehandler(path, **kwargs)
entrypoint = helpers.normalize_pure_path(entrypoint)
return path, entrypoint
if not isinstance(path, filehandler.FileHandler):
path = os.fspath(path)
protocol, nested_path = filehandler.split_protocol(path)
if protocol == "file":
assert isinstance(nested_path, pathlib.Path)
if nested_path.suffix == ".aird":
entrypoint = pathlib.PurePosixPath(nested_path.name)
path = nested_path.parent
return filehandler.get_filehandler(path, **kwargs), entrypoint
if nested_path.is_file():
raise ValueError(
f"Invalid entrypoint: Not an .aird file: {nested_path}"
)
path = filehandler.get_filehandler(path, **kwargs)
aird_files = [i for i in path.iterdir() if i.name.endswith(".aird")]
if not aird_files:
raise ValueError("No .aird file found, specify entrypoint")
if len(aird_files) > 1:
raise ValueError("Multiple .aird files found, specify entrypoint")
entrypoint = pathlib.PurePosixPath(aird_files[0])
return path, entrypoint
def _find_refs(root: etree._Element) -> cabc.Iterable[str]:
return itertools.chain(
(x.split("#")[0] for x in root.xpath(".//referencedAnalysis/@href")),
root.xpath(".//semanticResources/text()"),
)
def _unquote_ref(ref: str) -> str:
ref = urllib.parse.unquote(ref)
prefix = "platform:/resource/"
if ref.startswith(prefix):
ref = ref.replace(prefix, "../")
return ref
def _round_version(v: str, prec: int) -> str:
"""Round a version number.
Parameters
----------
v
The version number.
prec
Precision to round to, i.e. the number of leading non-zero
parts. Remaining parts will be set to zero.
Returns
-------
str
The rounded version number.
"""
assert prec > 0
pos = dots = 0
while pos < len(v) and dots < prec:
dot = v.find(".", pos)
if dot < 0:
return v
pos = dot + 1
dots += 1
return v[:pos] + re.sub(r"[^.]+", "0", v[pos:])
class FragmentType(enum.Enum):
"""The type of an XML fragment."""
SEMANTIC = enum.auto()
VISUAL = enum.auto()
OTHER = enum.auto()
class MissingResourceLocationError(KeyError):
"""Raised when a model needs an additional resource location."""
class CorruptModelError(Exception):
"""Raised when the model is corrupted and cannot be processed safely.
In addition to the short description in the exception's arguments,
some validators may also produce additional information in the form
of CRITICAL log messages just before this exception is raised.
"""
class ResourceLocationManager(dict):
def __missing__(self, key: str) -> t.NoReturn:
raise MissingResourceLocationError(key)
class ModelFile:
"""Represents a single file in the model (i.e. a fragment)."""
__qtypecache: dict[etree.QName, dict[int, etree._Element]]
__xtypecache: dict[str, dict[int, etree._Element]]
__idcache: dict[str, etree._Element | None]
__hrefsources: dict[str, etree._Element]
@property
def fragment_type(self) -> FragmentType:
if self.filename.suffix in SEMANTIC_EXTS:
return FragmentType.SEMANTIC
if self.filename.suffix in VISUAL_EXTS:
return FragmentType.VISUAL
return FragmentType.OTHER
def __init__(
self,
filename: pathlib.PurePosixPath,
handler: filehandler.FileHandler,
*,
ignore_uuid_dups: bool,
) -> None:
self.filename = filename
self.filehandler = handler
self.__ignore_uuid_dups = (
ignore_uuid_dups or self.fragment_type is FragmentType.VISUAL
)
with handler.open(filename) as f:
tree = etree.parse(
f, etree.XMLParser(remove_blank_text=True, huge_tree=True)
)
self.root = tree.getroot()
self.idcache_rebuild()
def __getitem__(self, key: str) -> etree._Element:
e = self.__idcache.get(key)
if e is None:
raise KeyError(key)
return e
def enumerate_uuids(self) -> set[str]:
"""Enumerate all UUIDs used in this fragment."""
return set(self.__idcache)
def idcache_index(self, subtree: etree._Element) -> None:
"""Index the IDs of ``subtree``."""
idtypes = IDTYPES_PER_FILETYPE[self.filename.suffix]
for elm in subtree.iter():
xtype = helpers.xtype_of(elm)
if xtype is not None:
self.__xtypecache[xtype][id(elm)] = elm
qtype = helpers.qtype_of(elm)
if qtype is not None:
self.__qtypecache[qtype][id(elm)] = elm
for idtype in idtypes:
elm_id = elm.get(idtype, None)
if elm_id is None:
continue
existing = self.__idcache.get(elm_id)
if existing is not None and existing is not elm:
msg = (
f"Duplicate UUID {elm_id!r}"
f" within fragment {self.filename!s}"
)
if self.__ignore_uuid_dups:
LOGGER.warning(msg)
else:
raise CorruptModelError(msg)
self.__idcache[elm_id] = elm
href = elm.get("href")
if href is not None:
self.__hrefsources[href.split("#")[-1]] = elm
def idcache_remove(self, source: str | etree._Element) -> None:
"""Remove the ID or all IDs below the source from the ID cache."""
if isinstance(source, str):
with contextlib.suppress(KeyError):
del self.__idcache[source]
else:
for elm in source.iter():
xtype = helpers.xtype_of(elm)
if xtype:
del self.__xtypecache[xtype][id(elm)]
qtype = helpers.qtype_of(elm)
if qtype is not None:
del self.__qtypecache[qtype][id(elm)]
for idtype in IDTYPES_RESOLVED:
elm_id = elm.get(idtype, None)
if elm_id is None:
continue
with contextlib.suppress(KeyError):
del self.__idcache[elm_id]
href = elm.get("href")
if href is not None:
del self.__hrefsources[href.split("#")[-1]]
def idcache_rebuild(self) -> None:
"""Invalidate and rebuild this file's ID cache."""
LOGGER.debug("Indexing file %s...", self.filename)
self.__qtypecache = collections.defaultdict(dict)
self.__xtypecache = collections.defaultdict(dict)
self.__idcache = {}
self.__hrefsources = {}
self.idcache_index(self.root)
LOGGER.debug("Cached %d element IDs", len(self.__idcache))
def idcache_reserve(self, new_id: str) -> None:
"""Reserve the given ID for an element to be inserted later."""
self.__idcache[new_id] = None
def add_namespace(self, uri: str, alias: str) -> str:
"""Add the given namespace to the root of this fragment.
If a namespace with the same URI is already registered, no
changes will be made.
If the alias is already in use for a namespace with a different
URI, a numeric suffix will be added to it.
This method returns the actual alias in use for the namespace,
after applying the aforementioned rules.
"""
new_nsmap = dict(self.root.nsmap)
for k, v in new_nsmap.items():
if v == uri:
assert k is not None
return k
if alias in new_nsmap:
for count in range(1, sys.maxsize):
alternative = f"{alias}_{count}"
if alternative not in new_nsmap:
alias = alternative
break
new_nsmap[alias] = uri
self.__replace_nsmap(new_nsmap)
return alias
def update_namespaces(self, viewpoints: cabc.Mapping[str, str]) -> None:
"""Update the current namespace map.
Parameters
----------
viewpoints
A mapping from viewpoint names to the version activated in
the model.
If an element from a versioned Plugin is encountered, but
the Plugin's viewpoint is not activated in the model, an
error is raised and no update is performed.
"""
new_nsmap: dict[str | None, str] = {
**self.root.nsmap,
"xmi": _n.NAMESPACES["xmi"],
"xsi": _n.NAMESPACES["xsi"],
}
for elem in self.root.iter():
xtype = helpers.xtype_of(elem)
if xtype is None:
continue
ns, _, _ = xtype.partition(":")
plugin = _n.NAMESPACES_PLUGINS.get(ns)
if plugin is None:
try:
uri = elem.nsmap[ns]
except KeyError:
LOGGER.error("Undefined and unknown namespace %s", ns)
continue
else:
uri = plugin.name.rstrip("/")
if plugin.version is not None:
assert plugin.viewpoint is not None
vp_version = viewpoints.get(plugin.viewpoint)
if not vp_version:
raise CorruptModelError(
f"Viewpoint not activated: {plugin.viewpoint}"
)
vp_version = _round_version(
vp_version, plugin.version_precision
)
uri += f"/{vp_version}"
assert new_nsmap.get(ns) in (None, uri)
new_nsmap[ns] = uri
self.__replace_nsmap(new_nsmap)
def __replace_nsmap(self, new_nsmap: dict[str | None, str]) -> None:
assert new_nsmap
LOGGER.debug("New nsmap: %s", new_nsmap)
if self.root.nsmap == new_nsmap:
return
new_root = self.root.makeelement(
self.root.tag,
attrib=self.root.attrib,
nsmap=dict(sorted(new_nsmap.items())),
)
new_root.extend(self.root)
siblings = self.root.itersiblings(preceding=True) # type: ignore[unreachable] # ???
for i in reversed(list(siblings)):
new_root.addprevious(i)
siblings = self.root.itersiblings(preceding=False)
for i in list(siblings):
new_root.addnext(i)
self.root = new_root
@deprecated(
"iterall_xt() is deprecated,"
" use iterall() or iter_qtypes() + iter_qtype() instead"
)
def iterall_xt(
self, xtypes: cabc.Container[str]
) -> cabc.Iterator[etree._Element]:
"""Iterate over all elements in this tree by ``xsi:type``."""
for xtype, elms in self.__xtypecache.items():
if xtype in xtypes:
for elm in elms.values():
if not elm.get("href"):
yield elm
def iterall(self) -> cabc.Iterator[etree._Element]:
"""Iterate over all elements in this tree."""
for qt in self.iter_qtypes():
yield from self.iter_qtype(qt)
def iter_qtypes(self) -> cabc.Iterator[etree.QName]:
"""Iterate over all qualified types used in this fragment."""
for qtype, elems in self.__qtypecache.items():
if elems:
yield qtype
def iter_qtype(self, qtype: etree.QName) -> cabc.Iterator[etree._Element]:
"""Iterate over all elements of the given qualified type."""
yield from self.__qtypecache.get(qtype, {}).values()
def write_xml(
self,
file: t.BinaryIO,
encoding: str | _UnspecifiedType = _NOT_SPECIFIED,
) -> None:
"""Write this file's XML into the file specified by ``path``."""
if self.fragment_type == FragmentType.SEMANTIC:
line_length = exs.LINE_LENGTH
else:
line_length = sys.maxsize
args = {}
if encoding != _NOT_SPECIFIED:
warnings.warn(
(
"Specifying an encoding to 'ModelFile.write_xml' is deprecated,"
" please remove the 'encoding' parameter from your calls"
),
DeprecationWarning,
stacklevel=2,
)
assert isinstance(encoding, str)
if encoding != "utf-8":
args["encoding"] = encoding
exs.write(
self.root,
file,
**args,
line_length=line_length,
siblings=True,
)
def unfollow_href(self, element_id: str) -> etree._Element:
"""Unfollow a fragment link and return the placeholder element.
If the given UUID is not linked to from this file, None is
returned.
"""
return self.__hrefsources[element_id]
class MelodyLoader:
"""Facilitates extensive access to Polarsys / Capella projects."""
def __init__(
self,
path: str | os.PathLike | filehandler.FileHandler,
entrypoint: str | pathlib.PurePosixPath | None = None,
*,
resources: (
cabc.Mapping[
str,
filehandler.FileHandler | str | os.PathLike | dict[str, t.Any],
]
| None
) = None,
ignore_duplicate_uuids_and_void_all_warranties: bool = False,
**kwargs: t.Any,
) -> None:
"""Construct a MelodyLoader.
Parameters
----------
path
The ``path`` argument to the primary file handler, or the
primary file handler itself.
entrypoint
The entry point into the model, i.e. the top-level ``.aird``
file. This must be located within the primary file handler.
resources
Additional file handler instances that provide library
resources that are referenced from the model.
ignore_duplicate_uuids_and_void_all_warranties
Ignore corruption due to duplicate UUIDs (see below).
kwargs
Additional arguments to the primary file handler, if
necessary.
Raises
------
CorruptModelError
If the model is corrupt.
Currently the only kind of corruption that is detected is
duplicated UUIDs (either within a fragment or across
multiple fragments).
It is possible to ignore this error and load the model
anyways by setting the keyword-only argument
*ignore_duplicate_uuids_and_void_all_warranties* to
``True``. However, this *will* lead to strange behavior like
random exceptions when searching or filtering, or
accidentally working with the wrong object. If you try to
make changes to the model, always make sure that you have an
up to date backup ready. In order to prevent accidental
overwrites with an even corrupter model, you must therefore
also set the *i_have_a_recent_backup* keyword argument to
``True`` when calling :meth:`save`.
"""
self.__ignore_uuid_dups: bool = (
ignore_duplicate_uuids_and_void_all_warranties
)
self.__may_be_corrupt = False
handler, self.entrypoint = _derive_entrypoint(
path, entrypoint, **kwargs
)
if self.entrypoint.suffix != ".aird":
raise ValueError("Invalid entrypoint, specify the ``.aird`` file")
self.resources = ResourceLocationManager({"\0": handler})
for resname, reshdl in (resources or {}).items():
if not resname:
raise ValueError("Empty resource name")
if "/" in resname or "\0" in resname:
raise ValueError(f"Invalid resource name: {resname!r}")
if isinstance(reshdl, str | os.PathLike):
self.resources[resname] = filehandler.get_filehandler(reshdl)
elif isinstance(reshdl, cabc.Mapping):
self.resources[resname] = filehandler.get_filehandler(**reshdl)
else:
self.resources[resname] = reshdl
self.trees: dict[pathlib.PurePosixPath, ModelFile] = {}
self.__load_referenced_files(
pathlib.PurePosixPath("\0", self.entrypoint)
)
self.check_duplicate_uuids()
@property
def filehandler(self) -> filehandler.FileHandler:
r"""The file handler containing the original model.
This is a shorthand for ``self.resources["\0"]``.
"""
return self.resources["\0"]
def check_duplicate_uuids(self) -> None:
seen_ids = set[str]()
has_dups = False
for fragment, tree in self.trees.items():
tree_ids = set(tree.enumerate_uuids())
if duplicates := seen_ids & tree_ids:
LOGGER.critical(
"Duplicate UUIDs across fragments (found in %s): %r",
fragment,
duplicates,
)
self.__may_be_corrupt = True
has_dups = True
if has_dups and not self.__ignore_uuid_dups:
raise CorruptModelError(
"Model has duplicated UUIDs across fragments"
" - check the 'resources' for duplicate models"
)
def __get_metadata(
self, afm: ModelFile
) -> etree._Element:
"""Return metadata from given model.
Parameters
----------
afm
model metadata file
return
metadata element if found
Raises
------
RuntimeError
If metadata could not be found
"""
metadata = next(afm.root.iter(METADATA_TAG), None)
if metadata is None:
raise RuntimeError("Cannot find <Metadata> in primary .afm file")
LOGGER.debug("Found <Metadata> with ID %s", metadata.get("id"))
return metadata
def _link_library(
self, lib: pathlib.PurePosixPath
) -> None:
"""Link library into the project tree, updates .aird, .capella, .afm to correcrly reflect library in target model.
Parameters
----------
lib
path to a library .aird file
Description
-----------
When you need to refere to external library (or reuse one in a project)
```
p = "..." #path to library
model._loader._link_library(p)
lib = model.project.extensions[0].reference.library #no longer crashes, all fragments are in place
```
"""
handler = self.resources[str(lib)]
_h , filename = _derive_entrypoint(handler)
frag = ModelFile(
filename, handler, ignore_uuid_dups=self.__ignore_uuid_dups
)
p = lib.joinpath(filename)
self.trees[p] = frag
for ref in _find_refs(frag.root):
ref_name = helpers.normalize_pure_path(
_unquote_ref(ref), base=p.parent
)
self.__load_referenced_files(ref_name)
if ref_name.suffix == ".afm":
meta_lib = self.__get_metadata(self.trees[ref_name])
meta_self = self.__find_metadata()
if not next(filter(lambda el: re.search(str(ref_name), el.attrib["href"]), meta_self.iterchildren("additionalResources")), None):
ael = meta_self.makeelement("additionalMetadata", href=f"../{ref_name}#{meta_lib.attrib['id']}")
meta_self.append(ael)
elif ref_name.suffix == ".capella":
aird_self = self.trees[pathlib.PurePosixPath(f"\x00/{self.entrypoint}")]
last = next(filter(lambda el: re.search(str(ref_name), el.text), XP_SEMANTIC_RESOURCES(aird_self.root)), None)
if not last:
for r in XP_SEMANTIC_RESOURCES(aird_self.root):
last = r
if last is not None:
sr = last.makeelement("semanticResources")
sr.text = f"platform:/resource/{ref_name}"
last.addnext(sr)
def __load_referenced_files(
self, resource_path: pathlib.PurePosixPath
) -> None:
if resource_path in self.trees:
return
if resource_path.suffix not in VALID_EXTS:
LOGGER.warning(
(
"Ignoring file of unknown type,"
" loaded model may be incomplete: %s"
),
resource_path.name,
)
self.__may_be_corrupt = True
return
handler = self.resources[resource_path.parts[0]]
filename = pathlib.PurePosixPath(*resource_path.parts[1:])
frag = ModelFile(
filename, handler, ignore_uuid_dups=self.__ignore_uuid_dups
)
self.trees[resource_path] = frag
for ref in _find_refs(frag.root):
ref_name = helpers.normalize_pure_path(
_unquote_ref(ref), base=resource_path.parent
)
self.__load_referenced_files(ref_name)
def save(self, **kw: t.Any) -> None:
"""Save all model files.
Parameters
----------
kw
Additional keyword arguments accepted by the file handler in
use. Please see the respective documentation for more info.
See Also
--------
capellambse.filehandler.local.LocalFileHandler.write_transaction :
Accepted ``**kw`` when using local directories
capellambse.filehandler.git.GitFileHandler.write_transaction :
Accepted ``**kw`` when using ``git://`` and similar URLs
Notes
-----
With a :attr:`filehandler` that contacts a remote location (such
as the :class:`capellambse.filehandler.git.GitFileHandler` with
non-local repositories), saving might fail if the local state
has gone out of sync with the remote state. To avoid this,
always leave the ``update_cache`` parameter at its default value
of ``True`` if you intend to save changes.
"""
self.check_duplicate_uuids()
overwrite_corrupt = kw.pop("i_have_a_recent_backup", False)
if self.__may_be_corrupt and not overwrite_corrupt:
raise CorruptModelError(
"Refusing to save a corrupt model without having a backup"
" (hint: pass i_have_a_recent_backup=True)"
)
self.update_namespaces()
LOGGER.debug("Saving model %r", self.get_model_info().title)
with self.filehandler.write_transaction(**kw) as unsupported_kws:
if unsupported_kws:
LOGGER.warning(
"Ignoring unsupported transaction parameters: %s",
", ".join(repr(k) for k in unsupported_kws),
)
for fname, tree in self.trees.items():
resname = fname.parts[0]
fname = pathlib.PurePosixPath(*fname.parts[1:])
if resname != "\0":
continue
LOGGER.debug("Saving tree %r to file %s", tree, fname)
with self.resources[resname].open(fname, "wb") as f:
tree.write_xml(f)
def update_namespaces(self) -> None:
"""Update the namespace definitions on each fragment root.
This method is automatically called while saving to ensure that
all namespaces necessary for the current model elements are
registered on the fragment roots.
"""
vp = dict(self.referenced_viewpoints())
for fname, fragment in self.trees.items():
if fragment.fragment_type != FragmentType.SEMANTIC:
continue
LOGGER.debug("Updating namespaces on fragment %s", fname)
fragment.update_namespaces(vp)
def idcache_index(self, subtree: etree._Element) -> None:
"""Index the IDs of ``subtree``.
This method must be called after adding ``subtree`` to the XML
tree.
Parameters
----------
subtree
The new element that was just inserted.
"""
try:
_, tree = self._find_fragment(subtree)
except ValueError:
raise ValueError(
"Call idcache_index() after adding the subtree"
) from None
tree.idcache_index(subtree)
def idcache_remove(self, subtree: etree._Element) -> None:
"""Remove the ``subtree`` from the ID cache.
This method must be called before actually removing ``subtree``
from the XML tree.
Parameters
----------
subtree
The element that is about to be removed.
"""
try:
_, tree = self._find_fragment(subtree)
except ValueError:
raise ValueError(
"Call idcache_remove() before removing the subtree"
) from None
tree.idcache_remove(subtree)
def idcache_rebuild(self) -> None:
"""Rebuild the ID caches of all loaded :class:`ModelFile` instances."""
for tree in self.trees.values():
tree.idcache_rebuild()
def generate_uuid(
self, parent: etree._Element, *, want: str | None = None
) -> str:
"""Generate a unique UUID for a new child of ``parent``.
The generated ID is guaranteed to be unique across all currently
loaded fragments.
Parameters
----------
parent
The parent element below which the new UUID will be used.
want
Try this UUID first, and use it if it satisfies all other
constraints. If it does not satisfy all constraints (e.g. it
would be non-unique), a random UUID will be generated as
normal.
Returns
-------
str
The new UUID.
"""
_, tree = self._find_fragment(parent)
if want:
try:
self[want]
except KeyError:
tree.idcache_reserve(want)
return want
else:
raise ValueError(f"UUID {want!r} is already in use")
while True:
new_id = helpers.generate_id()
try:
self[new_id]
except KeyError:
tree.idcache_reserve(new_id)
return new_id
raise AssertionError()
@contextlib.contextmanager
def new_uuid(
self, parent: etree._Element, *, want: str | None = None
) -> cabc.Generator[str, None, None]:
"""Context Manager around :meth:`generate_uuid()`.
This context manager yields a newly generated model-wide unique
UUID that can be inserted into a new element during the ``with``
block. It tries to keep the ID cache consistent in some harder
to manage edge cases, like exceptions being thrown. Additionally
it checks that the generated UUID was actually used in the tree;
not using it before the ``with`` block ends is an error and
provokes an Exception.
.. note:: You still need to call :meth:`idcache_index()` on the
newly inserted element!
Example usage::
>>> with ldr.new_uuid(parent_elm) as obj_id:
... child_elm = parent_elm.makeelement("ownedObjects")
... child_elm.set("id", obj_id)
... parent_elm.append(child_elm)
... ldr.idcache_index(child_elm)
If you intend to reserve a UUID that should be inserted later,
use :meth:`generate_uuid()` directly.
Parameters
----------
parent
The parent element below which the new UUID will be used.
want
Request this UUID. The request may or may not be fulfilled;
always use the actual UUID returned by the context manager.
"""
_, tree = self._find_fragment(parent)
new_uuid = self.generate_uuid(parent, want=want)
def cleanup_after_failure() -> None:
tree.idcache_remove(new_uuid)
for child in parent:
for id_attr in IDTYPES_RESOLVED:
if child.get(id_attr) == new_uuid:
parent.remove(child)
try:
yield new_uuid
except BaseException:
cleanup_after_failure()
raise
if self[new_uuid] is None:
cleanup_after_failure()
raise RuntimeError("New UUID was requested but never used")
def xpath(
self,
query: str | etree.XPath,
*,
namespaces: dict[str, str] | None = None,
roots: etree._Element | cabc.Iterable[etree._Element] | None = None,
) -> list[etree._Element]:
"""Run an XPath query on all fragments.
Note that, unlike the ``iter_*`` methods, placeholder elements
are not followed into their respective fragment.
Parameters
----------
query
The XPath query
namespaces
Namespaces used in the query. Defaults to all known
namespaces.
roots
A list of XML elements to use as roots for the query.
Defaults to all tree roots.
Returns
-------
list[lxml.etree._Element]
A list of all matching elements.
"""
return list(
map(
operator.itemgetter(1),
self.xpath2(query, namespaces=namespaces, roots=roots),
)
)
def xpath2(
self,
query: str | etree.XPath,
*,
namespaces: dict[str, str] | None = None,
roots: etree._Element | cabc.Iterable[etree._Element] | None = None,
) -> list[tuple[pathlib.PurePosixPath, etree._Element]]:
"""Run an XPath query and return the fragments and elements.
Note that, unlike the ``iter_*`` methods, placeholder elements
are not followed into their respective fragment.
The tuples have the fragment where the match was found as first
element, and the LXML element as second one.
Parameters
----------
query
The XPath query
namespaces
Namespaces used in the query. Defaults to all known
namespaces.
roots
A list of XML elements to use as roots for the query.
Defaults to all tree roots.
Returns
-------
list[tuple[pathlib.PurePosixPath, lxml.etree._Element]]
A list of 2-tuples, containing:
1. The fragment name where the match was found.
2. The matching element.
"""
if namespaces is None:
namespaces = _n.NAMESPACES
def follow_href(
tree: pathlib.PurePosixPath, match: etree._Element
) -> tuple[pathlib.PurePosixPath, etree._Element]:
if href := match.get("href"):
match = self.follow_link(match, href)
return (self.find_fragment(match), match)
return (tree, match)
if not isinstance(query, etree.XPath):
query = etree.XPath(query, namespaces=namespaces)
if roots is None:
roottrees = [(k, t.root) for k, t in self.trees.items()]
elif isinstance(roots, etree._Element):
roottrees = [(self._find_fragment(roots)[0], roots)]