erdify-studio 0.1.0__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.
Files changed (43) hide show
  1. erdify_studio/__init__.py +63 -0
  2. erdify_studio/__main__.py +7 -0
  3. erdify_studio/_check.py +215 -0
  4. erdify_studio/_config.py +95 -0
  5. erdify_studio/_diagrams.py +433 -0
  6. erdify_studio/_entities.py +101 -0
  7. erdify_studio/_errors.py +48 -0
  8. erdify_studio/_export.py +353 -0
  9. erdify_studio/_geometry.py +181 -0
  10. erdify_studio/_layout.py +334 -0
  11. erdify_studio/_place.py +351 -0
  12. erdify_studio/_server.py +536 -0
  13. erdify_studio/_static/THIRD_PARTY_LICENSES.txt +552 -0
  14. erdify_studio/_static/assets/Toast-DKNikwgv.js +15 -0
  15. erdify_studio/_static/assets/index-BwaNC2Tp.css +1 -0
  16. erdify_studio/_static/assets/index-DCr6Tq0B.js +15 -0
  17. erdify_studio/_static/assets/jetbrains-mono-cyrillic-400-normal-BEIGL1Tu.woff2 +0 -0
  18. erdify_studio/_static/assets/jetbrains-mono-cyrillic-400-normal-ugxPyKxw.woff +0 -0
  19. erdify_studio/_static/assets/jetbrains-mono-cyrillic-700-normal-BWTpRfYl.woff2 +0 -0
  20. erdify_studio/_static/assets/jetbrains-mono-cyrillic-700-normal-CEoEElIJ.woff +0 -0
  21. erdify_studio/_static/assets/jetbrains-mono-greek-400-normal-B9oWc5Lo.woff +0 -0
  22. erdify_studio/_static/assets/jetbrains-mono-greek-400-normal-C190GLew.woff2 +0 -0
  23. erdify_studio/_static/assets/jetbrains-mono-greek-700-normal-C6CZE3T8.woff2 +0 -0
  24. erdify_studio/_static/assets/jetbrains-mono-greek-700-normal-DEigVDxa.woff +0 -0
  25. erdify_studio/_static/assets/jetbrains-mono-latin-400-normal-6-qcROiO.woff +0 -0
  26. erdify_studio/_static/assets/jetbrains-mono-latin-400-normal-V6pRDFza.woff2 +0 -0
  27. erdify_studio/_static/assets/jetbrains-mono-latin-700-normal-BYuf6tUa.woff2 +0 -0
  28. erdify_studio/_static/assets/jetbrains-mono-latin-700-normal-D3wTyLJW.woff +0 -0
  29. erdify_studio/_static/assets/jetbrains-mono-latin-ext-400-normal-Bc8Ftmh3.woff2 +0 -0
  30. erdify_studio/_static/assets/jetbrains-mono-latin-ext-400-normal-fXTG6kC5.woff +0 -0
  31. erdify_studio/_static/assets/jetbrains-mono-latin-ext-700-normal-CZipNAKV.woff2 +0 -0
  32. erdify_studio/_static/assets/jetbrains-mono-latin-ext-700-normal-CxPITLHs.woff +0 -0
  33. erdify_studio/_static/assets/jetbrains-mono-vietnamese-400-normal-CqNFfHCs.woff +0 -0
  34. erdify_studio/_static/assets/jetbrains-mono-vietnamese-700-normal-BDLVIk2r.woff +0 -0
  35. erdify_studio/_static/index.html +13 -0
  36. erdify_studio/_svg.py +250 -0
  37. erdify_studio/cli.py +272 -0
  38. erdify_studio/py.typed +0 -0
  39. erdify_studio-0.1.0.dist-info/METADATA +224 -0
  40. erdify_studio-0.1.0.dist-info/RECORD +43 -0
  41. erdify_studio-0.1.0.dist-info/WHEEL +4 -0
  42. erdify_studio-0.1.0.dist-info/entry_points.txt +2 -0
  43. erdify_studio-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,63 @@
