figurekit 0.5.1__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.
- figkit/__init__.py +141 -0
- figkit/access.py +144 -0
- figkit/check.py +227 -0
- figkit/cli.py +180 -0
- figkit/export.py +366 -0
- figkit/fonts/BricolageGrotesque-Regular.ttf +0 -0
- figkit/fonts/BricolageGrotesque-SemiBold.ttf +0 -0
- figkit/fonts/JetBrainsMono-Regular.ttf +0 -0
- figkit/fonts/JetBrainsMono-SemiBold.ttf +0 -0
- figkit/fonts/OFL-BricolageGrotesque.txt +93 -0
- figkit/fonts/OFL-JetBrainsMono.txt +93 -0
- figkit/helpers.py +404 -0
- figkit/language.py +126 -0
- figkit/manifest.py +188 -0
- figkit/preview.py +103 -0
- figkit/project.py +173 -0
- figkit/py.typed +0 -0
- figkit/theme.py +524 -0
- figkit/tokens.json +52 -0
- figkit/tokens.schema.json +95 -0
- figurekit-0.5.1.dist-info/METADATA +439 -0
- figurekit-0.5.1.dist-info/RECORD +27 -0
- figurekit-0.5.1.dist-info/WHEEL +4 -0
- figurekit-0.5.1.dist-info/entry_points.txt +2 -0
- figurekit-0.5.1.dist-info/licenses/LICENSE +21 -0
- figurekit-0.5.1.dist-info/licenses/src/figkit/fonts/OFL-BricolageGrotesque.txt +93 -0
- figurekit-0.5.1.dist-info/licenses/src/figkit/fonts/OFL-JetBrainsMono.txt +93 -0
figkit/manifest.py
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
"""Figures for a website: headless files per language and a ``figures.json`` that describes them.
|
|
2
|
+
|
|
3
|
+
A page shows the title and caption of a figure as text, in its own type and language, and needs
|
|
4
|
+
an alt text for each image. :func:`page` writes the figure without its title once per language,
|
|
5
|
+
and :func:`write` lists those files with their texts and sizes, so the website reads everything
|
|
6
|
+
from one file instead of copying texts out of a README::
|
|
7
|
+
|
|
8
|
+
entries = [figkit.page(out, "f1", draw, {"en": Caption(...), "de": Caption(...)})]
|
|
9
|
+
figkit.write_manifest(out, entries)
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import json
|
|
13
|
+
import re
|
|
14
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
15
|
+
from dataclasses import dataclass
|
|
16
|
+
from functools import partial
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
from typing import Any
|
|
19
|
+
|
|
20
|
+
from matplotlib.figure import Figure
|
|
21
|
+
from PIL import Image
|
|
22
|
+
|
|
23
|
+
from figkit.export import SVG, Output, path_for, render
|
|
24
|
+
from figkit.theme import DEFAULT, Style, Theme
|
|
25
|
+
|
|
26
|
+
FILE = "figures.json"
|
|
27
|
+
VERSION = 1
|
|
28
|
+
|
|
29
|
+
PageDraw = Callable[[str, Theme], Figure]
|
|
30
|
+
|
|
31
|
+
_SVG_SIZE = re.compile(r'<svg[^>]* width="([\d.]+)pt" height="([\d.]+)pt"')
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass(frozen=True, slots=True)
|
|
35
|
+
class Caption:
|
|
36
|
+
"""Texts of a figure in one language.
|
|
37
|
+
|
|
38
|
+
Attributes:
|
|
39
|
+
title: Headline the page shows above the figure.
|
|
40
|
+
alt: Alt text, what a reader who cannot see the image needs to know: the finding and the
|
|
41
|
+
key numbers.
|
|
42
|
+
subtitle: Line below the title, such as the data and the method.
|
|
43
|
+
"""
|
|
44
|
+
|
|
45
|
+
title: str
|
|
46
|
+
alt: str
|
|
47
|
+
subtitle: str | None = None
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def size(path: Path, output: Output = SVG) -> tuple[float, float]:
|
|
51
|
+
"""Width and height of a figure file in points, read from the file.
|
|
52
|
+
|
|
53
|
+
An SVG states its size. A raster image has only pixels, so ``output``, the output that wrote
|
|
54
|
+
it, gives the resolution: its ``dpi``, or with ``pixels`` the fixed canvas ``width``.
|
|
55
|
+
|
|
56
|
+
Raises:
|
|
57
|
+
ValueError: If the SVG has no size in pt, or a raster output sets ``pixels`` without a
|
|
58
|
+
fixed canvas, which leaves the resolution unknown.
|
|
59
|
+
"""
|
|
60
|
+
if path.suffix == ".svg":
|
|
61
|
+
match = _SVG_SIZE.search(path.read_text(encoding="utf-8"))
|
|
62
|
+
if match is None:
|
|
63
|
+
msg = f"{path.name}: no width and height in pt"
|
|
64
|
+
raise ValueError(msg)
|
|
65
|
+
return float(match.group(1)), float(match.group(2))
|
|
66
|
+
with Image.open(path) as image:
|
|
67
|
+
width, height = image.size
|
|
68
|
+
if output.pixels is None:
|
|
69
|
+
dpi = output.dpi
|
|
70
|
+
elif output.width is not None and output.tight:
|
|
71
|
+
dpi = width / output.width
|
|
72
|
+
else:
|
|
73
|
+
msg = f"{path.name}: pixels without a fixed canvas width leave the size unknown"
|
|
74
|
+
raise ValueError(msg)
|
|
75
|
+
return width * 72 / dpi, height * 72 / dpi
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def page(
|
|
79
|
+
directory: Path,
|
|
80
|
+
name: str,
|
|
81
|
+
draw: PageDraw,
|
|
82
|
+
captions: Mapping[str, Caption],
|
|
83
|
+
outputs: Sequence[Output] = (SVG,),
|
|
84
|
+
style: Style | None = None,
|
|
85
|
+
) -> dict[str, Any]:
|
|
86
|
+
"""Write ``name`` without its title in each language of ``captions`` and describe it.
|
|
87
|
+
|
|
88
|
+
``draw`` receives the language and the theme, once per theme of ``style``. The first output
|
|
89
|
+
is the one the page shows; for photographs pass :data:`figkit.PHOTO` and the page gets the
|
|
90
|
+
WebP.
|
|
91
|
+
|
|
92
|
+
Returns:
|
|
93
|
+
The entry of the figure for :func:`write`.
|
|
94
|
+
"""
|
|
95
|
+
for language in captions:
|
|
96
|
+
render(
|
|
97
|
+
directory,
|
|
98
|
+
name,
|
|
99
|
+
partial(draw, language),
|
|
100
|
+
outputs,
|
|
101
|
+
language=language,
|
|
102
|
+
headless=True,
|
|
103
|
+
style=style,
|
|
104
|
+
)
|
|
105
|
+
return entry(directory, name, captions, outputs[0], style)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def entry(
|
|
109
|
+
directory: Path,
|
|
110
|
+
name: str,
|
|
111
|
+
captions: Mapping[str, Caption],
|
|
112
|
+
output: Output = SVG,
|
|
113
|
+
style: Style | None = None,
|
|
114
|
+
) -> dict[str, Any]:
|
|
115
|
+
"""The entry of ``name`` for :func:`write`, from files that :func:`page` wrote earlier.
|
|
116
|
+
|
|
117
|
+
For a figure whose drawing needs more than the others, such as a trained model, so that a
|
|
118
|
+
separate step writes it: the manifest of all figures can still be written in one place. The
|
|
119
|
+
files of each language are listed under the names of the themes of ``style``, ``light`` and
|
|
120
|
+
``dark`` in the bundled one; the size is that of the default theme.
|
|
121
|
+
|
|
122
|
+
Raises:
|
|
123
|
+
FileNotFoundError: If a file of a language in ``captions`` is missing.
|
|
124
|
+
"""
|
|
125
|
+
style = style or DEFAULT
|
|
126
|
+
files: dict[str, dict[str, Any]] = {}
|
|
127
|
+
for language in captions:
|
|
128
|
+
paths = {
|
|
129
|
+
theme.name: path_for(directory, name, theme, output, language, style)
|
|
130
|
+
for theme in style.themes
|
|
131
|
+
}
|
|
132
|
+
for path in paths.values():
|
|
133
|
+
if not path.is_file():
|
|
134
|
+
msg = f"{path.name} is missing; write the figure with page() first"
|
|
135
|
+
raise FileNotFoundError(msg)
|
|
136
|
+
width, height = size(paths[style.default], output)
|
|
137
|
+
files[language] = {
|
|
138
|
+
**{theme: path.name for theme, path in paths.items()},
|
|
139
|
+
"width": round(width, 1),
|
|
140
|
+
"height": round(height, 1),
|
|
141
|
+
}
|
|
142
|
+
return {
|
|
143
|
+
"name": name,
|
|
144
|
+
"title": {code: c.title for code, c in captions.items()},
|
|
145
|
+
"subtitle": {code: c.subtitle for code, c in captions.items() if c.subtitle},
|
|
146
|
+
"alt": {code: c.alt for code, c in captions.items()},
|
|
147
|
+
"files": files,
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def write(directory: Path, entries: Sequence[Mapping[str, Any]]) -> Path:
|
|
152
|
+
"""Write ``figures.json`` with the entries of :func:`page`, in their order.
|
|
153
|
+
|
|
154
|
+
Raises:
|
|
155
|
+
ValueError: If the entries differ in their languages or a name occurs twice.
|
|
156
|
+
"""
|
|
157
|
+
names = [entry["name"] for entry in entries]
|
|
158
|
+
if len(set(names)) != len(names):
|
|
159
|
+
msg = f"figure names occur twice: {sorted({n for n in names if names.count(n) > 1})}"
|
|
160
|
+
raise ValueError(msg)
|
|
161
|
+
languages = sorted({code for entry in entries for code in entry["files"]})
|
|
162
|
+
for entry in entries:
|
|
163
|
+
if sorted(entry["files"]) != languages:
|
|
164
|
+
msg = f"figure {entry['name']!r} is not in every language of {languages}"
|
|
165
|
+
raise ValueError(msg)
|
|
166
|
+
manifest = {"version": VERSION, "languages": languages, "figures": list(entries)}
|
|
167
|
+
path = directory / FILE
|
|
168
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
169
|
+
# Bytes, so the file ends lines with LF on every platform.
|
|
170
|
+
text = json.dumps(manifest, indent=2, ensure_ascii=False) + "\n"
|
|
171
|
+
path.write_bytes(text.encode("utf-8"))
|
|
172
|
+
return path
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def load(directory: Path) -> object:
|
|
176
|
+
"""The parsed manifest of ``directory``, or ``None`` if it has none.
|
|
177
|
+
|
|
178
|
+
The file may be edited by hand, so the result is any JSON value; :mod:`figkit.check` checks
|
|
179
|
+
its structure.
|
|
180
|
+
|
|
181
|
+
Raises:
|
|
182
|
+
ValueError: If the file is not valid JSON.
|
|
183
|
+
"""
|
|
184
|
+
path = directory / FILE
|
|
185
|
+
if not path.is_file():
|
|
186
|
+
return None
|
|
187
|
+
data: object = json.loads(path.read_text(encoding="utf-8"))
|
|
188
|
+
return data
|
figkit/preview.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
"""A specimen figure that shows every token of a style, for ``figkit style preview``.
|
|
2
|
+
|
|
3
|
+
The specimen draws all series colours as lines with direct labels and a reference line, the
|
|
4
|
+
sequential ramp as a strip of cells and the status colours as bars, with a title, a subtitle,
|
|
5
|
+
axis labels and tick labels in the fonts and sizes of the style. :func:`preview` renders it in
|
|
6
|
+
every theme, so a new tokens file can be judged before the first real figure uses it.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from collections.abc import Sequence
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
import matplotlib.pyplot as plt
|
|
13
|
+
import numpy as np
|
|
14
|
+
from matplotlib.colors import ListedColormap
|
|
15
|
+
from matplotlib.figure import Figure
|
|
16
|
+
|
|
17
|
+
from figkit.export import WEB, WEB_WIDTH, Output, render
|
|
18
|
+
from figkit.helpers import (
|
|
19
|
+
category_axis,
|
|
20
|
+
grid,
|
|
21
|
+
ink_on,
|
|
22
|
+
line_labels,
|
|
23
|
+
reference_line,
|
|
24
|
+
title,
|
|
25
|
+
value,
|
|
26
|
+
)
|
|
27
|
+
from figkit.theme import DEFAULT, Style, Theme
|
|
28
|
+
|
|
29
|
+
NAME = "style"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def specimen(theme: Theme, style: Style | None = None) -> Figure:
|
|
33
|
+
"""The specimen in ``theme``; ``style`` picks the dark ink of text on ramp cells."""
|
|
34
|
+
figure = plt.figure(figsize=(WEB_WIDTH, 5.4))
|
|
35
|
+
rows = figure.add_gridspec(2, 2, height_ratios=(2.3, 1), hspace=0.75, wspace=0.45)
|
|
36
|
+
lines = figure.add_subplot(rows[0, :])
|
|
37
|
+
ramp = figure.add_subplot(rows[1, 0])
|
|
38
|
+
status = figure.add_subplot(rows[1, 1])
|
|
39
|
+
|
|
40
|
+
steps = np.arange(0, 11)
|
|
41
|
+
ends = []
|
|
42
|
+
for slot, colour in enumerate(theme.series):
|
|
43
|
+
level = 0.9 - 0.7 * slot / max(len(theme.series), 2)
|
|
44
|
+
curve = level - (level - 0.05) * np.exp(-steps / (2.0 + slot))
|
|
45
|
+
lines.plot(steps, curve, color=colour)
|
|
46
|
+
ends.append((10.0, float(curve[-1]), f"series {slot + 1} {colour}"))
|
|
47
|
+
reference_line(lines, 0.5, "reference", theme, axis="y", where=0.02)
|
|
48
|
+
title(lines, f"Style preview, {theme.name}", theme, subtitle="Series in their fixed order")
|
|
49
|
+
grid(lines, "y")
|
|
50
|
+
lines.set_xlim(0, 10)
|
|
51
|
+
lines.set_ylim(0, 1)
|
|
52
|
+
lines.set_xlabel("step")
|
|
53
|
+
line_labels(lines, ends, theme)
|
|
54
|
+
|
|
55
|
+
cells = np.linspace(0, 1, len(theme.ramp))[np.newaxis, :]
|
|
56
|
+
ramp.imshow(
|
|
57
|
+
cells,
|
|
58
|
+
cmap=ListedColormap(list(theme.ramp), name=f"ramp-{theme.name}"),
|
|
59
|
+
vmin=0,
|
|
60
|
+
vmax=1,
|
|
61
|
+
aspect="auto",
|
|
62
|
+
)
|
|
63
|
+
for index, colour in enumerate(theme.ramp):
|
|
64
|
+
value(
|
|
65
|
+
ramp,
|
|
66
|
+
index,
|
|
67
|
+
0,
|
|
68
|
+
str(index + 1),
|
|
69
|
+
theme,
|
|
70
|
+
ha="center",
|
|
71
|
+
va="center",
|
|
72
|
+
color=ink_on(colour, style),
|
|
73
|
+
)
|
|
74
|
+
ramp.set_xticks([])
|
|
75
|
+
ramp.set_yticks([])
|
|
76
|
+
for spine in ramp.spines.values():
|
|
77
|
+
spine.set_visible(False)
|
|
78
|
+
ramp.set_title("Ramp")
|
|
79
|
+
|
|
80
|
+
names = list(theme.status)
|
|
81
|
+
positions = np.arange(len(names))
|
|
82
|
+
status.barh(positions, [1] * len(names), height=0.6, color=[theme.status[n] for n in names])
|
|
83
|
+
status.set_yticks(positions, names)
|
|
84
|
+
status.invert_yaxis()
|
|
85
|
+
status.set_xticks([])
|
|
86
|
+
status.spines["bottom"].set_visible(False)
|
|
87
|
+
category_axis(status, "y")
|
|
88
|
+
status.set_title("Status")
|
|
89
|
+
return figure
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def preview(
|
|
93
|
+
directory: Path, style: Style | None = None, outputs: Sequence[Output] = WEB
|
|
94
|
+
) -> list[Path]:
|
|
95
|
+
"""Render the specimen in every theme of ``style`` to ``directory`` as ``style*.svg|png``.
|
|
96
|
+
|
|
97
|
+
Raises:
|
|
98
|
+
ValueError: If the specimen does not fit the canvas or has text below the minimum size
|
|
99
|
+
of the style, such as tick labels smaller than ``font.minimum``.
|
|
100
|
+
"""
|
|
101
|
+
style = style or DEFAULT
|
|
102
|
+
directory.mkdir(parents=True, exist_ok=True)
|
|
103
|
+
return render(directory, NAME, lambda theme: specimen(theme, style), outputs, style=style)
|
figkit/project.py
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
"""Settings of a project in the ``[tool.figkit]`` table of its ``pyproject.toml``.
|
|
2
|
+
|
|
3
|
+
A project with its own style names its tokens there once, and both its figure scripts and
|
|
4
|
+
``figkit check`` use them::
|
|
5
|
+
|
|
6
|
+
[tool.figkit]
|
|
7
|
+
tokens = "figures/tokens.json" # style, relative to pyproject.toml
|
|
8
|
+
css = "../Website/src/tokens.css" # stylesheet that figkit check compares
|
|
9
|
+
|
|
10
|
+
Without the table, or without a ``pyproject.toml``, the bundled style applies.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
import json
|
|
14
|
+
import shutil
|
|
15
|
+
import tomllib
|
|
16
|
+
from dataclasses import dataclass
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
|
|
19
|
+
from figkit.theme import DEFAULT, SCHEMA, Style, StyleError, load_style, tokens
|
|
20
|
+
|
|
21
|
+
FILE = "pyproject.toml"
|
|
22
|
+
_KEYS = ("tokens", "css")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True, slots=True)
|
|
26
|
+
class Project:
|
|
27
|
+
"""The figkit settings of a project.
|
|
28
|
+
|
|
29
|
+
Attributes:
|
|
30
|
+
tokens: Tokens file of the project's style, ``None`` for the bundled style.
|
|
31
|
+
css: Stylesheet whose colours ``figkit check`` compares with the style, or ``None``.
|
|
32
|
+
config: The ``pyproject.toml`` the settings came from, ``None`` without one.
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
tokens: Path | None = None
|
|
36
|
+
css: Path | None = None
|
|
37
|
+
config: Path | None = None
|
|
38
|
+
|
|
39
|
+
def style(self) -> Style:
|
|
40
|
+
"""The style of ``tokens``, or the bundled style without them.
|
|
41
|
+
|
|
42
|
+
Raises:
|
|
43
|
+
StyleError: If the tokens are not a valid style.
|
|
44
|
+
OSError: If the tokens file cannot be read.
|
|
45
|
+
"""
|
|
46
|
+
return DEFAULT if self.tokens is None else load_style(self.tokens)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def find(start: Path | None = None) -> Path | None:
|
|
50
|
+
"""The nearest ``pyproject.toml`` in ``start`` or one of its parents, ``None`` without one."""
|
|
51
|
+
folder = (start or Path.cwd()).resolve()
|
|
52
|
+
for candidate in (folder, *folder.parents):
|
|
53
|
+
if (candidate / FILE).is_file():
|
|
54
|
+
return candidate / FILE
|
|
55
|
+
return None
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def project(start: Path | None = None) -> Project:
|
|
59
|
+
"""Settings of the project that contains ``start``, by default the working directory.
|
|
60
|
+
|
|
61
|
+
Paths in the table are relative to the ``pyproject.toml`` that holds them. The style is read
|
|
62
|
+
only by :meth:`Project.style`, so that a broken tokens file can be overridden.
|
|
63
|
+
|
|
64
|
+
Raises:
|
|
65
|
+
StyleError: If the file is not TOML or the table has unknown keys or values that are not
|
|
66
|
+
paths.
|
|
67
|
+
OSError: If the ``pyproject.toml`` cannot be read.
|
|
68
|
+
"""
|
|
69
|
+
config = find(start)
|
|
70
|
+
if config is None:
|
|
71
|
+
return Project()
|
|
72
|
+
try:
|
|
73
|
+
data = tomllib.loads(config.read_text(encoding="utf-8"))
|
|
74
|
+
except tomllib.TOMLDecodeError as error:
|
|
75
|
+
raise StyleError(str(config), [f"not TOML: {error}"]) from error
|
|
76
|
+
table = data.get("tool", {}).get("figkit")
|
|
77
|
+
if table is None:
|
|
78
|
+
return Project(config=config)
|
|
79
|
+
if not isinstance(table, dict):
|
|
80
|
+
raise StyleError(str(config), ["tool.figkit: must be a table"])
|
|
81
|
+
problems = [f"tool.figkit.{key}: unknown key" for key in table if key not in _KEYS]
|
|
82
|
+
problems += [
|
|
83
|
+
f"tool.figkit.{key}: must be a path"
|
|
84
|
+
for key in _KEYS
|
|
85
|
+
if key in table and (not isinstance(table[key], str) or not table[key])
|
|
86
|
+
]
|
|
87
|
+
if problems:
|
|
88
|
+
raise StyleError(str(config), problems)
|
|
89
|
+
base = config.parent
|
|
90
|
+
tokens = base / table["tokens"] if "tokens" in table else None
|
|
91
|
+
css = base / table["css"] if "css" in table else None
|
|
92
|
+
return Project(tokens, css, config)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def project_style(start: Path | None = None) -> Style:
|
|
96
|
+
"""Style of the project that contains ``start``, see :func:`project`.
|
|
97
|
+
|
|
98
|
+
Raises:
|
|
99
|
+
StyleError: If the settings or the tokens are not valid.
|
|
100
|
+
OSError: If a file cannot be read.
|
|
101
|
+
"""
|
|
102
|
+
return project(start).style()
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def init(root: Path, tokens_file: Path, css: Path | None = None) -> list[Path]:
|
|
106
|
+
"""Give the project in ``root`` a style of its own and name it in ``[tool.figkit]``.
|
|
107
|
+
|
|
108
|
+
Writes a copy of the bundled tokens to ``tokens_file`` with the schema next to it, unless
|
|
109
|
+
the file exists; an existing file is kept and only checked. Then appends the table to the
|
|
110
|
+
``pyproject.toml`` of ``root``. Relative paths are relative to ``root``.
|
|
111
|
+
|
|
112
|
+
Returns:
|
|
113
|
+
The files written or changed, the ``pyproject.toml`` last.
|
|
114
|
+
|
|
115
|
+
Raises:
|
|
116
|
+
FileNotFoundError: If ``root`` has no ``pyproject.toml``.
|
|
117
|
+
FileExistsError: If the project already has a ``[tool.figkit]`` table.
|
|
118
|
+
StyleError: If the ``pyproject.toml`` is not TOML or an existing tokens file is not a
|
|
119
|
+
valid style.
|
|
120
|
+
OSError: If a file cannot be read or written.
|
|
121
|
+
"""
|
|
122
|
+
config = root / FILE
|
|
123
|
+
if not config.is_file():
|
|
124
|
+
msg = f"{config}: not found; init needs the pyproject.toml of a project"
|
|
125
|
+
raise FileNotFoundError(msg)
|
|
126
|
+
text = config.read_text(encoding="utf-8")
|
|
127
|
+
try:
|
|
128
|
+
data = tomllib.loads(text)
|
|
129
|
+
except tomllib.TOMLDecodeError as error:
|
|
130
|
+
raise StyleError(str(config), [f"not TOML: {error}"]) from error
|
|
131
|
+
if "figkit" in data.get("tool", {}):
|
|
132
|
+
msg = f"{config}: [tool.figkit] exists already; init leaves it as it is"
|
|
133
|
+
raise FileExistsError(msg)
|
|
134
|
+
|
|
135
|
+
target = tokens_file if tokens_file.is_absolute() else root / tokens_file
|
|
136
|
+
written: list[Path] = []
|
|
137
|
+
if target.exists():
|
|
138
|
+
load_style(target)
|
|
139
|
+
else:
|
|
140
|
+
template = tokens()
|
|
141
|
+
template["$schema"] = f"./{SCHEMA.name}"
|
|
142
|
+
template["$comment"] = (
|
|
143
|
+
"Colours and type of the figures of this project, a copy of the figkit style. "
|
|
144
|
+
"Preview them with `figkit style preview`."
|
|
145
|
+
)
|
|
146
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
147
|
+
target.write_text(json.dumps(template, indent=2) + "\n", encoding="utf-8", newline="\n")
|
|
148
|
+
written.append(target)
|
|
149
|
+
schema = target.parent / SCHEMA.name
|
|
150
|
+
if not schema.exists():
|
|
151
|
+
shutil.copyfile(SCHEMA, schema)
|
|
152
|
+
written.append(schema)
|
|
153
|
+
|
|
154
|
+
table = ["[tool.figkit]", f"tokens = {_toml_path(target, root)}"]
|
|
155
|
+
if css is not None:
|
|
156
|
+
table.append(f"css = {_toml_path(css if css.is_absolute() else root / css, root)}")
|
|
157
|
+
# The table keeps the line ends of the file, so that Git shows only the added lines.
|
|
158
|
+
raw = config.read_bytes()
|
|
159
|
+
end = "\r\n" if b"\r\n" in raw else "\n"
|
|
160
|
+
lead = "" if not raw else (end if raw.endswith(b"\n") else end * 2)
|
|
161
|
+
with config.open("a", encoding="utf-8", newline="") as file:
|
|
162
|
+
file.write(lead + end.join(table) + end)
|
|
163
|
+
written.append(config)
|
|
164
|
+
return written
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _toml_path(path: Path, root: Path) -> str:
|
|
168
|
+
"""``path`` relative to ``root`` where it can be, with forward slashes, as a TOML string."""
|
|
169
|
+
try:
|
|
170
|
+
relative = path.relative_to(root).as_posix()
|
|
171
|
+
except ValueError:
|
|
172
|
+
relative = path.as_posix()
|
|
173
|
+
return json.dumps(relative) # A JSON string of a path is a valid TOML basic string.
|
figkit/py.typed
ADDED
|
File without changes
|