sheetmap 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.
- sheetmap/__init__.py +9 -0
- sheetmap/__main__.py +5 -0
- sheetmap/addressing.py +57 -0
- sheetmap/cli.py +88 -0
- sheetmap/draw.py +417 -0
- sheetmap/errors.py +2 -0
- sheetmap/layout.py +247 -0
- sheetmap/model.py +246 -0
- sheetmap/page.py +268 -0
- sheetmap/py.typed +0 -0
- sheetmap/render.py +193 -0
- sheetmap-0.1.0.dist-info/METADATA +255 -0
- sheetmap-0.1.0.dist-info/RECORD +15 -0
- sheetmap-0.1.0.dist-info/WHEEL +4 -0
- sheetmap-0.1.0.dist-info/entry_points.txt +2 -0
sheetmap/layout.py
ADDED
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
"""A small layout engine: arrange sheet images into sections, rows and columns.
|
|
2
|
+
|
|
3
|
+
Every image has two dimensions: the map it belongs to and the sheet it shows. A layout says which
|
|
4
|
+
dimension forms the sections, which forms the rows and which forms the columns. Column widths are
|
|
5
|
+
shared across sections, so the same map or sheet lines up all the way down the page. Explicit
|
|
6
|
+
``cells`` place images by hand instead.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from collections.abc import Sequence
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
|
|
12
|
+
from sheetmap.errors import SheetmapError
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
DIMENSIONS = ("map", "sheet")
|
|
16
|
+
SECTION_CHOICES = ("auto", "none", *DIMENSIONS)
|
|
17
|
+
EMPTY_COLUMN_WIDTH = 200
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass
|
|
21
|
+
class Figure:
|
|
22
|
+
"""One sheet image and what the page says about it."""
|
|
23
|
+
|
|
24
|
+
map_key: str
|
|
25
|
+
map_title: str
|
|
26
|
+
subtitle: str | None
|
|
27
|
+
workbook: str
|
|
28
|
+
sheet: str
|
|
29
|
+
png: bytes
|
|
30
|
+
width: int
|
|
31
|
+
height: int
|
|
32
|
+
regions: int
|
|
33
|
+
rows: int
|
|
34
|
+
cols: int
|
|
35
|
+
rows_cut: bool = False
|
|
36
|
+
cols_cut: bool = False
|
|
37
|
+
buttons: list[str] = field(default_factory=list)
|
|
38
|
+
|
|
39
|
+
@property
|
|
40
|
+
def map_name(self) -> str:
|
|
41
|
+
return join(self.map_title, self.subtitle)
|
|
42
|
+
|
|
43
|
+
def value(self, dimension: str) -> str:
|
|
44
|
+
return self.map_key if dimension == "map" else self.sheet
|
|
45
|
+
|
|
46
|
+
def label(self, dimension: str) -> str:
|
|
47
|
+
return self.map_name if dimension == "map" else self.sheet
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@dataclass(frozen=True)
|
|
51
|
+
class Layout:
|
|
52
|
+
"""How the page arranges sheet images.
|
|
53
|
+
|
|
54
|
+
``sections``, ``rows`` and ``columns`` each take ``"map"`` or ``"sheet"``, and each dimension can be
|
|
55
|
+
used once. ``sections`` also takes ``"none"`` for one undivided grid, or ``"auto"``, which uses
|
|
56
|
+
whichever dimension ``rows`` and ``columns`` leave free (``"map"`` when both are free).
|
|
57
|
+
|
|
58
|
+
When only one of ``rows`` and ``columns`` is set, the free dimension fills the other. When neither
|
|
59
|
+
is set, images flow: side by side while they fit, or ``wrap`` to a column count.
|
|
60
|
+
|
|
61
|
+
``fit`` scales grids down to the window, every image by the same amount; otherwise images keep their
|
|
62
|
+
full size and the page scrolls sideways when they do not fit. Flowing images always keep their size.
|
|
63
|
+
|
|
64
|
+
``cells`` places images by hand, as rows of ``"map/sheet"`` references, where map is a map's key or
|
|
65
|
+
title. ``None`` leaves a gap. Images not referenced are left out.
|
|
66
|
+
"""
|
|
67
|
+
|
|
68
|
+
sections: str = "auto"
|
|
69
|
+
rows: str | None = None
|
|
70
|
+
columns: str | None = None
|
|
71
|
+
wrap: int | None = None
|
|
72
|
+
fit: bool = False
|
|
73
|
+
cells: Sequence[Sequence[str | None]] | None = None
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
@dataclass
|
|
77
|
+
class Slot:
|
|
78
|
+
figure: Figure
|
|
79
|
+
caption: str | None
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
@dataclass
|
|
83
|
+
class Grid:
|
|
84
|
+
"""One section of the page. ``rows`` holds ``None`` where a grid position has no image."""
|
|
85
|
+
|
|
86
|
+
heading: str | None
|
|
87
|
+
rows: list[list[Slot | None]]
|
|
88
|
+
column_headers: list[str] | None = None
|
|
89
|
+
row_headers: list[str] | None = None
|
|
90
|
+
flow: bool = False
|
|
91
|
+
gaps_say: str = ""
|
|
92
|
+
column_widths: list[int] = field(default_factory=list)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def check_layout(layout: Layout) -> None:
|
|
96
|
+
if layout.sections not in SECTION_CHOICES:
|
|
97
|
+
raise SheetmapError(f"Layout sections must be one of {', '.join(SECTION_CHOICES)}, not {layout.sections!r}")
|
|
98
|
+
for axis in ("rows", "columns"):
|
|
99
|
+
value = getattr(layout, axis)
|
|
100
|
+
if value is not None and value not in DIMENSIONS:
|
|
101
|
+
raise SheetmapError(f"Layout {axis} must be map or sheet, not {value!r}")
|
|
102
|
+
used = [d for d in (layout.sections, layout.rows, layout.columns) if d in DIMENSIONS]
|
|
103
|
+
if len(used) != len(set(used)):
|
|
104
|
+
raise SheetmapError("Layout uses the same dimension twice; give sections, rows and columns different ones")
|
|
105
|
+
if layout.wrap is not None:
|
|
106
|
+
if layout.wrap < 1:
|
|
107
|
+
raise SheetmapError("Layout wrap must be at least 1")
|
|
108
|
+
if layout.columns or layout.rows or layout.cells:
|
|
109
|
+
raise SheetmapError("Layout wrap only applies when images flow, without rows, columns or cells")
|
|
110
|
+
if layout.cells is not None:
|
|
111
|
+
if layout.rows or layout.columns or layout.sections in DIMENSIONS:
|
|
112
|
+
raise SheetmapError("Layout cells place images by hand; leave out sections, rows and columns")
|
|
113
|
+
if not layout.cells or not all(isinstance(row, list | tuple) and row for row in layout.cells):
|
|
114
|
+
raise SheetmapError("Layout cells must be a list of non-empty rows")
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def arrange(figures: list[Figure], layout: Layout) -> list[Grid]:
|
|
118
|
+
"""Turn figures into grids, in the order maps were given and sheets appear in each workbook."""
|
|
119
|
+
check_layout(layout)
|
|
120
|
+
if layout.cells is not None:
|
|
121
|
+
grids = [_explicit(figures, layout.cells)]
|
|
122
|
+
else:
|
|
123
|
+
grids = _by_dimension(figures, layout)
|
|
124
|
+
_share_column_widths(grids)
|
|
125
|
+
return grids
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _by_dimension(figures: list[Figure], layout: Layout) -> list[Grid]:
|
|
129
|
+
rows, columns = layout.rows, layout.columns
|
|
130
|
+
sections = _sections(layout)
|
|
131
|
+
free = [d for d in DIMENSIONS if d not in (sections, rows, columns)]
|
|
132
|
+
# With one axis named, the free dimension fills the other, so each position holds one image.
|
|
133
|
+
if free and (rows or columns):
|
|
134
|
+
if rows:
|
|
135
|
+
columns = free.pop()
|
|
136
|
+
else:
|
|
137
|
+
rows = free.pop()
|
|
138
|
+
|
|
139
|
+
def caption(figure: Figure) -> str | None:
|
|
140
|
+
return join(*(figure.label(d) for d in free)) or None
|
|
141
|
+
|
|
142
|
+
row_values = _ordered(figures, rows)
|
|
143
|
+
column_values = _ordered(figures, columns)
|
|
144
|
+
grids = []
|
|
145
|
+
for heading, members in _group(figures, sections):
|
|
146
|
+
if not rows and not columns:
|
|
147
|
+
slots = [Slot(f, caption(f)) for f in members]
|
|
148
|
+
if layout.wrap:
|
|
149
|
+
chunks = [slots[i : i + layout.wrap] for i in range(0, len(slots), layout.wrap)]
|
|
150
|
+
grids.append(Grid(heading, chunks))
|
|
151
|
+
else:
|
|
152
|
+
grids.append(Grid(heading, [slots], flow=True))
|
|
153
|
+
continue
|
|
154
|
+
at = {(f.value(rows) if rows else None, f.value(columns) if columns else None): f for f in members}
|
|
155
|
+
grid_rows, row_headers = [], []
|
|
156
|
+
for row_value in row_values or [None]:
|
|
157
|
+
cells = [at.get((row_value, column_value)) for column_value in column_values or [None]]
|
|
158
|
+
if not any(cells):
|
|
159
|
+
continue
|
|
160
|
+
grid_rows.append([Slot(f, caption(f)) if f else None for f in cells])
|
|
161
|
+
if rows:
|
|
162
|
+
row_headers.append(_label(figures, rows, row_value))
|
|
163
|
+
grids.append(
|
|
164
|
+
Grid(
|
|
165
|
+
heading,
|
|
166
|
+
grid_rows,
|
|
167
|
+
column_headers=[_label(figures, columns, v) for v in column_values] if columns else None,
|
|
168
|
+
row_headers=row_headers if rows else None,
|
|
169
|
+
gaps_say=f"No regions on this {'sheet' if 'sheet' in (rows, columns) else 'map'}",
|
|
170
|
+
)
|
|
171
|
+
)
|
|
172
|
+
return grids
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _sections(layout: Layout) -> str | None:
|
|
176
|
+
if layout.sections == "none" or layout.cells is not None:
|
|
177
|
+
return None
|
|
178
|
+
if layout.sections in DIMENSIONS:
|
|
179
|
+
return layout.sections
|
|
180
|
+
free = [d for d in DIMENSIONS if d not in (layout.rows, layout.columns)]
|
|
181
|
+
return free[0] if free else None
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _group(figures: list[Figure], dimension: str | None) -> list[tuple[str | None, list[Figure]]]:
|
|
185
|
+
if dimension is None:
|
|
186
|
+
return [(None, figures)]
|
|
187
|
+
return [
|
|
188
|
+
(_label(figures, dimension, value), [f for f in figures if f.value(dimension) == value])
|
|
189
|
+
for value in _ordered(figures, dimension)
|
|
190
|
+
]
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _ordered(figures: list[Figure], dimension: str | None) -> list[str]:
|
|
194
|
+
return list(dict.fromkeys(f.value(dimension) for f in figures)) if dimension else []
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _label(figures: list[Figure], dimension: str, value: str) -> str:
|
|
198
|
+
return next(f.label(dimension) for f in figures if f.value(dimension) == value)
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def _explicit(figures: list[Figure], cells: Sequence[Sequence[str | None]]) -> Grid:
|
|
202
|
+
lookup: dict[str, Figure | None] = {}
|
|
203
|
+
for figure in figures:
|
|
204
|
+
for name in dict.fromkeys((figure.map_key, figure.map_title)):
|
|
205
|
+
reference = f"{name}/{figure.sheet}"
|
|
206
|
+
# Two maps sharing a title make the title ambiguous; their keys still work.
|
|
207
|
+
lookup[reference] = None if reference in lookup and lookup[reference] is not figure else figure
|
|
208
|
+
width = max(len(row) for row in cells)
|
|
209
|
+
rows = []
|
|
210
|
+
for row in cells:
|
|
211
|
+
slots: list[Slot | None] = []
|
|
212
|
+
for reference in row:
|
|
213
|
+
if reference is None:
|
|
214
|
+
slots.append(None)
|
|
215
|
+
continue
|
|
216
|
+
if reference not in lookup:
|
|
217
|
+
known = ", ".join(f"{f.map_key}/{f.sheet}" for f in figures)
|
|
218
|
+
raise SheetmapError(f"Layout cell {reference!r} matches no image; images are {known}")
|
|
219
|
+
figure = lookup[reference]
|
|
220
|
+
if figure is None:
|
|
221
|
+
raise SheetmapError(f"Layout cell {reference!r} matches more than one map; use a map key")
|
|
222
|
+
slots.append(Slot(figure, join(figure.map_name, figure.sheet)))
|
|
223
|
+
rows.append(slots + [None] * (width - len(slots)))
|
|
224
|
+
return Grid(None, rows)
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def _share_column_widths(grids: list[Grid]) -> None:
|
|
228
|
+
"""Give each column the width of its widest image on the whole page, so columns line up.
|
|
229
|
+
|
|
230
|
+
Fitted pages size columns in proportion to these widths, which scales every image by the same amount.
|
|
231
|
+
"""
|
|
232
|
+
widths: dict[int, int] = {}
|
|
233
|
+
for grid in grids:
|
|
234
|
+
if grid.flow:
|
|
235
|
+
continue
|
|
236
|
+
for row in grid.rows:
|
|
237
|
+
for index, slot in enumerate(row):
|
|
238
|
+
width = slot.figure.width if slot else 0
|
|
239
|
+
widths[index] = max(widths.get(index, 0), width)
|
|
240
|
+
for grid in grids:
|
|
241
|
+
if not grid.flow:
|
|
242
|
+
count = max(len(row) for row in grid.rows) if grid.rows else 0
|
|
243
|
+
grid.column_widths = [widths.get(i) or EMPTY_COLUMN_WIDTH for i in range(count)]
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def join(*parts: str | None) -> str:
|
|
247
|
+
return " · ".join(part for part in parts if part)
|
sheetmap/model.py
ADDED
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
"""Map definitions: which ranges of which workbook to label, in Python or a YAML map file."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Mapping, Sequence
|
|
4
|
+
from dataclasses import dataclass, field
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
import re
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
import yaml
|
|
10
|
+
|
|
11
|
+
from sheetmap.addressing import parse_reference
|
|
12
|
+
from sheetmap.errors import SheetmapError
|
|
13
|
+
from sheetmap.layout import Layout, check_layout
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
KINDS = ("cell", "range", "list", "table")
|
|
17
|
+
_COLOUR = re.compile(r"^#[0-9a-fA-F]{6}$")
|
|
18
|
+
_COLUMN_KEY = re.compile(r"^[A-Za-z]{1,3}$")
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass(frozen=True)
|
|
22
|
+
class Region:
|
|
23
|
+
"""A labelled cell or range.
|
|
24
|
+
|
|
25
|
+
``kind`` defaults to ``table`` when ``columns`` or ``rows`` are given, ``cell`` for a single cell and
|
|
26
|
+
``range`` otherwise. ``columns`` labels columns by letter, and ``rows`` labels rows by number for
|
|
27
|
+
tables that read across. A column without a label continues the label to its left when its cells are
|
|
28
|
+
empty, so merged headers can share one label.
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
label: str
|
|
32
|
+
ref: str
|
|
33
|
+
kind: str | None = None
|
|
34
|
+
columns: Mapping[str, str] | None = None
|
|
35
|
+
rows: Mapping[str, str] | None = None
|
|
36
|
+
colour: str | None = None
|
|
37
|
+
|
|
38
|
+
@property
|
|
39
|
+
def resolved_kind(self) -> str:
|
|
40
|
+
if self.kind:
|
|
41
|
+
return self.kind
|
|
42
|
+
if self.columns or self.rows:
|
|
43
|
+
return "table"
|
|
44
|
+
return "cell" if parse_reference(self.ref).is_cell else "range"
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@dataclass(frozen=True)
|
|
48
|
+
class Preview:
|
|
49
|
+
"""Limit a large sheet to this many rows and columns.
|
|
50
|
+
|
|
51
|
+
The preview always reaches the first row and last column of every region. Regions that run further
|
|
52
|
+
down are cut off at the preview's edge.
|
|
53
|
+
"""
|
|
54
|
+
|
|
55
|
+
rows: int
|
|
56
|
+
columns: int
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
@dataclass(frozen=True)
|
|
60
|
+
class SheetMap:
|
|
61
|
+
"""The regions to draw over one workbook.
|
|
62
|
+
|
|
63
|
+
``details`` are extra lines shown with review requests, such as a schema path or version. ``scope``,
|
|
64
|
+
when given, offers reviewers a checkbox with that text, for example ``Apply to every version``.
|
|
65
|
+
"""
|
|
66
|
+
|
|
67
|
+
workbook: str | Path
|
|
68
|
+
regions: Sequence[Region]
|
|
69
|
+
title: str | None = None
|
|
70
|
+
subtitle: str | None = None
|
|
71
|
+
key: str | None = None
|
|
72
|
+
details: Mapping[str, str] = field(default_factory=dict)
|
|
73
|
+
scope: str | None = None
|
|
74
|
+
preview: Mapping[str, Preview] = field(default_factory=dict)
|
|
75
|
+
|
|
76
|
+
@property
|
|
77
|
+
def resolved_title(self) -> str:
|
|
78
|
+
return self.title or Path(self.workbook).stem
|
|
79
|
+
|
|
80
|
+
@property
|
|
81
|
+
def resolved_key(self) -> str:
|
|
82
|
+
return self.key or self.resolved_title + "--" + Path(self.workbook).stem
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def validate(sheet_map: SheetMap) -> None:
|
|
86
|
+
"""Check a map's own consistency. Checks against the workbook happen when it is rendered."""
|
|
87
|
+
labels = set()
|
|
88
|
+
for region in sheet_map.regions:
|
|
89
|
+
where = f"region {region.label!r} in {sheet_map.resolved_title}"
|
|
90
|
+
if not region.label:
|
|
91
|
+
raise SheetmapError(f"A region in {sheet_map.resolved_title} has no label")
|
|
92
|
+
if region.label in labels:
|
|
93
|
+
raise SheetmapError(f"Duplicate label {region.label!r} in {sheet_map.resolved_title}")
|
|
94
|
+
labels.add(region.label)
|
|
95
|
+
reference = parse_reference(region.ref)
|
|
96
|
+
kind = region.resolved_kind
|
|
97
|
+
if kind not in KINDS:
|
|
98
|
+
raise SheetmapError(f"Unknown kind {kind!r} for {where}; use one of {', '.join(KINDS)}")
|
|
99
|
+
if kind == "cell" and not reference.is_cell:
|
|
100
|
+
raise SheetmapError(f"Cell {where} must refer to one cell, not {region.ref!r}")
|
|
101
|
+
if (region.columns or region.rows) and kind != "table":
|
|
102
|
+
raise SheetmapError(f"Only tables can label columns or rows ({where})")
|
|
103
|
+
if region.columns and region.rows:
|
|
104
|
+
raise SheetmapError(f"Give columns or rows, not both ({where})")
|
|
105
|
+
if region.columns and not all(_COLUMN_KEY.match(key) for key in region.columns):
|
|
106
|
+
raise SheetmapError(f"Column labels must be keyed by column letter ({where})")
|
|
107
|
+
if region.rows and not all(str(key).isdigit() for key in region.rows):
|
|
108
|
+
raise SheetmapError(f"Row labels must be keyed by row number ({where})")
|
|
109
|
+
if region.colour and not _COLOUR.match(region.colour):
|
|
110
|
+
raise SheetmapError(f"Colour for {where} must look like #1d4ed8")
|
|
111
|
+
for sheet, preview in sheet_map.preview.items():
|
|
112
|
+
if preview.rows < 1 or preview.columns < 1:
|
|
113
|
+
raise SheetmapError(f"Preview for sheet {sheet!r} needs at least one row and column")
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
@dataclass(frozen=True)
|
|
117
|
+
class MapFile:
|
|
118
|
+
"""A map file's maps and page settings. ``layout`` and ``review`` are ``None`` when the file leaves them out."""
|
|
119
|
+
|
|
120
|
+
title: str | None
|
|
121
|
+
maps: list[SheetMap]
|
|
122
|
+
layout: Layout | None = None
|
|
123
|
+
review: bool | None = None
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
_PAGE_KEYS = {"layout", "review"}
|
|
127
|
+
_LAYOUT_KEYS = {"sections", "rows", "columns", "wrap", "fit", "cells"}
|
|
128
|
+
_FILE_KEYS = {"title", "maps"} | _PAGE_KEYS
|
|
129
|
+
_MAP_KEYS = {"workbook", "regions", "title", "subtitle", "key", "details", "scope", "preview"}
|
|
130
|
+
_REGION_KEYS = {"label", "ref", "kind", "columns", "rows", "colour"}
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def load_map_file(path: str | Path) -> MapFile:
|
|
134
|
+
"""Read a YAML map file. Workbook paths resolve relative to the file.
|
|
135
|
+
|
|
136
|
+
The file holds either one map at the top level, or ``maps:`` with a list of them and an optional
|
|
137
|
+
page ``title``. Either form can set ``layout`` and ``review`` for the page.
|
|
138
|
+
"""
|
|
139
|
+
path = Path(path)
|
|
140
|
+
try:
|
|
141
|
+
data = yaml.safe_load(path.read_text(encoding="utf-8"))
|
|
142
|
+
except yaml.YAMLError as error:
|
|
143
|
+
raise SheetmapError(f"{path}: {error}") from error
|
|
144
|
+
if not isinstance(data, dict):
|
|
145
|
+
raise SheetmapError(f"{path}: expected a mapping at the top level")
|
|
146
|
+
if "maps" in data:
|
|
147
|
+
_known(data, _FILE_KEYS, path)
|
|
148
|
+
entries = data["maps"]
|
|
149
|
+
if not isinstance(entries, list) or not entries:
|
|
150
|
+
raise SheetmapError(f"{path}: maps must be a non-empty list")
|
|
151
|
+
page = data
|
|
152
|
+
else:
|
|
153
|
+
_known(data, _MAP_KEYS | _PAGE_KEYS, path)
|
|
154
|
+
page = {key: data[key] for key in _PAGE_KEYS if key in data}
|
|
155
|
+
entries = [{key: value for key, value in data.items() if key not in _PAGE_KEYS}]
|
|
156
|
+
if page.get("review") not in (None, True, False):
|
|
157
|
+
raise SheetmapError(f"{path}: review must be true or false")
|
|
158
|
+
maps = [_map_from(entry, path) for entry in entries]
|
|
159
|
+
for sheet_map in maps:
|
|
160
|
+
validate(sheet_map)
|
|
161
|
+
layout = _layout_from(page["layout"], path) if "layout" in page else None
|
|
162
|
+
return MapFile(page.get("title"), maps, layout, page.get("review"))
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _layout_from(data: Any, path: Path) -> Layout:
|
|
166
|
+
if not isinstance(data, dict):
|
|
167
|
+
raise SheetmapError(f"{path}: layout must be a mapping")
|
|
168
|
+
_known(data, _LAYOUT_KEYS, path)
|
|
169
|
+
if "wrap" in data and not isinstance(data["wrap"], int):
|
|
170
|
+
raise SheetmapError(f"{path}: layout wrap must be a whole number")
|
|
171
|
+
if "fit" in data and not isinstance(data["fit"], bool):
|
|
172
|
+
raise SheetmapError(f"{path}: layout fit must be true or false")
|
|
173
|
+
cells = data.get("cells")
|
|
174
|
+
if cells is not None:
|
|
175
|
+
if not isinstance(cells, list) or not all(isinstance(row, list) for row in cells):
|
|
176
|
+
raise SheetmapError(f"{path}: layout cells must be a list of rows")
|
|
177
|
+
cells = [[None if cell is None else str(cell) for cell in row] for row in cells]
|
|
178
|
+
layout = Layout(
|
|
179
|
+
sections=str(data.get("sections", "auto")),
|
|
180
|
+
rows=data.get("rows"),
|
|
181
|
+
columns=data.get("columns"),
|
|
182
|
+
wrap=data.get("wrap"),
|
|
183
|
+
fit=data.get("fit", False),
|
|
184
|
+
cells=cells,
|
|
185
|
+
)
|
|
186
|
+
try:
|
|
187
|
+
check_layout(layout)
|
|
188
|
+
except SheetmapError as error:
|
|
189
|
+
raise SheetmapError(f"{path}: {error}") from error
|
|
190
|
+
return layout
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _map_from(entry: Any, path: Path) -> SheetMap:
|
|
194
|
+
if not isinstance(entry, dict):
|
|
195
|
+
raise SheetmapError(f"{path}: each map must be a mapping")
|
|
196
|
+
_known(entry, _MAP_KEYS, path)
|
|
197
|
+
for required in ("workbook", "regions"):
|
|
198
|
+
if required not in entry:
|
|
199
|
+
raise SheetmapError(f"{path}: a map is missing {required!r}")
|
|
200
|
+
if not isinstance(entry["regions"], list):
|
|
201
|
+
raise SheetmapError(f"{path}: regions must be a list")
|
|
202
|
+
regions = []
|
|
203
|
+
for item in entry["regions"]:
|
|
204
|
+
if not isinstance(item, dict):
|
|
205
|
+
raise SheetmapError(f"{path}: each region must be a mapping")
|
|
206
|
+
_known(item, _REGION_KEYS, path)
|
|
207
|
+
if "label" not in item or "ref" not in item:
|
|
208
|
+
raise SheetmapError(f"{path}: each region needs a label and a ref")
|
|
209
|
+
regions.append(
|
|
210
|
+
Region(
|
|
211
|
+
label=str(item["label"]),
|
|
212
|
+
ref=str(item["ref"]),
|
|
213
|
+
kind=item.get("kind"),
|
|
214
|
+
columns=_labels(item.get("columns"), path),
|
|
215
|
+
rows=_labels(item.get("rows"), path),
|
|
216
|
+
colour=item.get("colour"),
|
|
217
|
+
)
|
|
218
|
+
)
|
|
219
|
+
preview = {}
|
|
220
|
+
for sheet, limits in (entry.get("preview") or {}).items():
|
|
221
|
+
if not isinstance(limits, dict) or set(limits) - {"rows", "columns"}:
|
|
222
|
+
raise SheetmapError(f"{path}: preview for {sheet!r} takes rows and columns")
|
|
223
|
+
preview[str(sheet)] = Preview(int(limits.get("rows", 40)), int(limits.get("columns", 20)))
|
|
224
|
+
return SheetMap(
|
|
225
|
+
workbook=path.parent / entry["workbook"],
|
|
226
|
+
regions=regions,
|
|
227
|
+
title=entry.get("title"),
|
|
228
|
+
subtitle=entry.get("subtitle"),
|
|
229
|
+
key=entry.get("key"),
|
|
230
|
+
details={str(name): str(value) for name, value in (entry.get("details") or {}).items()},
|
|
231
|
+
scope=entry.get("scope"),
|
|
232
|
+
preview=preview,
|
|
233
|
+
)
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def _labels(value: Any, path: Path) -> dict[str, str] | None:
|
|
237
|
+
if value is None:
|
|
238
|
+
return None
|
|
239
|
+
if not isinstance(value, dict):
|
|
240
|
+
raise SheetmapError(f"{path}: columns and rows must map a column letter or row number to a label")
|
|
241
|
+
return {str(key).upper(): str(label) for key, label in value.items()}
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def _known(data: dict, allowed: set[str], path: Path) -> None:
|
|
245
|
+
if unknown := set(data) - allowed:
|
|
246
|
+
raise SheetmapError(f"{path}: unknown setting {', '.join(sorted(map(str, unknown)))}")
|