capella-model-explorer 0.2.2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- capella_model_explorer/__init__.py +11 -0
- capella_model_explorer/backend/__init__.py +11 -0
- capella_model_explorer/backend/__main__.py +37 -0
- capella_model_explorer/backend/explorer.py +372 -0
- capella_model_explorer/backend/model_diff.py +478 -0
- capella_model_explorer/backend/templates.py +200 -0
- capella_model_explorer-0.2.2.dist-info/METADATA +221 -0
- capella_model_explorer-0.2.2.dist-info/RECORD +10 -0
- capella_model_explorer-0.2.2.dist-info/WHEEL +5 -0
- capella_model_explorer-0.2.2.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# Copyright DB InfraGO AG and contributors
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""The capella_model_explorer package."""
|
|
4
|
+
|
|
5
|
+
from importlib import metadata
|
|
6
|
+
|
|
7
|
+
try:
|
|
8
|
+
__version__ = metadata.version("capella_model_explorer")
|
|
9
|
+
except metadata.PackageNotFoundError: # pragma: no cover
|
|
10
|
+
__version__ = "0.0.0+unknown"
|
|
11
|
+
del metadata
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# Copyright DB InfraGO AG and contributors
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""The capella_model_explorer package."""
|
|
4
|
+
|
|
5
|
+
from importlib import metadata
|
|
6
|
+
|
|
7
|
+
try:
|
|
8
|
+
__version__ = metadata.version("capella_model_explorer")
|
|
9
|
+
except metadata.PackageNotFoundError: # pragma: no cover
|
|
10
|
+
__version__ = "0.0.0+unknown"
|
|
11
|
+
del metadata
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
# Copyright DB InfraGO AG and contributors
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
|
|
4
|
+
import os
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
import capellambse
|
|
8
|
+
import click
|
|
9
|
+
import uvicorn
|
|
10
|
+
|
|
11
|
+
from . import explorer
|
|
12
|
+
|
|
13
|
+
HOST = os.getenv("CAPELLA_MODEL_EXPLORER_HOST_IP", "0.0.0.0")
|
|
14
|
+
PORT = os.getenv("CAPELLA_MODEL_EXPLORER_PORT", "8000")
|
|
15
|
+
|
|
16
|
+
PATH_TO_TEMPLATES = Path("./templates")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@click.command()
|
|
20
|
+
@click.argument("model", type=capellambse.ModelCLI())
|
|
21
|
+
@click.argument(
|
|
22
|
+
"templates",
|
|
23
|
+
type=click.Path(path_type=Path, exists=True),
|
|
24
|
+
required=False,
|
|
25
|
+
default=PATH_TO_TEMPLATES,
|
|
26
|
+
)
|
|
27
|
+
def run(model: capellambse.MelodyModel, templates: Path):
|
|
28
|
+
backend = explorer.CapellaModelExplorerBackend(
|
|
29
|
+
Path(templates),
|
|
30
|
+
model,
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
uvicorn.run(backend.app, host=HOST, port=int(PORT))
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
if __name__ == "__main__":
|
|
37
|
+
run()
|
|
@@ -0,0 +1,372 @@
|
|
|
1
|
+
# Copyright DB InfraGO AG and contributors
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
|
|
4
|
+
import dataclasses
|
|
5
|
+
import logging
|
|
6
|
+
import os
|
|
7
|
+
import pathlib
|
|
8
|
+
import time
|
|
9
|
+
import traceback
|
|
10
|
+
import typing as t
|
|
11
|
+
import urllib.parse as urlparse
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
import capellambse
|
|
15
|
+
import capellambse.model as m
|
|
16
|
+
import fastapi
|
|
17
|
+
import markupsafe
|
|
18
|
+
import prometheus_client
|
|
19
|
+
import yaml
|
|
20
|
+
from fastapi import APIRouter, FastAPI, HTTPException, Request
|
|
21
|
+
from fastapi.middleware.cors import CORSMiddleware
|
|
22
|
+
from fastapi.responses import HTMLResponse
|
|
23
|
+
from fastapi.staticfiles import StaticFiles
|
|
24
|
+
from fastapi.templating import Jinja2Templates
|
|
25
|
+
from jinja2 import (
|
|
26
|
+
Environment,
|
|
27
|
+
FileSystemLoader,
|
|
28
|
+
TemplateSyntaxError,
|
|
29
|
+
is_undefined,
|
|
30
|
+
)
|
|
31
|
+
from pydantic import BaseModel
|
|
32
|
+
|
|
33
|
+
from capella_model_explorer.backend import model_diff
|
|
34
|
+
from capella_model_explorer.backend import templates as tl
|
|
35
|
+
|
|
36
|
+
from . import __version__
|
|
37
|
+
|
|
38
|
+
esc = markupsafe.escape
|
|
39
|
+
|
|
40
|
+
PATH_TO_FRONTEND = Path("./frontend/dist")
|
|
41
|
+
ROUTE_PREFIX = os.getenv("ROUTE_PREFIX", "")
|
|
42
|
+
LOGGER = logging.getLogger(__name__)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class CommitRange(BaseModel):
|
|
46
|
+
head: str
|
|
47
|
+
prev: str
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class ObjectDiffID(BaseModel):
|
|
51
|
+
uuid: str
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@dataclasses.dataclass
|
|
55
|
+
class CapellaModelExplorerBackend:
|
|
56
|
+
app: FastAPI = dataclasses.field(init=False)
|
|
57
|
+
env: Environment = dataclasses.field(init=False)
|
|
58
|
+
templates: dict[str, t.Any] = dataclasses.field(
|
|
59
|
+
init=False, default_factory=dict
|
|
60
|
+
)
|
|
61
|
+
templates_loader: tl.TemplateLoader = dataclasses.field(init=False)
|
|
62
|
+
|
|
63
|
+
templates_path: Path
|
|
64
|
+
model: capellambse.MelodyModel
|
|
65
|
+
|
|
66
|
+
templates_index: tl.TemplateCategories | None = dataclasses.field(
|
|
67
|
+
init=False
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
def __post_init__(self):
|
|
71
|
+
self.app = FastAPI(version=__version__)
|
|
72
|
+
self.router = APIRouter(prefix=ROUTE_PREFIX)
|
|
73
|
+
self.app.add_middleware(
|
|
74
|
+
CORSMiddleware,
|
|
75
|
+
allow_origins=["*"],
|
|
76
|
+
allow_credentials=True,
|
|
77
|
+
allow_methods=["*"],
|
|
78
|
+
allow_headers=["*"],
|
|
79
|
+
)
|
|
80
|
+
self.templates_loader = tl.TemplateLoader(self.model)
|
|
81
|
+
self.env = Environment(loader=FileSystemLoader(self.templates_path))
|
|
82
|
+
self.env.finalize = self.__finalize
|
|
83
|
+
self.env.filters["make_href"] = self.__make_href_filter
|
|
84
|
+
self.app.state.templates = Jinja2Templates(directory=PATH_TO_FRONTEND)
|
|
85
|
+
self.configure_routes()
|
|
86
|
+
self.app.include_router(self.router)
|
|
87
|
+
self.idle_time_gauge = prometheus_client.Gauge(
|
|
88
|
+
"idletime_minutes",
|
|
89
|
+
"Time in minutes since the last user interaction",
|
|
90
|
+
)
|
|
91
|
+
self.last_interaction = time.time()
|
|
92
|
+
self.templates_index = self.templates_loader.index_path(
|
|
93
|
+
self.templates_path
|
|
94
|
+
)
|
|
95
|
+
self.diff = {}
|
|
96
|
+
self.object_diff = {}
|
|
97
|
+
|
|
98
|
+
@self.app.middleware("http")
|
|
99
|
+
async def update_last_interaction_time(request: Request, call_next):
|
|
100
|
+
if request.url.path not in ("/metrics", "/favicon.ico"):
|
|
101
|
+
self.last_interaction = time.time()
|
|
102
|
+
return await call_next(request)
|
|
103
|
+
|
|
104
|
+
def __finalize(self, markup: t.Any) -> object:
|
|
105
|
+
markup = markupsafe.escape(markup)
|
|
106
|
+
return capellambse.helpers.replace_hlinks(
|
|
107
|
+
markup, self.model, self.__make_href
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
def __make_href_filter(self, obj: object) -> str | None:
|
|
111
|
+
if is_undefined(obj) or obj is None:
|
|
112
|
+
return "#"
|
|
113
|
+
|
|
114
|
+
if isinstance(obj, m.ElementList):
|
|
115
|
+
raise TypeError("Cannot make an href to a list of elements")
|
|
116
|
+
if not isinstance(obj, m.ModelElement | m.AbstractDiagram):
|
|
117
|
+
raise TypeError(f"Expected a model object, got {obj!r}")
|
|
118
|
+
|
|
119
|
+
try:
|
|
120
|
+
self.model.by_uuid(obj.uuid)
|
|
121
|
+
except KeyError:
|
|
122
|
+
return "#"
|
|
123
|
+
|
|
124
|
+
return self.__make_href(obj)
|
|
125
|
+
|
|
126
|
+
def __make_href(
|
|
127
|
+
self, obj: m.ModelElement | m.AbstractDiagram
|
|
128
|
+
) -> str | None:
|
|
129
|
+
if self.templates_index is None:
|
|
130
|
+
return None
|
|
131
|
+
|
|
132
|
+
for idx, template in self.templates_index.flat.items():
|
|
133
|
+
if "type" in dir(template.scope):
|
|
134
|
+
clsname = template.scope.type
|
|
135
|
+
if obj.xtype.rsplit(":", 1)[-1] == clsname:
|
|
136
|
+
return f"{ROUTE_PREFIX}/{idx}/{obj.uuid}"
|
|
137
|
+
return f"{ROUTE_PREFIX}/__generic__/{obj.uuid}"
|
|
138
|
+
|
|
139
|
+
def render_instance_page(self, template_text, base, object=None):
|
|
140
|
+
try:
|
|
141
|
+
# render the template with the object
|
|
142
|
+
template = self.env.from_string(template_text)
|
|
143
|
+
rendered = template.render(
|
|
144
|
+
object=object,
|
|
145
|
+
model=self.model,
|
|
146
|
+
diff_data=self.diff,
|
|
147
|
+
object_diff=self.object_diff,
|
|
148
|
+
)
|
|
149
|
+
return HTMLResponse(content=rendered, status_code=200)
|
|
150
|
+
except TemplateSyntaxError as e:
|
|
151
|
+
error_message = markupsafe.Markup(
|
|
152
|
+
"<p style='color:red'>Template syntax error: {}, line {}</p>"
|
|
153
|
+
).format(e.message, e.lineno)
|
|
154
|
+
base.error = error_message
|
|
155
|
+
print(base)
|
|
156
|
+
return HTMLResponse(content=error_message)
|
|
157
|
+
except Exception as e:
|
|
158
|
+
LOGGER.exception("Error rendering template")
|
|
159
|
+
trace = markupsafe.escape(traceback.format_exc())
|
|
160
|
+
error_message = markupsafe.Markup(
|
|
161
|
+
'<p style="color:red">'
|
|
162
|
+
f"Unexpected error: {type(e).__name__}: {e}"
|
|
163
|
+
'</p><pre style="font-size:80%;overflow:scroll">'
|
|
164
|
+
f"object={object!r}\nmodel={self.model!r}"
|
|
165
|
+
f"\n\n{trace}"
|
|
166
|
+
"</pre>"
|
|
167
|
+
)
|
|
168
|
+
return HTMLResponse(content=error_message)
|
|
169
|
+
|
|
170
|
+
def configure_routes(self): # noqa: C901
|
|
171
|
+
self.app.mount(
|
|
172
|
+
f"{ROUTE_PREFIX}/assets",
|
|
173
|
+
StaticFiles(
|
|
174
|
+
directory=PATH_TO_FRONTEND.joinpath("assets"), html=True
|
|
175
|
+
),
|
|
176
|
+
)
|
|
177
|
+
self.app.mount(
|
|
178
|
+
f"{ROUTE_PREFIX}/static",
|
|
179
|
+
StaticFiles(
|
|
180
|
+
directory=PATH_TO_FRONTEND.joinpath("static"), html=True
|
|
181
|
+
),
|
|
182
|
+
)
|
|
183
|
+
|
|
184
|
+
@self.router.get("/api/views")
|
|
185
|
+
def read_templates():
|
|
186
|
+
self.templates_index = self.templates_loader.index_path(
|
|
187
|
+
self.templates_path
|
|
188
|
+
)
|
|
189
|
+
return self.templates_index.as_dict
|
|
190
|
+
|
|
191
|
+
@self.router.get("/api/objects/{uuid}")
|
|
192
|
+
def read_object(uuid: str):
|
|
193
|
+
obj = self.model.by_uuid(uuid)
|
|
194
|
+
details = tl.simple_object(obj)
|
|
195
|
+
return {
|
|
196
|
+
"idx": details["idx"],
|
|
197
|
+
"name": details["name"],
|
|
198
|
+
"type": obj.xtype,
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
@self.router.get("/api/views/{template_name}")
|
|
202
|
+
def read_template(template_name: str):
|
|
203
|
+
template_name = urlparse.unquote(template_name)
|
|
204
|
+
if (
|
|
205
|
+
self.templates_index is None
|
|
206
|
+
or template_name not in self.templates_index.flat
|
|
207
|
+
):
|
|
208
|
+
return {
|
|
209
|
+
"error": (
|
|
210
|
+
f"Template {template_name} not found"
|
|
211
|
+
" or templates index not initialized"
|
|
212
|
+
)
|
|
213
|
+
}
|
|
214
|
+
base = self.templates_index.flat[template_name]
|
|
215
|
+
base.compute_instance_list(self.model)
|
|
216
|
+
return base
|
|
217
|
+
|
|
218
|
+
@self.router.get("/api/views/{template_name}/{object_id}")
|
|
219
|
+
def render_template(template_name: str, object_id: str):
|
|
220
|
+
content = None
|
|
221
|
+
object = None
|
|
222
|
+
try:
|
|
223
|
+
template_name = urlparse.unquote(template_name)
|
|
224
|
+
if (
|
|
225
|
+
self.templates_index is None
|
|
226
|
+
or template_name not in self.templates_index.flat
|
|
227
|
+
):
|
|
228
|
+
return {"error": f"Template {template_name} not found"}
|
|
229
|
+
base = self.templates_index.flat[template_name]
|
|
230
|
+
template_filename = base.template
|
|
231
|
+
# load the template file from the templates folder
|
|
232
|
+
content = (self.templates_path / template_filename).read_text(
|
|
233
|
+
encoding="utf8"
|
|
234
|
+
)
|
|
235
|
+
except Exception as e:
|
|
236
|
+
error_message = markupsafe.Markup(
|
|
237
|
+
"<p style='color:red'>Template not found: {}</p>"
|
|
238
|
+
).format(str(e))
|
|
239
|
+
return HTMLResponse(content=error_message)
|
|
240
|
+
if object_id == "render":
|
|
241
|
+
object = None
|
|
242
|
+
else:
|
|
243
|
+
try:
|
|
244
|
+
object = self.model.by_uuid(object_id)
|
|
245
|
+
except Exception as e:
|
|
246
|
+
error_message = markupsafe.Markup(
|
|
247
|
+
"<p style='color:red'>"
|
|
248
|
+
"Requested object not found: {}</p>"
|
|
249
|
+
).format(str(e))
|
|
250
|
+
return HTMLResponse(content=error_message)
|
|
251
|
+
return self.render_instance_page(content, base, object)
|
|
252
|
+
|
|
253
|
+
@self.router.get("/api/model-info")
|
|
254
|
+
def model_info():
|
|
255
|
+
info = self.model.info
|
|
256
|
+
resinfo = info.resources["\x00"]
|
|
257
|
+
return {
|
|
258
|
+
"title": info.title,
|
|
259
|
+
"revision": resinfo.revision,
|
|
260
|
+
"hash": resinfo.rev_hash,
|
|
261
|
+
"capella_version": info.capella_version,
|
|
262
|
+
"branch": resinfo.branch,
|
|
263
|
+
"badge": self.model.description_badge,
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
@self.app.get("/metrics")
|
|
267
|
+
def metrics():
|
|
268
|
+
idle_time_minutes = (time.time() - self.last_interaction) / 60
|
|
269
|
+
self.idle_time_gauge.set(idle_time_minutes)
|
|
270
|
+
return fastapi.Response(
|
|
271
|
+
content=prometheus_client.generate_latest(),
|
|
272
|
+
media_type="text/plain",
|
|
273
|
+
)
|
|
274
|
+
|
|
275
|
+
@self.router.get("/api/metadata")
|
|
276
|
+
async def version():
|
|
277
|
+
return {"version": self.app.version}
|
|
278
|
+
|
|
279
|
+
@self.router.post("/api/compare")
|
|
280
|
+
async def post_compare(commit_range: CommitRange):
|
|
281
|
+
try:
|
|
282
|
+
self.diff = model_diff.get_diff_data(
|
|
283
|
+
self.model, commit_range.head, commit_range.prev
|
|
284
|
+
)
|
|
285
|
+
self.diff["lookup"] = create_diff_lookup(self.diff["objects"])
|
|
286
|
+
if self.diff["lookup"]:
|
|
287
|
+
return {"success": True}
|
|
288
|
+
return {"success": False, "error": "No model changes to show"}
|
|
289
|
+
except Exception as e:
|
|
290
|
+
LOGGER.exception("Failed to compare versions")
|
|
291
|
+
return {"success": False, "error": str(e)}
|
|
292
|
+
|
|
293
|
+
@self.router.post("/api/object-diff")
|
|
294
|
+
async def post_object_diff(object_id: ObjectDiffID):
|
|
295
|
+
if object_id.uuid not in self.diff["lookup"]:
|
|
296
|
+
raise HTTPException(status_code=404, detail="Object not found")
|
|
297
|
+
|
|
298
|
+
self.object_diff = self.diff["lookup"][object_id.uuid]
|
|
299
|
+
return {"success": True}
|
|
300
|
+
|
|
301
|
+
@self.router.get("/api/commits")
|
|
302
|
+
async def get_commits():
|
|
303
|
+
try:
|
|
304
|
+
return model_diff.populate_commits(self.model)
|
|
305
|
+
except Exception as e:
|
|
306
|
+
return {"error": str(e)}
|
|
307
|
+
|
|
308
|
+
@self.router.get("/api/diff")
|
|
309
|
+
async def get_diff():
|
|
310
|
+
if self.diff:
|
|
311
|
+
return self.diff
|
|
312
|
+
return {
|
|
313
|
+
"error": "No data available. Please compare two commits first."
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
@self.router.get("/{rest_of_path:path}")
|
|
317
|
+
async def catch_all(request: Request, rest_of_path: str):
|
|
318
|
+
del rest_of_path
|
|
319
|
+
return self.app.state.templates.TemplateResponse(
|
|
320
|
+
"index.html", {"request": request}
|
|
321
|
+
)
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
def index_template(template, templates, templates_grouped, filename=None):
|
|
325
|
+
idx = filename if filename else template["idx"]
|
|
326
|
+
record = {"idx": idx, **template}
|
|
327
|
+
if "category" in template:
|
|
328
|
+
category = template["category"]
|
|
329
|
+
if category not in templates_grouped:
|
|
330
|
+
templates_grouped[category] = []
|
|
331
|
+
templates_grouped[category].append(record)
|
|
332
|
+
else:
|
|
333
|
+
templates_grouped["other"].append(record)
|
|
334
|
+
templates[idx] = template
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def index_templates(
|
|
338
|
+
path: pathlib.Path,
|
|
339
|
+
) -> tuple[dict[str, t.Any], dict[str, t.Any]]:
|
|
340
|
+
templates_grouped: dict[str, t.Any] = {"other": []}
|
|
341
|
+
templates: dict[str, t.Any] = {}
|
|
342
|
+
for template_file in path.glob("**/*.yaml"):
|
|
343
|
+
template = yaml.safe_load(template_file.read_text(encoding="utf8"))
|
|
344
|
+
if "templates" in template:
|
|
345
|
+
for template_def in template["templates"]:
|
|
346
|
+
index_template(template_def, templates, templates_grouped)
|
|
347
|
+
else:
|
|
348
|
+
idx = urlparse.quote(template_file.name.replace(".yaml", ""))
|
|
349
|
+
index_template(
|
|
350
|
+
template, templates, templates_grouped, filename=idx
|
|
351
|
+
)
|
|
352
|
+
return templates_grouped, templates
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
def create_diff_lookup(data, lookup=None):
|
|
356
|
+
if lookup is None:
|
|
357
|
+
lookup = {}
|
|
358
|
+
try:
|
|
359
|
+
if isinstance(data, dict):
|
|
360
|
+
for _, obj in data.items():
|
|
361
|
+
if "uuid" in obj:
|
|
362
|
+
lookup[obj["uuid"]] = {
|
|
363
|
+
"uuid": obj["uuid"],
|
|
364
|
+
"display_name": obj["display_name"],
|
|
365
|
+
"change": obj["change"],
|
|
366
|
+
"attributes": obj["attributes"],
|
|
367
|
+
}
|
|
368
|
+
if children := obj.get("children"):
|
|
369
|
+
create_diff_lookup(children, lookup)
|
|
370
|
+
except Exception:
|
|
371
|
+
LOGGER.exception("Cannot create diff lookup")
|
|
372
|
+
return lookup
|
|
@@ -0,0 +1,478 @@
|
|
|
1
|
+
# Copyright DB InfraGO AG and contributors
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
|
|
4
|
+
import datetime
|
|
5
|
+
import enum
|
|
6
|
+
import logging
|
|
7
|
+
import pathlib
|
|
8
|
+
import subprocess
|
|
9
|
+
import typing as t
|
|
10
|
+
|
|
11
|
+
import capellambse
|
|
12
|
+
import capellambse.model as m
|
|
13
|
+
import diff_match_patch
|
|
14
|
+
import typing_extensions as te
|
|
15
|
+
from capellambse.filehandler import git, local
|
|
16
|
+
|
|
17
|
+
logger = logging.getLogger(__name__)
|
|
18
|
+
NUM_COMMITS = "20"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class RevisionInfo(te.TypedDict, total=False):
|
|
22
|
+
hash: te.Required[str]
|
|
23
|
+
"""The revision hash."""
|
|
24
|
+
revision: str
|
|
25
|
+
"""The original revision passed to the diff tool."""
|
|
26
|
+
author: str
|
|
27
|
+
"""The author of the revision, in "Name <email@domain>" format."""
|
|
28
|
+
date: datetime.datetime
|
|
29
|
+
"""The time and date of the revision."""
|
|
30
|
+
description: str
|
|
31
|
+
"""The description of the revision, i.e. the commit message."""
|
|
32
|
+
subject: str
|
|
33
|
+
"""The subject of the commit."""
|
|
34
|
+
tag: str | None
|
|
35
|
+
"""The tag of the commit."""
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class Metadata(te.TypedDict):
|
|
39
|
+
model: dict[str, t.Any]
|
|
40
|
+
"""The 'modelinfo' used to load the models, sans the revision key."""
|
|
41
|
+
new_revision: RevisionInfo
|
|
42
|
+
old_revision: RevisionInfo
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class BaseObject(te.TypedDict):
|
|
46
|
+
uuid: str
|
|
47
|
+
display_name: str
|
|
48
|
+
"""Name for displaying in the frontend.
|
|
49
|
+
|
|
50
|
+
This is usually the ``name`` attribute of the "current" version of
|
|
51
|
+
the object.
|
|
52
|
+
"""
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class FullObject(BaseObject, te.TypedDict):
|
|
56
|
+
attributes: dict[str, t.Any]
|
|
57
|
+
"""All attributes that the object has (or had)."""
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class ChangedAttribute(te.TypedDict):
|
|
61
|
+
previous: t.Any
|
|
62
|
+
"""The old value of the attribute."""
|
|
63
|
+
current: t.Any
|
|
64
|
+
"""The new value of the attribute."""
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class ChangedObject(BaseObject, te.TypedDict):
|
|
68
|
+
attributes: dict[str, ChangedAttribute]
|
|
69
|
+
"""The attributes that were changed."""
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class ObjectChange(te.TypedDict, total=False):
|
|
73
|
+
created: list[FullObject]
|
|
74
|
+
"""Contains objects that were created."""
|
|
75
|
+
deleted: list[FullObject]
|
|
76
|
+
"""Contains objects that were deleted."""
|
|
77
|
+
modified: list[ChangedObject]
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
ObjectLayer: te.TypeAlias = "dict[str, ObjectChange]"
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class ObjectChanges(te.TypedDict, total=False):
|
|
84
|
+
oa: ObjectLayer
|
|
85
|
+
"""Changes to objects from the OperationalAnalysis layer."""
|
|
86
|
+
sa: ObjectLayer
|
|
87
|
+
"""Changes to objects from the SystemAnalysis layer."""
|
|
88
|
+
la: ObjectLayer
|
|
89
|
+
"""Changes to objects from the LogicalAnalysis layer."""
|
|
90
|
+
pa: ObjectLayer
|
|
91
|
+
"""Changes to objects from the PhysicalAnalysis layer."""
|
|
92
|
+
epbs: ObjectLayer
|
|
93
|
+
"""Changes to objects from the EPBS layer."""
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
class ChangeSummaryDocument(te.TypedDict):
|
|
97
|
+
metadata: Metadata
|
|
98
|
+
objects: ObjectChanges
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def init_model(model: capellambse.MelodyModel) -> str | None:
|
|
102
|
+
"""Initialize the model and return the path if it's a git repository."""
|
|
103
|
+
file_handler = model.resources["\x00"]
|
|
104
|
+
path = file_handler.path
|
|
105
|
+
|
|
106
|
+
if isinstance(file_handler, git.GitFileHandler):
|
|
107
|
+
path = file_handler.cache_dir
|
|
108
|
+
elif (
|
|
109
|
+
isinstance(file_handler, local.LocalFileHandler)
|
|
110
|
+
and file_handler.rootdir.joinpath(".git").is_dir()
|
|
111
|
+
):
|
|
112
|
+
pass
|
|
113
|
+
else:
|
|
114
|
+
return None
|
|
115
|
+
return str(path)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def populate_commits(model: capellambse.MelodyModel):
|
|
119
|
+
path = init_model(model)
|
|
120
|
+
if not path:
|
|
121
|
+
return path
|
|
122
|
+
return get_commit_hashes(path)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _serialize_obj(obj: t.Any) -> t.Any:
|
|
126
|
+
if isinstance(obj, m.ModelElement):
|
|
127
|
+
return {"uuid": obj.uuid, "display_name": _get_name(obj)}
|
|
128
|
+
if isinstance(obj, m.ElementList):
|
|
129
|
+
return [{"uuid": i.uuid, "display_name": _get_name(i)} for i in obj]
|
|
130
|
+
if isinstance(obj, enum.Enum | enum.Flag):
|
|
131
|
+
return obj.name
|
|
132
|
+
return obj
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def get_diff_data(model: capellambse.MelodyModel, head: str, prev: str):
|
|
136
|
+
path = init_model(model)
|
|
137
|
+
if not path:
|
|
138
|
+
return None
|
|
139
|
+
path = str(pathlib.Path(path).resolve())
|
|
140
|
+
old_model = capellambse.MelodyModel(path=f"git+{path}", revision=prev)
|
|
141
|
+
|
|
142
|
+
metadata: Metadata = {
|
|
143
|
+
"model": {"path": path, "entrypoint": None},
|
|
144
|
+
"old_revision": _get_revision_info(path, prev),
|
|
145
|
+
"new_revision": _get_revision_info(path, head),
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
objects = compare_models(old_model, model)
|
|
149
|
+
diff_data: ChangeSummaryDocument = {
|
|
150
|
+
"metadata": metadata,
|
|
151
|
+
"objects": objects,
|
|
152
|
+
}
|
|
153
|
+
return _traverse_and_diff(diff_data)
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def _get_revision_info(
|
|
157
|
+
repo_path: str,
|
|
158
|
+
revision: str,
|
|
159
|
+
) -> RevisionInfo:
|
|
160
|
+
"""Return the revision info of the given model."""
|
|
161
|
+
author, date_str, description = (
|
|
162
|
+
subprocess.check_output(
|
|
163
|
+
["git", "log", "-1", "--format=%aN%x00%aI%x00%B", revision],
|
|
164
|
+
cwd=repo_path,
|
|
165
|
+
encoding="utf-8",
|
|
166
|
+
)
|
|
167
|
+
.strip()
|
|
168
|
+
.split("\x00")
|
|
169
|
+
)
|
|
170
|
+
subject = description.splitlines()[0] if description.splitlines() else ""
|
|
171
|
+
try:
|
|
172
|
+
tag = subprocess.check_output(
|
|
173
|
+
["git", "tag", "--points-at", revision],
|
|
174
|
+
cwd=repo_path,
|
|
175
|
+
encoding="utf-8",
|
|
176
|
+
stderr=subprocess.DEVNULL,
|
|
177
|
+
).strip()
|
|
178
|
+
except subprocess.CalledProcessError:
|
|
179
|
+
tag = None
|
|
180
|
+
|
|
181
|
+
return {
|
|
182
|
+
"hash": revision,
|
|
183
|
+
"revision": revision,
|
|
184
|
+
"author": author,
|
|
185
|
+
"date": datetime.datetime.fromisoformat(date_str),
|
|
186
|
+
"description": description.rstrip(),
|
|
187
|
+
"subject": subject,
|
|
188
|
+
"tag": tag if tag else None,
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def get_commit_hashes(path: str) -> list[RevisionInfo]:
|
|
193
|
+
"""Return the commit hashes of the given model."""
|
|
194
|
+
commit_hashes = subprocess.check_output(
|
|
195
|
+
["git", "log", "-n", NUM_COMMITS, "--format=%H"],
|
|
196
|
+
cwd=path,
|
|
197
|
+
encoding="utf-8",
|
|
198
|
+
).splitlines()
|
|
199
|
+
return [_get_revision_info(path, c) for c in commit_hashes]
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _get_name(obj: m.ModelObject) -> str:
|
|
203
|
+
"""Return the object's name.
|
|
204
|
+
|
|
205
|
+
If the object doesn't own a name, its type is returned instead.
|
|
206
|
+
"""
|
|
207
|
+
return getattr(obj, "name", None) or f"[{type(obj).__name__}]"
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def compare_models(
|
|
211
|
+
old: capellambse.MelodyModel,
|
|
212
|
+
new: capellambse.MelodyModel,
|
|
213
|
+
):
|
|
214
|
+
"""Compare all elements in the given models."""
|
|
215
|
+
changes = {}
|
|
216
|
+
for layer in (
|
|
217
|
+
"oa",
|
|
218
|
+
"sa",
|
|
219
|
+
"la",
|
|
220
|
+
"pa",
|
|
221
|
+
):
|
|
222
|
+
layer_old = getattr(old, layer)
|
|
223
|
+
layer_new = getattr(new, layer)
|
|
224
|
+
changes[layer] = compare_objects(layer_old, layer_new, old)
|
|
225
|
+
return changes
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def compare_objects(
|
|
229
|
+
old_object: capellambse.ModelObject | None,
|
|
230
|
+
new_object: capellambse.ModelObject,
|
|
231
|
+
old_model: capellambse.MelodyModel,
|
|
232
|
+
):
|
|
233
|
+
assert old_object is None or type(old_object) is type(
|
|
234
|
+
new_object
|
|
235
|
+
), f"{type(old_object).__name__} != {type(new_object).__name__}"
|
|
236
|
+
|
|
237
|
+
attributes: dict[str, ChangedAttribute] = {}
|
|
238
|
+
children: dict[str, t.Any] = {}
|
|
239
|
+
for attr in dir(type(new_object)):
|
|
240
|
+
acc = getattr(type(new_object), attr, None)
|
|
241
|
+
if isinstance(acc, m.BasePOD):
|
|
242
|
+
_handle_pod(attr, old_object, new_object, attributes)
|
|
243
|
+
elif isinstance(
|
|
244
|
+
acc, m.AttrProxyAccessor | m.LinkAccessor | m.ParentAccessor
|
|
245
|
+
):
|
|
246
|
+
_handle_accessors(attr, old_object, new_object, attributes)
|
|
247
|
+
elif (
|
|
248
|
+
# pylint: disable=unidiomatic-typecheck
|
|
249
|
+
type(acc) is m.RoleTagAccessor
|
|
250
|
+
or (type(acc) is m.DirectProxyAccessor and not acc.rootelem)
|
|
251
|
+
):
|
|
252
|
+
_handle_direct_accessors(
|
|
253
|
+
attr, old_object, new_object, children, old_model
|
|
254
|
+
)
|
|
255
|
+
|
|
256
|
+
if attributes or children or old_object is None:
|
|
257
|
+
return {
|
|
258
|
+
"display_name": _get_name(new_object),
|
|
259
|
+
"uuid": getattr(new_object, "uuid", None),
|
|
260
|
+
"change": "created" if old_object is None else "modified",
|
|
261
|
+
"attributes": attributes,
|
|
262
|
+
"children": children,
|
|
263
|
+
}
|
|
264
|
+
return {}
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def _handle_pod(attr, old_object, new_object, attributes):
|
|
268
|
+
if attr != "uuid":
|
|
269
|
+
try:
|
|
270
|
+
old_value = getattr(old_object, attr, None)
|
|
271
|
+
new_value = getattr(new_object, attr, None)
|
|
272
|
+
if old_value != new_value:
|
|
273
|
+
attributes[attr] = {
|
|
274
|
+
"previous": _serialize_obj(old_value),
|
|
275
|
+
"current": _serialize_obj(new_value),
|
|
276
|
+
}
|
|
277
|
+
except Exception as e:
|
|
278
|
+
print(f"Failed to process attribute '{attr}': {e}")
|
|
279
|
+
else:
|
|
280
|
+
pass
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def _handle_accessors(attr, old_object, new_object, attributes):
|
|
284
|
+
old_value = getattr(old_object, attr, None)
|
|
285
|
+
new_value = getattr(new_object, attr, None)
|
|
286
|
+
if isinstance(old_value, m.ModelElement | type(None)) and isinstance(
|
|
287
|
+
new_value, m.ModelElement | type(None)
|
|
288
|
+
):
|
|
289
|
+
if old_value is new_value is None:
|
|
290
|
+
pass
|
|
291
|
+
elif old_value is None:
|
|
292
|
+
attributes[attr] = {
|
|
293
|
+
"previous": None,
|
|
294
|
+
"current": _serialize_obj(new_value),
|
|
295
|
+
}
|
|
296
|
+
elif new_value is None:
|
|
297
|
+
attributes[attr] = {
|
|
298
|
+
"previous": _serialize_obj(old_value),
|
|
299
|
+
"current": None,
|
|
300
|
+
}
|
|
301
|
+
elif old_value.uuid != new_value.uuid:
|
|
302
|
+
attributes[attr] = {
|
|
303
|
+
"previous": _serialize_obj(old_value),
|
|
304
|
+
"current": _serialize_obj(new_value),
|
|
305
|
+
}
|
|
306
|
+
elif isinstance(old_value, m.ElementList | type(None)) and isinstance(
|
|
307
|
+
new_value, m.ElementList
|
|
308
|
+
):
|
|
309
|
+
old_value = old_value or []
|
|
310
|
+
if [i.uuid for i in old_value] != [i.uuid for i in new_value]:
|
|
311
|
+
attributes[attr] = {
|
|
312
|
+
"previous": _serialize_obj(old_value),
|
|
313
|
+
"current": _serialize_obj(new_value),
|
|
314
|
+
}
|
|
315
|
+
else:
|
|
316
|
+
raise RuntimeError(
|
|
317
|
+
f"Type mismatched between new value and old value:"
|
|
318
|
+
f" {type(old_value)} != {type(new_value)}"
|
|
319
|
+
)
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def _handle_direct_accessors(
|
|
323
|
+
attr, old_object, new_object, children, old_model
|
|
324
|
+
):
|
|
325
|
+
old_value = getattr(old_object, attr, None)
|
|
326
|
+
new_value = getattr(new_object, attr, None)
|
|
327
|
+
if isinstance(old_value, m.ModelElement | type(None)) and isinstance(
|
|
328
|
+
new_value, m.ModelElement | type(None)
|
|
329
|
+
):
|
|
330
|
+
if old_value is new_value is None:
|
|
331
|
+
pass
|
|
332
|
+
elif old_value is None:
|
|
333
|
+
assert new_value is not None
|
|
334
|
+
children[new_value.uuid] = compare_objects(
|
|
335
|
+
None, new_value, old_model
|
|
336
|
+
)
|
|
337
|
+
elif new_value is None:
|
|
338
|
+
children[old_value.uuid] = {
|
|
339
|
+
"display_name": _get_name(old_value),
|
|
340
|
+
"change": "deleted",
|
|
341
|
+
}
|
|
342
|
+
elif old_value.uuid == new_value.uuid:
|
|
343
|
+
result = compare_objects(old_value, new_value, old_model)
|
|
344
|
+
if result:
|
|
345
|
+
children[new_value.uuid] = result
|
|
346
|
+
else:
|
|
347
|
+
children[old_value.uuid] = {
|
|
348
|
+
"display_name": _get_name(old_value),
|
|
349
|
+
"change": "deleted",
|
|
350
|
+
}
|
|
351
|
+
children[new_value.uuid] = compare_objects(
|
|
352
|
+
None, new_value, old_model
|
|
353
|
+
)
|
|
354
|
+
elif isinstance(old_value, m.ElementList | type(None)) and isinstance(
|
|
355
|
+
new_value, m.ElementList
|
|
356
|
+
):
|
|
357
|
+
old_value = old_value or []
|
|
358
|
+
for item in new_value:
|
|
359
|
+
try:
|
|
360
|
+
old_item = old_model.by_uuid(item.uuid)
|
|
361
|
+
except KeyError:
|
|
362
|
+
old_item = None
|
|
363
|
+
if old_item is None:
|
|
364
|
+
children[item.uuid] = compare_objects(None, item, old_model)
|
|
365
|
+
else:
|
|
366
|
+
result = compare_objects(old_item, item, old_model)
|
|
367
|
+
if result:
|
|
368
|
+
children[item.uuid] = result
|
|
369
|
+
|
|
370
|
+
for item in old_value:
|
|
371
|
+
try:
|
|
372
|
+
new_object._model.by_uuid(item.uuid)
|
|
373
|
+
except KeyError:
|
|
374
|
+
children[item.uuid] = {
|
|
375
|
+
"display_name": _get_name(item),
|
|
376
|
+
"change": "deleted",
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
def _traverse_and_diff(data) -> dict[str, t.Any]:
|
|
381
|
+
"""Traverse the data and perform diff on text fields.
|
|
382
|
+
|
|
383
|
+
This function recursively traverses the data and performs an HTML
|
|
384
|
+
diff on every "name" and "description" field that has child keys
|
|
385
|
+
"previous" and "current". The result is stored in a new child key
|
|
386
|
+
"diff".
|
|
387
|
+
"""
|
|
388
|
+
updates = {}
|
|
389
|
+
for key, value in data.items():
|
|
390
|
+
if (
|
|
391
|
+
isinstance(value, dict)
|
|
392
|
+
and "previous" in value
|
|
393
|
+
and "current" in value
|
|
394
|
+
):
|
|
395
|
+
curr_type = type(value["current"])
|
|
396
|
+
if curr_type is str:
|
|
397
|
+
diff = _diff_text(
|
|
398
|
+
(value["previous"] or "").splitlines(),
|
|
399
|
+
value["current"].splitlines(),
|
|
400
|
+
)
|
|
401
|
+
updates[key] = {"diff": diff}
|
|
402
|
+
elif curr_type is dict:
|
|
403
|
+
diff = _diff_objects(value["previous"], value["current"])
|
|
404
|
+
updates[key] = {"diff": diff}
|
|
405
|
+
elif curr_type is list:
|
|
406
|
+
diff = _diff_lists(value["previous"], value["current"])
|
|
407
|
+
updates[key] = {"diff": diff}
|
|
408
|
+
elif key == "description":
|
|
409
|
+
prev, curr = _diff_description(
|
|
410
|
+
(value["previous"] or "").splitlines(),
|
|
411
|
+
value["current"].splitlines(),
|
|
412
|
+
)
|
|
413
|
+
if prev is curr is None:
|
|
414
|
+
continue
|
|
415
|
+
updates[key] = {"diff": ""}
|
|
416
|
+
value.update({"previous": prev, "current": curr})
|
|
417
|
+
elif isinstance(value, list):
|
|
418
|
+
for item in value:
|
|
419
|
+
_traverse_and_diff(item)
|
|
420
|
+
elif isinstance(value, dict):
|
|
421
|
+
_traverse_and_diff(value)
|
|
422
|
+
for key, value in updates.items():
|
|
423
|
+
data[key].update(value)
|
|
424
|
+
return data
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
def _diff_text(previous, current) -> str:
|
|
428
|
+
dmp = diff_match_patch.diff_match_patch()
|
|
429
|
+
diff = dmp.diff_main("\n".join(previous), "\n".join(current))
|
|
430
|
+
dmp.diff_cleanupSemantic(diff)
|
|
431
|
+
return dmp.diff_prettyHtml(diff)
|
|
432
|
+
|
|
433
|
+
|
|
434
|
+
def _diff_objects(previous, current) -> str:
|
|
435
|
+
return (
|
|
436
|
+
f"<del>{previous['display_name']}</del> → " if previous else ""
|
|
437
|
+
) + f"<ins>{current['display_name']}</ins>"
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
def _diff_lists(previous, current):
|
|
441
|
+
out = {}
|
|
442
|
+
previous = {item["uuid"]: item for item in previous}
|
|
443
|
+
for item in current:
|
|
444
|
+
if item["uuid"] not in previous:
|
|
445
|
+
out[item["uuid"]] = f"<ins>{item['display_name']}</ins>"
|
|
446
|
+
elif item["uuid"] in previous:
|
|
447
|
+
if item["display_name"] != previous[item["uuid"]]["display_name"]:
|
|
448
|
+
out[item["uuid"]] = (
|
|
449
|
+
f"{_diff_objects(previous[item['uuid']], item)}"
|
|
450
|
+
)
|
|
451
|
+
else:
|
|
452
|
+
out[item["uuid"]] = f"{item['display_name']}"
|
|
453
|
+
current = {item["uuid"]: item for item in current}
|
|
454
|
+
for uuid in previous:
|
|
455
|
+
if uuid not in current:
|
|
456
|
+
out[uuid] = f"<del>{previous[uuid]['display_name']}</del>"
|
|
457
|
+
return out
|
|
458
|
+
|
|
459
|
+
|
|
460
|
+
def _diff_description(
|
|
461
|
+
previous, current
|
|
462
|
+
) -> tuple[str, str] | tuple[None, None]:
|
|
463
|
+
if previous is current is None:
|
|
464
|
+
return None, None
|
|
465
|
+
dmp = diff_match_patch.diff_match_patch()
|
|
466
|
+
diff = dmp.diff_main("\n".join(previous), "\n".join(current))
|
|
467
|
+
dmp.diff_cleanupSemantic(diff)
|
|
468
|
+
previous_result = ""
|
|
469
|
+
current_result = ""
|
|
470
|
+
for operation, text in diff:
|
|
471
|
+
if operation == 0:
|
|
472
|
+
previous_result += text
|
|
473
|
+
current_result += text
|
|
474
|
+
elif operation == -1:
|
|
475
|
+
previous_result += f"<del class='text-removed'>{text}</del>"
|
|
476
|
+
elif operation == 1:
|
|
477
|
+
current_result += f"<ins class='text-added'>{text}</ins>"
|
|
478
|
+
return previous_result, current_result
|
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
# Copyright DB InfraGO AG and contributors
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
|
|
4
|
+
import operator
|
|
5
|
+
import traceback
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
import capellambse
|
|
10
|
+
import capellambse.model as m
|
|
11
|
+
import yaml
|
|
12
|
+
from pydantic import BaseModel, Field
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def simple_object(obj) -> dict[str, Any]:
|
|
16
|
+
if not obj:
|
|
17
|
+
return {}
|
|
18
|
+
if obj.name:
|
|
19
|
+
name = obj.name
|
|
20
|
+
else:
|
|
21
|
+
name = obj.long_name if hasattr(obj, "long_name") else "undefined"
|
|
22
|
+
|
|
23
|
+
return {"idx": obj.uuid, "name": str(name)}
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def find_objects(model, obj_type=None, below=None, attr=None, filters=None):
|
|
27
|
+
if attr:
|
|
28
|
+
getter = operator.attrgetter(attr)
|
|
29
|
+
objects = getter(model)
|
|
30
|
+
if hasattr(objects, "_element"):
|
|
31
|
+
objects = [objects]
|
|
32
|
+
elif not isinstance(objects, m.ElementList):
|
|
33
|
+
raise ValueError(
|
|
34
|
+
f"Expected a list of model objects or a single model object"
|
|
35
|
+
f" for {attr!r} of the model, got {objects!r}"
|
|
36
|
+
)
|
|
37
|
+
elif below and obj_type:
|
|
38
|
+
getter = operator.attrgetter(below)
|
|
39
|
+
objects = model.search(obj_type, below=getter(model))
|
|
40
|
+
elif obj_type:
|
|
41
|
+
objects = model.search(obj_type)
|
|
42
|
+
else:
|
|
43
|
+
raise ValueError("No search criteria provided")
|
|
44
|
+
|
|
45
|
+
if filters:
|
|
46
|
+
filtered = []
|
|
47
|
+
for object in objects:
|
|
48
|
+
for attr_key, filter in filters.items():
|
|
49
|
+
attr = getattr(object, attr_key)
|
|
50
|
+
if filter == "not_empty":
|
|
51
|
+
if attr:
|
|
52
|
+
filtered.append(object)
|
|
53
|
+
elif attr == filter:
|
|
54
|
+
filtered.append(object)
|
|
55
|
+
objects = filtered
|
|
56
|
+
return objects
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class InstanceDetails(BaseModel):
|
|
60
|
+
idx: str = Field(..., title="Instance Identifier")
|
|
61
|
+
name: str = Field(..., title="Instance Name")
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class TemplateScope(BaseModel):
|
|
65
|
+
type: str | None = Field(None, title="Model Element Type")
|
|
66
|
+
below: str | None = Field(
|
|
67
|
+
None, title="Model element to search below, scope limiter"
|
|
68
|
+
)
|
|
69
|
+
filters: dict[str, Any] | None = Field(
|
|
70
|
+
{}, title="Filters to apply to the search"
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class Template(BaseModel):
|
|
75
|
+
idx: str = Field(..., title="Template Identifier")
|
|
76
|
+
name: str = Field(..., title="Template Name")
|
|
77
|
+
template: Path = Field(..., title="Template File Path")
|
|
78
|
+
description: str = Field(..., title="Template Description")
|
|
79
|
+
|
|
80
|
+
scope: TemplateScope | None = Field(
|
|
81
|
+
default_factory=dict, title="Template Scope"
|
|
82
|
+
)
|
|
83
|
+
single: bool | None = Field(None, title="Single Instance Flag")
|
|
84
|
+
isStable: bool | None = Field(None, title="Stable Template Flag")
|
|
85
|
+
isDocument: bool | None = Field(None, title="Document Template Flag")
|
|
86
|
+
isExperimental: bool | None = Field(
|
|
87
|
+
None, title="Experimental Template Flag"
|
|
88
|
+
)
|
|
89
|
+
error: str | None = Field(None, title="Broken Template Flag")
|
|
90
|
+
traceback: str | None = Field(None, title="Template Error Traceback")
|
|
91
|
+
instanceCount: int | None = Field(None, title="Number of Instances")
|
|
92
|
+
instanceList: list[dict] | None = Field(None, title="List of Instances")
|
|
93
|
+
|
|
94
|
+
def find_instances(self, model: capellambse.MelodyModel):
|
|
95
|
+
if self.single:
|
|
96
|
+
return [
|
|
97
|
+
None,
|
|
98
|
+
]
|
|
99
|
+
try:
|
|
100
|
+
if self.scope is not None:
|
|
101
|
+
return find_objects(
|
|
102
|
+
model,
|
|
103
|
+
obj_type=self.scope.type,
|
|
104
|
+
below=self.scope.below,
|
|
105
|
+
attr=None,
|
|
106
|
+
filters=self.scope.filters,
|
|
107
|
+
)
|
|
108
|
+
return []
|
|
109
|
+
except Exception as e:
|
|
110
|
+
self.error = f"Template scope error: {e}"
|
|
111
|
+
self.traceback = traceback.format_exc()
|
|
112
|
+
return []
|
|
113
|
+
|
|
114
|
+
def compute_instance_count(self, model: capellambse.MelodyModel):
|
|
115
|
+
self.instanceCount = len(self.find_instances(model))
|
|
116
|
+
|
|
117
|
+
def compute_instance_list(self, model: capellambse.MelodyModel):
|
|
118
|
+
self.instanceList = [
|
|
119
|
+
simple_object(obj) for obj in self.find_instances(model)
|
|
120
|
+
]
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
class TemplateCategory(BaseModel):
|
|
124
|
+
idx: str = Field(..., title="Category Identifier")
|
|
125
|
+
templates: list[Template] = Field(
|
|
126
|
+
default_factory=list, title="Templates in this category"
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
def __add__(self, other):
|
|
130
|
+
if not isinstance(other, TemplateCategory):
|
|
131
|
+
return NotImplemented
|
|
132
|
+
return TemplateCategory(
|
|
133
|
+
idx=self.idx, templates=self.templates + other.templates
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
class TemplateCategories(BaseModel):
|
|
138
|
+
categories: list[TemplateCategory] = Field(
|
|
139
|
+
default_factory=list, title="Template Categories"
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
def __getitem__(self, category_id: str):
|
|
143
|
+
results = [cat for cat in self.categories if cat.idx == category_id]
|
|
144
|
+
return results[0] if results else None
|
|
145
|
+
|
|
146
|
+
def __add__(self, other):
|
|
147
|
+
if not isinstance(other, TemplateCategories):
|
|
148
|
+
return NotImplemented
|
|
149
|
+
for category in other.categories:
|
|
150
|
+
category_id = category.idx
|
|
151
|
+
if category_id in [cat.idx for cat in self.categories]:
|
|
152
|
+
for template in other[category_id].templates:
|
|
153
|
+
if template.idx not in [
|
|
154
|
+
t.idx for t in self[category_id].templates
|
|
155
|
+
]:
|
|
156
|
+
self[category_id].templates.append(template)
|
|
157
|
+
else:
|
|
158
|
+
self.categories.append(
|
|
159
|
+
TemplateCategory(
|
|
160
|
+
idx=category_id, templates=category.templates
|
|
161
|
+
)
|
|
162
|
+
)
|
|
163
|
+
return self
|
|
164
|
+
|
|
165
|
+
def __len__(self):
|
|
166
|
+
return len(self.categories)
|
|
167
|
+
|
|
168
|
+
@property
|
|
169
|
+
def as_dict(self):
|
|
170
|
+
return {
|
|
171
|
+
category.idx: category.templates for category in self.categories
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
@property
|
|
175
|
+
def flat(self):
|
|
176
|
+
return {
|
|
177
|
+
template.idx: template
|
|
178
|
+
for category in self.categories
|
|
179
|
+
for template in category.templates
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
class TemplateLoader:
|
|
184
|
+
def __init__(self, model: capellambse.MelodyModel) -> None:
|
|
185
|
+
self.model = model
|
|
186
|
+
self.templates = TemplateCategories()
|
|
187
|
+
|
|
188
|
+
def index_path(self, path: Path) -> TemplateCategories:
|
|
189
|
+
self.templates = TemplateCategories() # reset templates
|
|
190
|
+
for template_file in path.glob("**/*.yaml"):
|
|
191
|
+
templates_data = yaml.safe_load(
|
|
192
|
+
template_file.read_text(encoding="utf8")
|
|
193
|
+
)
|
|
194
|
+
if "categories" in templates_data:
|
|
195
|
+
self.templates += TemplateCategories(**templates_data)
|
|
196
|
+
for cat in self.templates.categories:
|
|
197
|
+
for template in cat.templates:
|
|
198
|
+
template.compute_instance_count(self.model)
|
|
199
|
+
|
|
200
|
+
return self.templates
|
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: capella-model-explorer
|
|
3
|
+
Version: 0.2.2
|
|
4
|
+
Summary: A webapp for exploring Capella models
|
|
5
|
+
Author: DB InfraGO AG
|
|
6
|
+
License: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/DSD-DBS/capella-model-explorer
|
|
8
|
+
Project-URL: Documentation, https://dsd-dbs.github.io/capella-model-explorer
|
|
9
|
+
Platform: any
|
|
10
|
+
Classifier: Development Status :: 1 - Planning
|
|
11
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
12
|
+
Classifier: Natural Language :: English
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Requires-Python: <3.13,>=3.11
|
|
18
|
+
Description-Content-Type: text/markdown
|
|
19
|
+
Requires-Dist: capellambse<0.7,>=0.6.6
|
|
20
|
+
Requires-Dist: capellambse-context-diagrams>=0.4.1
|
|
21
|
+
Requires-Dist: capella-diff-tools
|
|
22
|
+
Requires-Dist: diff-match-patch
|
|
23
|
+
Requires-Dist: jinja2
|
|
24
|
+
Requires-Dist: fastapi
|
|
25
|
+
Requires-Dist: uvicorn
|
|
26
|
+
Requires-Dist: prometheus-client
|
|
27
|
+
Provides-Extra: docs
|
|
28
|
+
Requires-Dist: furo; extra == "docs"
|
|
29
|
+
Requires-Dist: sphinx; extra == "docs"
|
|
30
|
+
Requires-Dist: sphinx-copybutton; extra == "docs"
|
|
31
|
+
Requires-Dist: tomli; python_version < "3.11" and extra == "docs"
|
|
32
|
+
Provides-Extra: test
|
|
33
|
+
Requires-Dist: pytest; extra == "test"
|
|
34
|
+
Requires-Dist: pytest-cov; extra == "test"
|
|
35
|
+
|
|
36
|
+
<!--
|
|
37
|
+
~ Copyright DB InfraGO AG and contributors
|
|
38
|
+
~ SPDX-License-Identifier: Apache-2.0
|
|
39
|
+
-->
|
|
40
|
+
|
|
41
|
+
# Capella Model Explorer
|
|
42
|
+
|
|
43
|
+

|
|
44
|
+

|
|
45
|
+
|
|
46
|
+
A webapp for exploring Capella models through simple "auto-generated" textual
|
|
47
|
+
and graphical views.
|
|
48
|
+
|
|
49
|
+
**Longer story**:
|
|
50
|
+
|
|
51
|
+
We see a larger non-MBSE crowd struggling with the things hidden in the model.
|
|
52
|
+
With this app we expose model contents in an easy to review readable form with
|
|
53
|
+
basic graphical annotations. Under the hood it uses Jinja templates enabling
|
|
54
|
+
the tooling teams to support their users with model-derived documents of any
|
|
55
|
+
shape and form.
|
|
56
|
+
|
|
57
|
+
**Use cases**:
|
|
58
|
+
|
|
59
|
+
- Provide insights into / "spell-out" the model for non-MBSE stakeholders via
|
|
60
|
+
document-a-like dynamic views that describe model elements in a
|
|
61
|
+
human-readable form.
|
|
62
|
+
- Provide meaningful default views (that can be further customized) for the key
|
|
63
|
+
elements to kickstart the model exploration.
|
|
64
|
+
|
|
65
|
+
There are a few more use cases but we will reveal them a bit later.
|
|
66
|
+
|
|
67
|
+
# Quick start
|
|
68
|
+
|
|
69
|
+
Clone, then build and run locally with Docker:
|
|
70
|
+
|
|
71
|
+
```bash
|
|
72
|
+
docker build -t model-explorer:latest .
|
|
73
|
+
docker run -e ROUTE_PREFIX="" -v /absolute/path/to/your/model/folder/on/host:/model -v $(pwd)/templates:/views -p 8000:8000 model-explorer
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
Then open your browser at `http://localhost:8000/views` and start exploring
|
|
77
|
+
your model.
|
|
78
|
+
|
|
79
|
+
While the thing is running you can edit the templates in the `templates` folder
|
|
80
|
+
and see the changes immediately in the browser.
|
|
81
|
+
|
|
82
|
+
# Development (local)
|
|
83
|
+
|
|
84
|
+
To run the app in dev mode you'll need to first run `npm run build` - this is
|
|
85
|
+
needed by the backend to have some statics to serve. Then run `npm run dev` in
|
|
86
|
+
a terminal and
|
|
87
|
+
`python -m capella_model_explorer.backend path_to_model path_to_templates` in
|
|
88
|
+
another terminal. The backend and statically built frontend will be served at
|
|
89
|
+
`http://localhost:8000`. The live frontend will be served by vite at
|
|
90
|
+
`http://localhost:5173`(or similar, it will be printed in the terminal where
|
|
91
|
+
you ran `npm run dev`). If you wish to display the Frontend Software Version,
|
|
92
|
+
it will initially show 'Fetch Failed'. To successfully fetch and display the
|
|
93
|
+
version, you need to run the command `python frontend/fetch_version.py`.
|
|
94
|
+
|
|
95
|
+
# Installation
|
|
96
|
+
|
|
97
|
+
You can install the latest released version directly from PyPI.
|
|
98
|
+
|
|
99
|
+
```sh
|
|
100
|
+
pip install capella-model-explorer
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
To set up a development environment, clone the project and install it into a
|
|
104
|
+
virtual environment.
|
|
105
|
+
|
|
106
|
+
```sh
|
|
107
|
+
git clone https://github.com/DSD-DBS/capella-model-explorer
|
|
108
|
+
cd capella-model-explorer
|
|
109
|
+
python -m venv .venv
|
|
110
|
+
|
|
111
|
+
source .venv/bin/activate.sh # for Linux / Mac
|
|
112
|
+
.venv\Scripts\activate # for Windows
|
|
113
|
+
|
|
114
|
+
pip install -U pip pre-commit
|
|
115
|
+
pip install -e '.[docs,test]'
|
|
116
|
+
pre-commit install
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
# Front-end development
|
|
120
|
+
|
|
121
|
+
To develop the frontend:
|
|
122
|
+
|
|
123
|
+
```bash
|
|
124
|
+
cd frontend
|
|
125
|
+
npm install
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
then, to develop components `npm run storybook` and to develop the whole app
|
|
129
|
+
`npm run dev`
|
|
130
|
+
|
|
131
|
+
# Integration in the Capella Collaboration Manager
|
|
132
|
+
|
|
133
|
+
The Capella Model Explorer can be integrated into the
|
|
134
|
+
[Capella Collaboration Manager](https://github.com/DSD-DBS/capella-collab-manager).
|
|
135
|
+
|
|
136
|
+
To do so, you need a running instance of the Capella Collaboration Manager.
|
|
137
|
+
Navigate to `Menu` > `Settings` > `Tools` > `Add a new tool` and fill in the
|
|
138
|
+
following configuration:
|
|
139
|
+
|
|
140
|
+
```yaml
|
|
141
|
+
name: "Capella model explorer"
|
|
142
|
+
integrations:
|
|
143
|
+
t4c: false
|
|
144
|
+
pure_variants: false
|
|
145
|
+
jupyter: false
|
|
146
|
+
config:
|
|
147
|
+
resources:
|
|
148
|
+
cpu:
|
|
149
|
+
requests: 0.4
|
|
150
|
+
limits: 2
|
|
151
|
+
memory:
|
|
152
|
+
requests: 1.6Gi
|
|
153
|
+
limits: 6Gi
|
|
154
|
+
environment:
|
|
155
|
+
MODEL_ENTRYPOINT:
|
|
156
|
+
stage: before
|
|
157
|
+
value: "{CAPELLACOLLAB_SESSION_PROVISIONING[0][path]}"
|
|
158
|
+
ROUTE_PREFIX: "{CAPELLACOLLAB_SESSIONS_BASE_PATH}"
|
|
159
|
+
connection:
|
|
160
|
+
methods:
|
|
161
|
+
- id: f51872a8-1a4f-4a4d-b4f4-b39cbd31a75b
|
|
162
|
+
type: http
|
|
163
|
+
name: Direct Browser connection
|
|
164
|
+
sharing:
|
|
165
|
+
enabled: true
|
|
166
|
+
ports:
|
|
167
|
+
metrics: 8000
|
|
168
|
+
http: 8000
|
|
169
|
+
redirect_url: "{CAPELLACOLLAB_SESSIONS_SCHEME}://{CAPELLACOLLAB_SESSIONS_HOST}:{CAPELLACOLLAB_SESSIONS_PORT}{CAPELLACOLLAB_SESSIONS_BASE_PATH}/"
|
|
170
|
+
monitoring:
|
|
171
|
+
prometheus:
|
|
172
|
+
path: /metrics
|
|
173
|
+
provisioning:
|
|
174
|
+
directory: /models
|
|
175
|
+
max_number_of_models: 1
|
|
176
|
+
persistent_workspaces:
|
|
177
|
+
mounting_enabled: false
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
You can tune the resources according to your needs.
|
|
181
|
+
|
|
182
|
+
After saving the configuration, you have to add a version for the new tool.
|
|
183
|
+
Since the Capella Model Explorer can load different Capella versions, we can
|
|
184
|
+
use one generic version:
|
|
185
|
+
|
|
186
|
+
```yaml
|
|
187
|
+
name: "Generic"
|
|
188
|
+
config:
|
|
189
|
+
is_recommended: true
|
|
190
|
+
is_deprecated: false
|
|
191
|
+
sessions:
|
|
192
|
+
persistent:
|
|
193
|
+
image: ghcr.io/dsd-dbs/capella-model-explorer/model-explorer:latest
|
|
194
|
+
backups:
|
|
195
|
+
image: null
|
|
196
|
+
compatible_versions: [1, 2, 3, 4]
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
Replace the numbers in `compatible_versions` with the version IDs for the
|
|
200
|
+
versions you want to support.
|
|
201
|
+
|
|
202
|
+
When configured properly, users will be able to start read-only sessions for
|
|
203
|
+
the Capella Model Explorer. More information about read-only sessions is
|
|
204
|
+
available in the
|
|
205
|
+
[Capella Collaboration Manager documentation](https://dsd-dbs.github.io/capella-collab-manager/user/sessions/types/read-only/).
|
|
206
|
+
|
|
207
|
+
# Contributing
|
|
208
|
+
|
|
209
|
+
We'd love to see your bug reports and improvement suggestions! Please take a
|
|
210
|
+
look at our [guidelines for contributors](CONTRIBUTING.md) for details.
|
|
211
|
+
|
|
212
|
+
# Licenses
|
|
213
|
+
|
|
214
|
+
This project is compliant with the
|
|
215
|
+
[REUSE Specification Version 3.0](https://git.fsfe.org/reuse/docs/src/commit/d173a27231a36e1a2a3af07421f5e557ae0fec46/spec.md).
|
|
216
|
+
|
|
217
|
+
Copyright DB InfraGO AG, licensed under Apache 2.0 (see full text in
|
|
218
|
+
[LICENSES/Apache-2.0.txt](LICENSES/Apache-2.0.txt))
|
|
219
|
+
|
|
220
|
+
Dot-files are licensed under CC0-1.0 (see full text in
|
|
221
|
+
[LICENSES/CC0-1.0.txt](LICENSES/CC0-1.0.txt))
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
capella_model_explorer/__init__.py,sha256=coMJvJF5sp7crUBL7AOFt-lcXWmTWyP7o0ieEEu7YGQ,327
|
|
2
|
+
capella_model_explorer/backend/__init__.py,sha256=coMJvJF5sp7crUBL7AOFt-lcXWmTWyP7o0ieEEu7YGQ,327
|
|
3
|
+
capella_model_explorer/backend/__main__.py,sha256=J8XqIfn1CyzZzEbbcjwCKkkLvCZoSQmPQr0seuV4wlg,811
|
|
4
|
+
capella_model_explorer/backend/explorer.py,sha256=RX9fXbylaufT6zeCdclCkipU6YHQ6eJIhDnrMDBuj98,13387
|
|
5
|
+
capella_model_explorer/backend/model_diff.py,sha256=5baeBc4xUilOm2H-UCxFWWNpIDsU7nuv3SG_ZNZ1X7A,15413
|
|
6
|
+
capella_model_explorer/backend/templates.py,sha256=OP88_2qhXBsoTbsezbN7h9VThHkfqUFoIA9gLFt_B0c,6667
|
|
7
|
+
capella_model_explorer-0.2.2.dist-info/METADATA,sha256=HrSkrL9vOeBQG9LvQLIjmMczt1L4VXGxA4FIE1rPIJI,7143
|
|
8
|
+
capella_model_explorer-0.2.2.dist-info/WHEEL,sha256=GV9aMThwP_4oNCtvEC2ec3qUYutgWeAzklro_0m4WJQ,91
|
|
9
|
+
capella_model_explorer-0.2.2.dist-info/top_level.txt,sha256=Vfbx-44T7IvmipvJTbR8nlkMTBOp7XT28ulVeIMDDdQ,23
|
|
10
|
+
capella_model_explorer-0.2.2.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
capella_model_explorer
|