1
+ """erdify-studio: interactive, persistent ERD layouts for erdify."""
2
+
3
+ from importlib.metadata import PackageNotFoundError, version
4
+
5
+ from erdify_studio._check import Problem, ProblemKind, check_project
6
+ from erdify_studio._config import GroupBy, StudioConfig, load_config
7
+ from erdify_studio._entities import entity_groups, entity_key, entity_keys, enum_key
8
+ from erdify_studio._errors import (
9
+ ConfigError,
10
+ DuplicateKeyError,
11
+ LayoutError,
12
+ LayoutVersionError,
13
+ ProjectError,
14
+ StudioError,
15
+ )
16
+ from erdify_studio._layout import (
17
+ DEFAULT_GROUP,
18
+ LAYOUT_VERSION,
19
+ OVERVIEW,
20
+ Layout,
21
+ Position,
22
+ dumps_layout,
23
+ load_layout,
24
+ loads_layout,
25
+ save_layout,
26
+ )
27
+ from erdify_studio._place import PlaceResult, place_project
28
+
29
+ try:
30
+ __version__ = version("erdify-studio")
31
+ except PackageNotFoundError: # pragma: no cover - running from source without installed metadata
32
+ __version__ = "0.0.0"
33
+
34
+ __all__ = [
35
+ "DEFAULT_GROUP",
36
+ "LAYOUT_VERSION",
37
+ "OVERVIEW",
38
+ "ConfigError",
39
+ "DuplicateKeyError",
40
+ "GroupBy",
41
+ "Layout",
42
+ "LayoutError",
43
+ "LayoutVersionError",
44
+ "PlaceResult",
45
+ "Position",
46
+ "Problem",
47
+ "ProblemKind",
48
+ "ProjectError",
49
+ "StudioConfig",
50
+ "StudioError",
51
+ "__version__",
52
+ "check_project",
53
+ "dumps_layout",
54
+ "entity_groups",
55
+ "entity_key",
56
+ "entity_keys",
57
+ "enum_key",
58
+ "load_config",
59
+ "load_layout",
60
+ "loads_layout",
61
+ "place_project",
62
+ "save_layout",
63
+ ]
@@ -0,0 +1,7 @@
1
+ """Run the command-line interface with ``python -m erdify_studio``."""
2
+
3
+ import sys
4
+
5
+ from erdify_studio.cli import main
6
+
7
+ sys.exit(main())
@@ -0,0 +1,215 @@
1
+ """What each diagram must hold, and how a layout differs from it."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Collection, Mapping
6
+ from dataclasses import dataclass, field
7
+ from typing import Literal
8
+
9
+ from erdify import EntityInfo, Project, diagram_edges, enum_users
10
+
11
+ from erdify_studio._config import GroupBy, StudioConfig
12
+ from erdify_studio._entities import entity_groups, entity_ids, entity_keys, enum_key
13
+ from erdify_studio._errors import ProjectError
14
+ from erdify_studio._layout import OVERVIEW, Layout, load_existing_layout
15
+
16
+ #: How a layout differs from its diagrams (see ``Problem``).
17
+ ProblemKind = Literal["unplaced", "foreign", "enum", "stale_entry", "stale_diagram"]
18
+
19
+
20
+ @dataclass(frozen=True)
21
+ class DiagramContent:
22
+ """The layout keys one diagram shows.
23
+
24
+ Attributes:
25
+ entities: Keys of the diagram's own entities (every entity on the overview).
26
+ foreign: Keys of foreign boxes: entities of other groups that an own entity
27
+ references or is referenced by. Always empty on the overview.
28
+ enums: Keys of the enums erdify draws that an own entity uses (every drawn
29
+ enum on the overview).
30
+ """
31
+
32
+ entities: frozenset[str]
33
+ foreign: frozenset[str] = field(default_factory=frozenset)
34
+ enums: frozenset[str] = field(default_factory=frozenset)
35
+
36
+ @property
37
+ def shown(self) -> frozenset[str]:
38
+ """Every key the diagram shows."""
39
+ return self.entities | self.foreign | self.enums
40
+
41
+ def shows_edge(self, a: str, b: str) -> bool:
42
+ """Whether the diagram draws an edge between the keys ``a`` and ``b``.
43
+
44
+ Both must be shown and at least one must be an own entity: an edge between
45
+ two foreign boxes belongs to another group. The overview draws every edge.
46
+ """
47
+ shown = self.shown
48
+ return a in shown and b in shown and (a in self.entities or b in self.entities)
49
+
50
+ def shows_enum_link(self, enum: str, entity: str) -> bool:
51
+ """Whether the diagram links the enum ``enum`` to the own entity ``entity``."""
52
+ return enum in self.enums and entity in self.entities
53
+
54
+
55
+ @dataclass(frozen=True)
56
+ class Problem:
57
+ """One difference between a layout and its diagrams.
58
+
59
+ Attributes:
60
+ diagram: The diagram it is in.
61
+ key: The layout key; None for a ``stale_diagram``.
62
+ kind: ``unplaced`` (an own entity has no position), ``foreign`` (a foreign
63
+ box has no position), ``enum`` (a drawn enum has no position),
64
+ ``stale_entry`` (a position for a key the diagram
65
+ does not show) or ``stale_diagram`` (a diagram that no longer exists).
66
+ """
67
+
68
+ diagram: str
69
+ key: str | None
70
+ kind: ProblemKind
71
+
72
+ def __str__(self) -> str:
73
+ if self.kind == "stale_diagram":
74
+ return f"stale diagram {self.diagram!r}: no such group"
75
+ where = f"diagram {self.diagram!r}"
76
+ if self.kind == "unplaced":
77
+ return f"{where}: entity {self.key!r} has no position"
78
+ if self.kind == "foreign":
79
+ return f"{where}: foreign box {self.key!r} has no position"
80
+ if self.kind == "enum":
81
+ return f"{where}: enum {self.key!r} has no position"
82
+ return f"{where}: stale entry {self.key!r}: not in this diagram"
83
+
84
+
85
+ def diagram_contents(
86
+ entities: Mapping[str, EntityInfo],
87
+ group_by: GroupBy,
88
+ *,
89
+ relationships: bool = True,
90
+ enums: Mapping[str, Collection[str]] | None = None,
91
+ ) -> dict[str, DiagramContent]:
92
+ """Map every diagram (the overview and one per group) to the keys it shows.
93
+
94
+ A group diagram shows its own entities plus a foreign box for every entity of
95
+ another group connected to one of them by an edge of ``erdify.diagram_edges``,
96
+ in either direction. Without ``relationships`` (erdify's ``no_relationships``)
97
+ erdify draws no edges, so there are no foreign boxes.
98
+
99
+ ``enums`` maps the layout key of every enum erdify draws to the names
100
+ (``EntityInfo.name``) of the entities using it (``erdify.enum_users``): the
101
+ overview shows every one, a group diagram those its own entities use.
102
+
103
+ Raises:
104
+ DuplicateKeyError: An entity keyed by its erdify name has another entity's key.
105
+ LayoutError: A group value is a reserved diagram name.
106
+ """
107
+ keys = entity_keys(entities)
108
+ groups = entity_groups(entities, group_by)
109
+ ids = entity_ids(entities)
110
+ own: dict[str, set[str]] = {}
111
+ for name, group in groups.items():
112
+ own.setdefault(group, set()).add(keys[name])
113
+ foreign: dict[str, set[str]] = {group: set() for group in own}
114
+ if groups and relationships:
115
+ for edge in diagram_edges(entities):
116
+ source, target = ids[edge.from_entity], ids[edge.to_entity]
117
+ if groups[source] != groups[target]:
118
+ foreign[groups[source]].add(keys[target])
119
+ foreign[groups[target]].add(keys[source])
120
+
121
+ used: dict[str, set[str]] = {group: set() for group in own}
122
+ if groups:
123
+ for key, users in (enums or {}).items():
124
+ for name in users:
125
+ used[groups[ids[name]]].add(key)
126
+
127
+ contents = {OVERVIEW: DiagramContent(frozenset(keys.values()), enums=frozenset(enums or {}))}
128
+ for group in own:
129
+ contents[group] = DiagramContent(
130
+ frozenset(own[group]), frozenset(foreign[group]), frozenset(used[group])
131
+ )
132
+ return contents
133
+
134
+
135
+ def check_layout(layout: Layout, diagrams: Mapping[str, DiagramContent]) -> list[Problem]:
136
+ """Return how ``layout`` differs from ``diagrams``; empty when it matches.
137
+
138
+ Sorted by diagram (the overview first), then key.
139
+
140
+ A missing diagram is no problem of its own: its entities are reported unplaced.
141
+
142
+ Args:
143
+ layout: The layout to check.
144
+ diagrams: What each diagram shows (``diagram_contents``).
145
+ """
146
+ problems: list[Problem] = []
147
+ for name, content in diagrams.items():
148
+ placed = layout.diagrams.get(name, {})
149
+ problems += [Problem(name, key, "unplaced") for key in content.entities - placed.keys()]
150
+ problems += [Problem(name, key, "foreign") for key in content.foreign - placed.keys()]
151
+ problems += [Problem(name, key, "enum") for key in content.enums - placed.keys()]
152
+ problems += [Problem(name, key, "stale_entry") for key in placed.keys() - content.shown]
153
+ problems += [
154
+ Problem(name, None, "stale_diagram") for name in layout.diagrams.keys() - diagrams.keys()
155
+ ]
156
+ # The overview first, then the groups by name ("_" would sort after uppercase).
157
+ return sorted(problems, key=lambda p: (p.diagram != OVERVIEW, p.diagram, p.key or "", p.kind))
158
+
159
+
160
+ def check_project(project: Project, config: StudioConfig) -> list[Problem] | None:
161
+ """Check the layout file of ``config`` against ``project``.
162
+
163
+ Every enum erdify draws needs a position on the overview and on the group
164
+ diagrams of the entities using it.
165
+
166
+ Args:
167
+ project: The project as ``erdify.load_project`` returns it; load it with
168
+ ``strict=True``, else a file erdify cannot parse drops its tables and
169
+ their positions are reported stale.
170
+ config: Its studio settings (``load_config(project.settings.pyproject)``).
171
+
172
+ Returns:
173
+ The problems, sorted (empty when the layout matches); None when there is no
174
+ layout yet (no file, or an empty one).
175
+
176
+ Raises:
177
+ ProjectError: The project has no entities and erdify's ``allow_empty`` is
178
+ off, as ``erdify`` refuses it: every position would read as stale.
179
+ DuplicateKeyError: An entity keyed by its erdify name has another entity's key.
180
+ LayoutVersionError: The layout file is of another version.
181
+ LayoutError: A reserved group name, or a layout file that cannot be read.
182
+ """
183
+ diagrams = project_diagrams(project, config)
184
+ layout = load_existing_layout(config.layout)
185
+ if layout is None:
186
+ return None
187
+ return check_layout(layout, diagrams)
188
+
189
+
190
+ def project_diagrams(project: Project, config: StudioConfig) -> dict[str, DiagramContent]:
191
+ """``diagram_contents`` of ``project`` under ``config``.
192
+
193
+ Raises:
194
+ ProjectError: The project has no entities and erdify's ``allow_empty`` is
195
+ off, as ``erdify`` refuses it: every position would read as stale.
196
+ DuplicateKeyError: An entity keyed by its erdify name has another entity's key.
197
+ LayoutError: A group value is a reserved diagram name.
198
+ """
199
+ if not project.entities and not project.settings.allow_empty:
200
+ raise ProjectError(
201
+ f"no entities found in {str(project.settings.input)!r}; check the path and "
202
+ f"[tool.erdify] include / sources, or set allow_empty"
203
+ )
204
+ return diagram_contents(
205
+ project.entities,
206
+ config.group_by,
207
+ relationships=not project.settings.no_relationships,
208
+ enums=drawn_enums(project),
209
+ )
210
+
211
+
212
+ def drawn_enums(project: Project) -> dict[str, list[str]]:
213
+ """Layout key of every enum erdify draws -> the names of the entities using it."""
214
+ users = enum_users(project.entities, project.enums, include_enums=not project.settings.no_enums)
215
+ return {enum_key(project.enums[name]): entities for name, entities in users.items()}
@@ -0,0 +1,95 @@
1
+ """The ``[tool.erdify-studio]`` table of ``pyproject.toml``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import tomllib
7
+ from dataclasses import dataclass
8
+ from pathlib import Path
9
+ from typing import Literal, cast, get_args
10
+
11
+ from erdify_studio._errors import ConfigError
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+ #: How entities are grouped into diagrams besides the overview.
16
+ GroupBy = Literal["auto", "schema", "app", "module", "none"]
17
+
18
+ #: Layout file name used when ``layout`` is not configured.
19
+ DEFAULT_LAYOUT_NAME = "erdify-layout.json"
20
+
21
+ _TABLE = "erdify-studio"
22
+ _KEYS = ("layout", "group_by", "export_dir")
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class StudioConfig:
27
+ """Resolved erdify-studio settings.
28
+
29
+ Attributes:
30
+ layout: The layout file. Relative paths in ``pyproject.toml`` resolve from its
31
+ folder; the default is ``erdify-layout.json`` next to it, else in the
32
+ working directory.
33
+ group_by: How entities are grouped into diagrams (``GroupBy``).
34
+ export_dir: Directory for the exported SVGs; None when nothing is exported.
35
+ """
36
+
37
+ layout: Path
38
+ group_by: GroupBy
39
+ export_dir: Path | None
40
+
41
+
42
+ def load_config(pyproject: Path | None) -> StudioConfig:
43
+ """Read ``[tool.erdify-studio]`` from ``pyproject`` and resolve it.
44
+
45
+ Pass the ``pyproject.toml`` erdify resolved for the project
46
+ (``erdify.resolve_settings(path).pyproject``), so both tools read the same file.
47
+
48
+ Args:
49
+ pyproject: The ``pyproject.toml``, or None when the project has none (the
50
+ defaults then resolve from the working directory).
51
+
52
+ Raises:
53
+ ConfigError: The file cannot be read, or a value has the wrong type.
54
+ """
55
+ base = pyproject.parent if pyproject is not None else Path.cwd()
56
+ table = _read_table(pyproject) if pyproject is not None else {}
57
+ source = str(pyproject)
58
+ for key in sorted(set(table) - set(_KEYS)):
59
+ logger.warning(f"unknown [tool.{_TABLE}] key {key!r} in {source}, ignored")
60
+
61
+ group_by = table.get("group_by", "auto")
62
+ choices = get_args(GroupBy)
63
+ if group_by not in choices:
64
+ raise ConfigError(
65
+ f"[tool.{_TABLE}] 'group_by' must be one of {', '.join(choices)}, "
66
+ f"got {group_by!r} in {source}"
67
+ )
68
+ layout = _path(table, "layout", base, source) or base / DEFAULT_LAYOUT_NAME
69
+ export_dir = _path(table, "export_dir", base, source)
70
+ return StudioConfig(layout=layout, group_by=cast(GroupBy, group_by), export_dir=export_dir)
71
+
72
+
73
+ def _read_table(pyproject: Path) -> dict[str, object]:
74
+ try:
75
+ data = tomllib.loads(pyproject.read_text(encoding="utf-8"))
76
+ except (OSError, UnicodeDecodeError, tomllib.TOMLDecodeError) as e:
77
+ raise ConfigError(f"cannot read {str(pyproject)!r}: {e}") from e
78
+ tool = data.get("tool", {})
79
+ if not isinstance(tool, dict):
80
+ raise ConfigError(f"[tool] must be a table in {pyproject}")
81
+ table = tool.get(_TABLE, {})
82
+ if not isinstance(table, dict):
83
+ raise ConfigError(f"[tool.{_TABLE}] must be a table in {pyproject}")
84
+ return table
85
+
86
+
87
+ def _path(table: dict[str, object], key: str, base: Path, source: str) -> Path | None:
88
+ if key not in table:
89
+ return None
90
+ value = table[key]
91
+ if not isinstance(value, str) or not value:
92
+ raise ConfigError(
93
+ f"[tool.{_TABLE}] {key!r} must be a non-empty string, got {value!r} in {source}"
94
+ )
95
+ return base / value