zoetty 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.
zoetty/__init__.py ADDED
File without changes
zoetty/ansi.py ADDED
@@ -0,0 +1,70 @@
1
+ """Turn captured terminal output, with its ANSI colour codes, into zoetty markup."""
2
+
3
+ import re
4
+
5
+ from zoetty.markup import escape
6
+
7
+ _OSC = re.compile(r"\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)")
8
+ _CSI = re.compile(r"\x1b\[([0-9;?]*)([A-Za-z])")
9
+ _COLOURS = {1: "red", 2: "green", 3: "yellow", 4: "blue", 5: "magenta", 6: "cyan"}
10
+ _ATTRIBUTES = {1: "bold", 2: "dim", 3: "italic"}
11
+
12
+
13
+ class _Pen:
14
+ """The current text style, changed by SGR codes."""
15
+
16
+ def __init__(self) -> None:
17
+ self.reset()
18
+
19
+ def reset(self) -> None:
20
+ self.bold = self.dim = self.italic = False
21
+ self.colour: str | None = None
22
+
23
+ def apply(self, codes: list[int]) -> None:
24
+ index = 0
25
+ while index < len(codes):
26
+ code = codes[index]
27
+ if code == 0:
28
+ self.reset()
29
+ elif code in _ATTRIBUTES:
30
+ setattr(self, _ATTRIBUTES[code], True)
31
+ elif code == 22:
32
+ self.bold = self.dim = False
33
+ elif code == 23:
34
+ self.italic = False
35
+ elif 31 <= code <= 36 or 91 <= code <= 96:
36
+ self.colour = _COLOURS[code % 10]
37
+ elif code in (30, 37, 39, 90, 97):
38
+ self.colour = None
39
+ elif code in (38, 48):
40
+ # 256-colour (5;n) and truecolour (2;r;g;b) arguments aren't codes of their own.
41
+ index += 2 if codes[index + 1 : index + 2] == [5] else 4
42
+ index += 1
43
+
44
+ def write(self, text: str) -> str:
45
+ styles = [name for name in ("bold", "dim", "italic") if getattr(self, name)]
46
+ if self.colour:
47
+ styles.append(self.colour)
48
+ text = escape(text)
49
+ return f"[{' '.join(styles)}]{text}[/]" if styles and text.strip() else text
50
+
51
+
52
+ def to_markup(raw: str) -> list[str]:
53
+ """One markup line per line of output, keeping colours and dropping everything else."""
54
+ raw = _OSC.sub("", raw).replace("\r\n", "\n")
55
+ lines = []
56
+ for line in raw.split("\n"):
57
+ # A carriage return moves back to the start: what's left on screen is the last thing written.
58
+ line = line.split("\r")[-1]
59
+ pen = _Pen()
60
+ markup, position = "", 0
61
+ for match in _CSI.finditer(line):
62
+ markup += pen.write(line[position : match.start()])
63
+ position = match.end()
64
+ if match.group(2) == "m":
65
+ pen.apply([int(code) for code in match.group(1).split(";") if code] or [0])
66
+ markup += pen.write(line[position:])
67
+ lines.append(markup.rstrip())
68
+ while lines and not lines[-1]:
69
+ lines.pop()
70
+ return lines
zoetty/cli.py ADDED
@@ -0,0 +1,173 @@
1
+ from pathlib import Path
2
+
3
+ import click
4
+ from rich.console import Console
5
+ from rich.markup import escape
6
+
7
+ from zoetty import clip as clips
8
+ from zoetty import html, record, svg, timeline
9
+ from zoetty.settings import VERSION
10
+
11
+ STARTER = """# A zoetty clip. Build it with: zoetty build {path}
12
+ # Every key is described at https://phalt.github.io/zoetty/clip-format/
13
+ title = "~/my-project"
14
+ label = "Saying hello in a terminal"
15
+ cols = 60
16
+
17
+ [[run]]
18
+ cmd = "echo 'Hello from zoetty!'"
19
+ lines = ["Hello from zoetty!"]
20
+
21
+ [[run]]
22
+ cmd = "ls"
23
+ lines = ["[blue]docs[/] README.md [green]tool.py[/]"]
24
+
25
+ # Record real output instead of writing it by hand:
26
+ # give a run an `output` file, then run `zoetty record {path}`.
27
+ #
28
+ # [[run]]
29
+ # cmd = "git log --oneline -3"
30
+ # output = "captures/git-log.ansi"
31
+ """
32
+
33
+
34
+ def _console() -> Console:
35
+ return Console(highlight=False, soft_wrap=True)
36
+
37
+
38
+ def _load(console: Console, path: Path) -> clips.Clip | None:
39
+ try:
40
+ return clips.load(path)
41
+ except clips.ClipError as error:
42
+ console.print(f"[red]✗ {escape(str(path))}[/]")
43
+ for problem in error.problems:
44
+ console.print(f" [red]•[/] {escape(problem)}")
45
+ return None
46
+
47
+
48
+ def _render(clip: clips.Clip) -> dict[Path, str]:
49
+ """What each of the clip's output files should contain. Raises MissingCapture."""
50
+ lines = timeline.build(clip)
51
+ return {
52
+ out: (svg.render if out.suffix == ".svg" else html.render)(clip, lines, timeline.name(out)) for out in clip.out
53
+ }
54
+
55
+
56
+ @click.group()
57
+ @click.version_option(VERSION, prog_name="zoetty")
58
+ def cli() -> None:
59
+ """⚜ zoetty: looping terminal clips as plain SVG or HTML and CSS."""
60
+
61
+
62
+ @cli.command()
63
+ @click.argument("spec", type=click.Path(dir_okay=False, path_type=Path))
64
+ def init(spec: Path) -> None:
65
+ """Write a starter clip spec to SPEC."""
66
+ console = _console()
67
+ if spec.exists():
68
+ raise click.ClickException(f"{spec} already exists")
69
+ spec.parent.mkdir(parents=True, exist_ok=True)
70
+ spec.write_text(STARTER.format(path=spec))
71
+ console.print(f"[green]✓[/] wrote {escape(str(spec))}")
72
+ console.print(f" next: [bold]zoetty build {escape(str(spec))}[/]")
73
+
74
+
75
+ @cli.command()
76
+ @click.argument("specs", nargs=-1, required=True, type=click.Path(dir_okay=False, path_type=Path))
77
+ def build(specs: tuple[Path, ...]) -> None:
78
+ """Render each clip spec to its output files."""
79
+ console = _console()
80
+ failed = False
81
+ for path in specs:
82
+ clip = _load(console, path)
83
+ if clip is None:
84
+ failed = True
85
+ continue
86
+ try:
87
+ outputs = _render(clip)
88
+ except timeline.MissingCapture as error:
89
+ console.print(f"[red]✗ {escape(str(path))}[/]: {escape(str(error))}")
90
+ failed = True
91
+ continue
92
+ for out, content in outputs.items():
93
+ out.parent.mkdir(parents=True, exist_ok=True)
94
+ out.write_text(content)
95
+ console.print(f"[green]✓[/] {escape(str(out))} [dim]({len(content.encode()) / 1024:.1f}KB)[/]")
96
+ if failed:
97
+ raise SystemExit(1)
98
+
99
+
100
+ @cli.command()
101
+ @click.argument("specs", nargs=-1, required=True, type=click.Path(dir_okay=False, path_type=Path))
102
+ def check(specs: tuple[Path, ...]) -> None:
103
+ """Fail if a clip spec is broken, or its output files are missing or out of date."""
104
+ console = _console()
105
+ failed = False
106
+ for path in specs:
107
+ clip = _load(console, path)
108
+ if clip is None:
109
+ failed = True
110
+ continue
111
+ try:
112
+ outputs = _render(clip)
113
+ except timeline.MissingCapture as error:
114
+ console.print(f"[red]✗ {escape(str(path))}[/]: {escape(str(error))}")
115
+ failed = True
116
+ continue
117
+ stale = [out for out, content in outputs.items() if not out.exists() or out.read_text() != content]
118
+ if stale:
119
+ failed = True
120
+ for out in stale:
121
+ why = "is out of date" if out.exists() else "doesn't exist"
122
+ console.print(f"[red]✗ {escape(str(out))}[/] {why}: run [bold]zoetty build {escape(str(path))}[/]")
123
+ else:
124
+ console.print(f"[green]✓[/] {escape(str(path))}")
125
+ if failed:
126
+ raise SystemExit(1)
127
+
128
+
129
+ @cli.command(name="record")
130
+ @click.argument("specs", nargs=-1, required=True, type=click.Path(dir_okay=False, path_type=Path))
131
+ def record_(specs: tuple[Path, ...]) -> None:
132
+ """Run each clip's commands for real and save their output."""
133
+ console = _console()
134
+ failed = False
135
+ for path in specs:
136
+ clip = _load(console, path)
137
+ if clip is None:
138
+ failed = True
139
+ continue
140
+ runs = [run for run in clip.runs if run.recordable]
141
+ if not runs:
142
+ console.print(f"[yellow]•[/] {escape(str(path))}: nothing to record (no run has an output file)")
143
+ continue
144
+ console.print(f"[bold]{escape(str(path))}[/]")
145
+ env = record.environment(clip)
146
+ try:
147
+ record.setup(clip, env)
148
+ except record.SetupFailed as error:
149
+ console.print(f" [red]✗ setup:[/] {escape(error.command)} exited {error.exit_code}")
150
+ console.print(escape(error.output.rstrip()), style="dim")
151
+ failed = True
152
+ continue
153
+ for run in runs:
154
+ assert run.output is not None
155
+ result = record.run(
156
+ run.command,
157
+ cwd=clip.record.cwd,
158
+ env=env,
159
+ cols=clip.cols,
160
+ rows=clip.rows or 24,
161
+ input=run.input,
162
+ timeout=clip.record.timeout,
163
+ )
164
+ if result.timed_out:
165
+ console.print(f" [red]✗ {escape(run.cmd)}[/] timed out after {clip.record.timeout:g}s")
166
+ failed = True
167
+ break
168
+ run.output.parent.mkdir(parents=True, exist_ok=True)
169
+ run.output.write_bytes(result.output)
170
+ mark = "[green]✓[/]" if result.exit_code == 0 else "[yellow]![/]"
171
+ console.print(f" {mark} {escape(run.cmd)} [dim]· exit {result.exit_code} → {escape(str(run.output))}[/]")
172
+ if failed:
173
+ raise SystemExit(1)
zoetty/clip.py ADDED
@@ -0,0 +1,272 @@
1
+ """Load and validate clip spec files (TOML)."""
2
+
3
+ import re
4
+ import tomllib
5
+ from dataclasses import dataclass, field
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ from zoetty.markup import COLOURS, MarkupError, parse
10
+
11
+ DEFAULT_PROMPT = "[dim]$[/] "
12
+
13
+ THEME = {
14
+ "bg": "#1c1c1c",
15
+ "fg": "#d0d0d0",
16
+ "bar": "#2a2a2a",
17
+ "blue": "#4b8fe3",
18
+ "green": "#2fcf7a",
19
+ "yellow": "#e6e04a",
20
+ "red": "#e05252",
21
+ "cyan": "#4fc6d6",
22
+ "magenta": "#c678dd",
23
+ }
24
+ assert set(THEME) == {"bg", "fg", "bar", *COLOURS}
25
+
26
+ FORMATS = (".svg", ".html")
27
+ _HEX = re.compile(r"#[0-9a-fA-F]{3}(?:[0-9a-fA-F]{3})?")
28
+
29
+
30
+ class ClipError(Exception):
31
+ """A spec file that can't be used, with every problem found in it."""
32
+
33
+ def __init__(self, path: Path, problems: list[str]) -> None:
34
+ self.path = path
35
+ self.problems = problems
36
+ super().__init__(f"{path}: " + "; ".join(problems))
37
+
38
+
39
+ @dataclass(frozen=True)
40
+ class Record:
41
+ """How `zoetty record` runs a clip's commands."""
42
+
43
+ cwd: Path
44
+ setup: list[str] = field(default_factory=list)
45
+ env: dict[str, str] = field(default_factory=dict)
46
+ timeout: float = 60
47
+
48
+
49
+ @dataclass(frozen=True)
50
+ class Run:
51
+ """A command typed at the prompt, and what it printed."""
52
+
53
+ cmd: str
54
+ exec: str | None = None
55
+ output: Path | None = None
56
+ lines: list[str] | None = None
57
+ input: str | None = None
58
+ record: bool = True
59
+ prompt: str | None = None
60
+ think: float = 0.5
61
+ pause: float = 0.9
62
+ line_gap: float | None = None
63
+
64
+ @property
65
+ def command(self) -> str:
66
+ """What `record` actually runs."""
67
+ return self.exec or self.cmd
68
+
69
+ @property
70
+ def recordable(self) -> bool:
71
+ return self.output is not None and self.record
72
+
73
+
74
+ @dataclass(frozen=True)
75
+ class Step:
76
+ """Lines that appear together at a set time, for clips that aren't command sessions."""
77
+
78
+ at: float
79
+ lines: list[str]
80
+ caret: bool = False
81
+
82
+
83
+ @dataclass(frozen=True)
84
+ class Clip:
85
+ path: Path
86
+ label: str
87
+ out: list[Path]
88
+ record: Record
89
+ theme: dict[str, str]
90
+ title: str = ""
91
+ cols: int = 80
92
+ rows: int | None = None
93
+ prompt: str = DEFAULT_PROMPT
94
+ final_prompt: str | None = None
95
+ typing_speed: float = 28
96
+ line_gap: float = 0.07
97
+ hold: float = 4.0
98
+ duration: float | None = None
99
+ chrome: bool = True
100
+ runs: list[Run] = field(default_factory=list)
101
+ steps: list[Step] = field(default_factory=list)
102
+
103
+
104
+ # Each key's type and check. `number` allows ints and floats, never bools.
105
+ _Kind = str
106
+ _TOP = {
107
+ "title": "str",
108
+ "label": "str",
109
+ "cols": "positive int",
110
+ "rows": "positive int",
111
+ "out": "list of str",
112
+ "prompt": "markup",
113
+ "final_prompt": "markup",
114
+ "typing_speed": "positive number",
115
+ "line_gap": "number",
116
+ "hold": "number",
117
+ "duration": "positive number",
118
+ "chrome": "bool",
119
+ "record": "table",
120
+ "theme": "table",
121
+ "run": "list of tables",
122
+ "step": "list of tables",
123
+ }
124
+ _RECORD = {"cwd": "str", "setup": "list of str", "env": "table of str", "timeout": "positive number"}
125
+ _RUN = {
126
+ "cmd": "str",
127
+ "exec": "str",
128
+ "output": "str",
129
+ "lines": "list of markup",
130
+ "input": "str",
131
+ "record": "bool",
132
+ "prompt": "markup",
133
+ "think": "number",
134
+ "pause": "number",
135
+ "line_gap": "number",
136
+ }
137
+ _STEP = {"at": "number", "lines": "list of markup", "caret": "bool"}
138
+
139
+
140
+ def _number(value: Any) -> bool:
141
+ return isinstance(value, int | float) and not isinstance(value, bool)
142
+
143
+
144
+ def _problem(kind: _Kind, value: Any) -> str | None:
145
+ """Why a value isn't of a kind, or None if it is."""
146
+ match kind:
147
+ case "str":
148
+ ok = isinstance(value, str)
149
+ case "bool":
150
+ ok = isinstance(value, bool)
151
+ case "positive int":
152
+ ok = isinstance(value, int) and not isinstance(value, bool) and value > 0
153
+ case "number":
154
+ ok = _number(value) and value >= 0
155
+ kind = "number, 0 or more"
156
+ case "positive number":
157
+ ok = _number(value) and value > 0
158
+ case "table":
159
+ ok = isinstance(value, dict)
160
+ case "table of str":
161
+ ok = isinstance(value, dict) and all(isinstance(item, str) for item in value.values())
162
+ case "list of tables":
163
+ ok = isinstance(value, list) and all(isinstance(item, dict) for item in value)
164
+ case "markup" | "list of markup" | "list of str":
165
+ items = [value] if kind == "markup" else value
166
+ ok = (kind == "markup" or isinstance(value, list)) and all(isinstance(item, str) for item in items)
167
+ if ok and kind != "list of str":
168
+ for item in items:
169
+ try:
170
+ parse(item)
171
+ except MarkupError as error:
172
+ return str(error)
173
+ case _: # pragma: no cover
174
+ raise AssertionError(kind)
175
+ return None if ok else f"should be a {kind}, got {value!r}"
176
+
177
+
178
+ def _check(table: dict[str, Any], keys: dict[str, _Kind], where: str, problems: list[str]) -> None:
179
+ for key, value in table.items():
180
+ if key not in keys:
181
+ problems.append(f"{where}unknown key {key!r}")
182
+ elif problem := _problem(keys[key], value):
183
+ problems.append(f"{where}{key} {problem}")
184
+
185
+
186
+ def load(path: Path) -> Clip:
187
+ """Read a spec file. Raises ClipError listing every problem in it."""
188
+ try:
189
+ data = tomllib.loads(path.read_text())
190
+ except OSError as error:
191
+ raise ClipError(path, [f"can't read it: {error.strerror}"]) from None
192
+ except tomllib.TOMLDecodeError as error:
193
+ raise ClipError(path, [f"isn't valid TOML: {error}"]) from None
194
+
195
+ problems: list[str] = []
196
+ _check(data, _TOP, "", problems)
197
+ if "label" not in data:
198
+ problems.append("label is required: it's the alt text people without the animation get")
199
+ record = data.get("record", {}) if isinstance(data.get("record"), dict) else {}
200
+ _check(record, _RECORD, "record.", problems)
201
+ theme = data.get("theme", {}) if isinstance(data.get("theme"), dict) else {}
202
+ for key, value in theme.items():
203
+ if key not in THEME:
204
+ problems.append(f"theme.{key} isn't a theme colour: use {', '.join(THEME)}")
205
+ elif not isinstance(value, str) or not _HEX.fullmatch(value):
206
+ problems.append(f"theme.{key} should be a colour like '#282c34', got {value!r}")
207
+
208
+ runs = data.get("run", []) if _problem("list of tables", data.get("run", [])) is None else []
209
+ steps = data.get("step", []) if _problem("list of tables", data.get("step", [])) is None else []
210
+ if bool(runs) == bool(steps):
211
+ problems.append("give either [[run]] entries or [[step]] entries (one or more, not both)")
212
+ for number, run in enumerate(runs, 1):
213
+ where = f"run {number}: "
214
+ _check(run, _RUN, where, problems)
215
+ if "cmd" not in run:
216
+ problems.append(f"{where}cmd is required")
217
+ if "output" in run and "lines" in run:
218
+ problems.append(f"{where}give output or lines, not both")
219
+ for number, step in enumerate(steps, 1):
220
+ where = f"step {number}: "
221
+ _check(step, _STEP, where, problems)
222
+ for key in ("at", "lines"):
223
+ if key not in step:
224
+ problems.append(f"{where}{key} is required")
225
+
226
+ out = data.get("out", [f"{path.stem}.svg"])
227
+ if not _problem("list of str", out):
228
+ for name in out:
229
+ if Path(name).suffix not in FORMATS:
230
+ problems.append(f"out: {name!r} should end in .svg or .html")
231
+ if problems:
232
+ raise ClipError(path, problems)
233
+
234
+ folder = path.parent
235
+ return Clip(
236
+ path=path,
237
+ label=data["label"],
238
+ out=[folder / name for name in out],
239
+ record=Record(
240
+ cwd=folder / record.get("cwd", "."),
241
+ setup=record.get("setup", []),
242
+ env=record.get("env", {}),
243
+ timeout=record.get("timeout", 60),
244
+ ),
245
+ theme=THEME | theme,
246
+ title=data.get("title", ""),
247
+ cols=data.get("cols", 80),
248
+ rows=data.get("rows"),
249
+ prompt=data.get("prompt", DEFAULT_PROMPT),
250
+ final_prompt=data.get("final_prompt"),
251
+ typing_speed=data.get("typing_speed", 28),
252
+ line_gap=data.get("line_gap", 0.07),
253
+ hold=data.get("hold", 4.0),
254
+ duration=data.get("duration"),
255
+ chrome=data.get("chrome", True),
256
+ runs=[
257
+ Run(
258
+ cmd=run["cmd"],
259
+ exec=run.get("exec"),
260
+ output=folder / run["output"] if "output" in run else None,
261
+ lines=run.get("lines"),
262
+ input=run.get("input"),
263
+ record=run.get("record", True),
264
+ prompt=run.get("prompt"),
265
+ think=run.get("think", 0.5),
266
+ pause=run.get("pause", 0.9),
267
+ line_gap=run.get("line_gap"),
268
+ )
269
+ for run in runs
270
+ ],
271
+ steps=[Step(at=step["at"], lines=step["lines"], caret=step.get("caret", False)) for step in steps],
272
+ )
zoetty/html.py ADDED
@@ -0,0 +1,91 @@
1
+ """Render a clip as an HTML fragment (a <div> and a <style>) for pages you control."""
2
+
3
+ from html import escape
4
+
5
+ from zoetty.clip import Clip
6
+ from zoetty.timeline import Timeline, percent
7
+
8
+ FONTS = 'ui-monospace,"JetBrains Mono","SF Mono",Menlo,Consolas,monospace'
9
+
10
+
11
+ def render(clip: Clip, timeline: Timeline, name: str) -> str:
12
+ """The clip as an HTML fragment.
13
+
14
+ Text is real, selectable text. Every class and keyframe is prefixed with `name`, so
15
+ several clips can share a page.
16
+ """
17
+ total = timeline.duration
18
+ css: list[str] = []
19
+ body: list[str] = []
20
+ n = name
21
+
22
+ for index, line in enumerate(timeline.lines):
23
+ css.append(f"@keyframes {n}-l{index}{{0%{{opacity:0}}{percent(line.at, total)},100%{{opacity:1}}}}")
24
+ parts = []
25
+ clock = line.at
26
+ for position, segment in enumerate(line.segments):
27
+ classes = " ".join(f"{n}-{style}" for style in segment.styles)
28
+ text = escape(segment.text)
29
+ if segment.typing is not None and segment.text:
30
+ length = len(segment.text)
31
+ animation = f"{n}-t{index}-{position}"
32
+ start = clock + segment.delay
33
+ end = start + segment.typing
34
+ css.append(
35
+ f"@keyframes {animation}{{0%,{percent(start, total)}"
36
+ f"{{width:0;animation-timing-function:steps({length},end)}}"
37
+ f"{percent(end, total)},100%{{width:{length}ch}}}}"
38
+ )
39
+ parts.append(f'<span class="{n}-type {classes}" style="animation-name:{animation}">{text}</span>')
40
+ clock = end
41
+ elif classes:
42
+ parts.append(f'<span class="{classes}">{text}</span>')
43
+ else:
44
+ parts.append(text)
45
+ if line.caret_until is not None:
46
+ css.append(
47
+ f"@keyframes {n}-k{index}{{0%{{opacity:0}}{percent(line.at, total)}{{opacity:1}}"
48
+ f"{percent(line.caret_until, total)},100%{{opacity:0}}}}"
49
+ )
50
+ parts.append(f'<span class="{n}-caret" style="animation-name:{n}-k{index}"><i></i></span>')
51
+ body.append(f'<div class="{n}-ln" style="animation-name:{n}-l{index}">{"".join(parts) or "&nbsp;"}</div>')
52
+
53
+ stops = "".join(
54
+ f"{percent(at, total)}{{transform:translateY(-{rows * 1.5:g}em)}}" for at, rows in timeline.scroll()
55
+ )
56
+ last = max(len(timeline.lines) - timeline.rows, 0) * 1.5
57
+ css.append(
58
+ f"@keyframes {n}-scroll{{0%{{transform:translateY(0)}}{stops}100%{{transform:translateY(-{last:g}em)}}}}"
59
+ )
60
+ css.append(
61
+ f"@keyframes {n}-fade{{0%{{opacity:1}}{percent(timeline.fade, total)}"
62
+ f"{{opacity:1;animation-timing-function:ease}}100%{{opacity:0}}}}"
63
+ )
64
+
65
+ theme = "".join(f"--{key}:{value};" for key, value in clip.theme.items())
66
+ colours = "".join(f".{n}-{c}{{color:var(--{c})}}" for c in ("blue", "green", "yellow", "red", "cyan", "magenta"))
67
+ bar = ""
68
+ if clip.chrome:
69
+ bar = f'<div class="{n}-bar"><span></span><span></span><span></span><b>{escape(clip.title)}</b></div>\n'
70
+ newline = "\n"
71
+ return f"""<div class="{n}" role="img" aria-label="{escape(clip.label)}">
72
+ {bar}<div class="{n}-screen" style="animation-name:{n}-fade"><div class="{n}-view"><div class="{n}-body" style="animation-name:{n}-scroll">{"".join(body)}</div></div></div>
73
+ </div>
74
+ <style>
75
+ .{n}{{{theme}font:clamp(9px,1.6vw,14px)/1.5 {FONTS};background:var(--bg);color:var(--fg);border-radius:10px;overflow:hidden;width:min(100%,calc({clip.cols}ch + 3em));box-shadow:0 10px 30px #0006;text-align:left;margin:1.5em 0}}
76
+ .{n}-bar{{display:flex;align-items:center;gap:.45em;padding:.6em .9em;background:var(--bar)}}
77
+ .{n}-bar span{{width:.8em;height:.8em;border-radius:50%;background:var(--fg);opacity:.3}}
78
+ .{n}-bar b{{flex:1;text-align:center;font-weight:400;opacity:.5;margin-right:3em}}
79
+ .{n}-screen{{padding:1em 1.5em 1.2em}}
80
+ .{n}-view{{height:{timeline.rows * 1.5:g}em;overflow:hidden}}
81
+ .{n}-screen,.{n}-body,.{n}-ln,.{n}-type,.{n}-caret{{animation-duration:{total}s;animation-iteration-count:infinite;animation-timing-function:step-end}}
82
+ .{n}-ln{{white-space:pre;opacity:0}}
83
+ .{n}-type{{display:inline-block;vertical-align:bottom;overflow:hidden;width:0}}
84
+ .{n}-caret{{opacity:0}}
85
+ .{n}-caret i{{display:inline-block;width:.6em;height:1.15em;vertical-align:-.2em;background:var(--fg);animation:{n}-blink 1s step-end infinite}}
86
+ @keyframes {n}-blink{{50%{{opacity:0}}}}
87
+ .{n}-dim{{opacity:.55}}.{n}-bold{{font-weight:700}}.{n}-italic{{font-style:italic}}{colours}
88
+ {newline.join(css)}
89
+ @media (prefers-reduced-motion:reduce){{.{n} *{{animation:none!important}}.{n}-ln{{opacity:1}}.{n}-type{{width:auto}}.{n}-caret{{display:none}}.{n}-body{{transform:translateY(-{last:g}em)}}}}
90
+ </style>
91
+ """
zoetty/markup.py ADDED
@@ -0,0 +1,91 @@
1
+ """zoetty's markup: styled text for clip lines and prompts.
2
+
3
+ `[bold blue]text[/]` styles text, `[type 1.2]text[/]` types it out over 1.2 seconds
4
+ (`[type 1.2 0.4]` waits 0.4 seconds first), and `\\[` is a literal `[`.
5
+ """
6
+
7
+ import re
8
+ from dataclasses import dataclass
9
+
10
+ COLOURS = ("blue", "green", "yellow", "red", "cyan", "magenta")
11
+ STYLES = ("bold", "dim", "italic", *COLOURS)
12
+ DEFAULT_TYPING_DELAY = 0.15
13
+
14
+ _TOKEN = re.compile(r"\\\[|\[(/?)([^\[\]]*)\]")
15
+
16
+
17
+ class MarkupError(ValueError):
18
+ """Markup that can't be parsed."""
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class Segment:
23
+ """A run of text with one set of styles, typed out if `typing` is set."""
24
+
25
+ text: str
26
+ styles: tuple[str, ...] = ()
27
+ typing: float | None = None
28
+ delay: float = DEFAULT_TYPING_DELAY
29
+
30
+
31
+ def escape(text: str) -> str:
32
+ """Text with every `[` escaped, so it's shown exactly as it is."""
33
+ return text.replace("[", "\\[")
34
+
35
+
36
+ def _number(value: str, markup: str) -> float:
37
+ try:
38
+ number = float(value)
39
+ except ValueError:
40
+ raise MarkupError(f"[type ...] needs numbers, got {value!r} in {markup!r}") from None
41
+ if number < 0:
42
+ raise MarkupError(f"[type ...] can't be negative, got {value!r} in {markup!r}")
43
+ return number
44
+
45
+
46
+ def parse(markup: str) -> list[Segment]:
47
+ """Split markup into styled segments. Raises MarkupError for anything it doesn't understand."""
48
+ segments: list[Segment] = []
49
+ styles: tuple[str, ...] = ()
50
+ typing: float | None = None
51
+ delay = DEFAULT_TYPING_DELAY
52
+ text = ""
53
+ position = 0
54
+
55
+ def flush() -> None:
56
+ nonlocal text
57
+ if text:
58
+ segments.append(Segment(text, styles, typing, delay))
59
+ text = ""
60
+
61
+ for match in _TOKEN.finditer(markup):
62
+ text += markup[position : match.start()]
63
+ position = match.end()
64
+ if match.group(0) == "\\[":
65
+ text += "["
66
+ continue
67
+ flush()
68
+ closing, tag = match.group(1), match.group(2).split()
69
+ if closing:
70
+ styles, typing, delay = (), None, DEFAULT_TYPING_DELAY
71
+ elif tag and tag[0] == "type":
72
+ if not 2 <= len(tag) <= 3:
73
+ raise MarkupError(f"use [type SECONDS] or [type SECONDS DELAY], got {match.group(0)!r} in {markup!r}")
74
+ typing = _number(tag[1], markup)
75
+ delay = _number(tag[2], markup) if len(tag) == 3 else DEFAULT_TYPING_DELAY
76
+ else:
77
+ unknown = [name for name in tag if name not in STYLES]
78
+ if unknown or not tag:
79
+ raise MarkupError(
80
+ f"unknown style {match.group(0)!r} in {markup!r}: styles are {', '.join(STYLES)}."
81
+ " Write \\[ for a literal ["
82
+ )
83
+ styles = tuple(tag)
84
+ text += markup[position:]
85
+ flush()
86
+ return segments
87
+
88
+
89
+ def plain(segments: list[Segment]) -> str:
90
+ """The text of some segments, without styles."""
91
+ return "".join(segment.text for segment in segments)
zoetty/record.py ADDED
@@ -0,0 +1,130 @@
1
+ """Run commands in a pseudo-terminal and capture what they print, colours and all."""
2
+
3
+ import fcntl
4
+ import os
5
+ import pty
6
+ import select
7
+ import signal
8
+ import struct
9
+ import subprocess
10
+ import termios
11
+ import time
12
+ from dataclasses import dataclass
13
+ from pathlib import Path
14
+
15
+ from zoetty.clip import Clip
16
+
17
+ # How long a command has to be quiet before the next line of `input` is typed.
18
+ QUIET = 0.3
19
+
20
+
21
+ class SetupFailed(Exception):
22
+ def __init__(self, command: str, exit_code: int, output: str) -> None:
23
+ self.command = command
24
+ self.exit_code = exit_code
25
+ self.output = output
26
+ super().__init__(f"setup command {command!r} exited {exit_code}")
27
+
28
+
29
+ @dataclass(frozen=True)
30
+ class Result:
31
+ exit_code: int | None
32
+ output: bytes
33
+ timed_out: bool = False
34
+
35
+
36
+ def environment(clip: Clip) -> dict[str, str]:
37
+ """The environment commands are recorded in: colour on, the clip's size, no pagers."""
38
+ rows = clip.rows or 24
39
+ return (
40
+ os.environ
41
+ | {
42
+ "TERM": "xterm-256color",
43
+ "COLUMNS": str(clip.cols),
44
+ "LINES": str(rows),
45
+ "FORCE_COLOR": "1",
46
+ "CLICOLOR_FORCE": "1",
47
+ "PAGER": "cat",
48
+ "GIT_PAGER": "cat",
49
+ }
50
+ | clip.record.env
51
+ )
52
+
53
+
54
+ def setup(clip: Clip, env: dict[str, str]) -> None:
55
+ """Run the clip's setup commands. Raises SetupFailed on the first that fails."""
56
+ for command in clip.record.setup:
57
+ done = subprocess.run(
58
+ command,
59
+ shell=True,
60
+ cwd=clip.record.cwd,
61
+ env=env,
62
+ capture_output=True,
63
+ text=True,
64
+ timeout=clip.record.timeout,
65
+ )
66
+ if done.returncode:
67
+ raise SetupFailed(command, done.returncode, done.stdout + done.stderr)
68
+
69
+
70
+ def run(
71
+ command: str, *, cwd: Path, env: dict[str, str], cols: int, rows: int, input: str | None = None, timeout: float = 60
72
+ ) -> Result:
73
+ """Run a shell command in a pty sized cols x rows and return everything it wrote.
74
+
75
+ Each line of `input` is typed once the command has been quiet for a moment, so it
76
+ lands after the prompt that asked for it, the way a person would type it. Once it has
77
+ all been typed, Ctrl-D (end of input) is sent, which ends a REPL or a `cat`.
78
+ """
79
+ pending = (input or "").splitlines(keepends=True)
80
+ if pending:
81
+ pending.append("\x04")
82
+ primary, secondary = pty.openpty()
83
+ fcntl.ioctl(secondary, termios.TIOCSWINSZ, struct.pack("HHHH", rows, cols, 0, 0))
84
+ # Don't echo control characters as ^D, ^C: nobody sees those in a real session.
85
+ attributes = termios.tcgetattr(secondary)
86
+ attributes[3] &= ~termios.ECHOCTL
87
+ termios.tcsetattr(secondary, termios.TCSANOW, attributes)
88
+ process = subprocess.Popen(
89
+ ["/bin/sh", "-c", command],
90
+ stdin=secondary,
91
+ stdout=secondary,
92
+ stderr=secondary,
93
+ cwd=cwd,
94
+ env=env,
95
+ start_new_session=True,
96
+ )
97
+ os.close(secondary)
98
+ output = bytearray()
99
+ ended_at: int | None = None
100
+ deadline = time.monotonic() + timeout
101
+ try:
102
+ while True:
103
+ if time.monotonic() > deadline:
104
+ os.killpg(process.pid, signal.SIGKILL)
105
+ process.wait()
106
+ return Result(None, bytes(output), timed_out=True)
107
+ ready, _, _ = select.select([primary], [], [], QUIET)
108
+ if ready:
109
+ try:
110
+ chunk = os.read(primary, 65536)
111
+ except OSError: # Linux: the command and everything it started have closed the terminal
112
+ chunk = b""
113
+ if not chunk:
114
+ break
115
+ output += chunk
116
+ elif pending:
117
+ typed = pending.pop(0)
118
+ os.write(primary, typed.encode())
119
+ if typed == "\x04":
120
+ ended_at = len(output)
121
+ elif process.poll() is not None:
122
+ break
123
+ finally:
124
+ os.close(primary)
125
+ if ended_at is not None:
126
+ # Some programs (Python's REPL) turn control-character echo back on: drop the ^D it shows.
127
+ marker = output.find(b"^D", ended_at)
128
+ if marker != -1:
129
+ del output[marker : marker + 2]
130
+ return Result(process.wait(), bytes(output))
zoetty/settings.py ADDED
@@ -0,0 +1,3 @@
1
+ from importlib.metadata import version
2
+
3
+ VERSION = version("zoetty")
zoetty/svg.py ADDED
@@ -0,0 +1,141 @@
1
+ """Render a clip as one animated SVG, for anywhere that takes an image (READMEs, PyPI)."""
2
+
3
+ from html import escape
4
+
5
+ from zoetty.clip import Clip
6
+ from zoetty.markup import COLOURS
7
+ from zoetty.timeline import Timeline, percent
8
+
9
+ FONT_SIZE = 14
10
+ LINE_HEIGHT = 21
11
+ CHAR_WIDTH = FONT_SIZE * 0.6
12
+ PAD_X, PAD_Y = 24, 18
13
+ BAR = 34
14
+ FONTS = 'ui-monospace,"SF Mono",Menlo,Consolas,"DejaVu Sans Mono","Liberation Mono",monospace'
15
+
16
+
17
+ def render(clip: Clip, timeline: Timeline, name: str) -> str:
18
+ """The clip as an SVG document.
19
+
20
+ Every text run is pinned to its column with textLength, so alignment holds whatever
21
+ monospace font the viewer falls back to (an <img> can't load web fonts). Typing is a
22
+ background-coloured cover that slides right in steps, carrying the caret with it.
23
+ """
24
+ theme = clip.theme
25
+ total = timeline.duration
26
+ bar = BAR if clip.chrome else 0
27
+ top = bar + PAD_Y
28
+ width = round(clip.cols * CHAR_WIDTH + PAD_X * 2)
29
+ height = round(top + PAD_Y + timeline.rows * LINE_HEIGHT)
30
+ css: list[str] = []
31
+ body: list[str] = []
32
+
33
+ for index, line in enumerate(timeline.lines):
34
+ y = top + index * LINE_HEIGHT
35
+ baseline = y + LINE_HEIGHT * 0.75
36
+ css.append(f"@keyframes {name}-l{index}{{0%{{opacity:0}}{percent(line.at, total)},100%{{opacity:1}}}}")
37
+ texts: list[str] = []
38
+ covers: list[tuple[str, float, float]] = []
39
+ column, clock = 0, line.at
40
+ for segment in line.segments:
41
+ length = len(segment.text)
42
+ stripped = segment.text.rstrip()
43
+ lead = len(stripped) - len(stripped.lstrip())
44
+ stripped = stripped.lstrip()
45
+ if stripped:
46
+ attributes = [
47
+ f'x="{PAD_X + (column + lead) * CHAR_WIDTH:.1f}"',
48
+ f'y="{baseline:.1f}"',
49
+ f'textLength="{len(stripped) * CHAR_WIDTH:.1f}"',
50
+ 'lengthAdjust="spacingAndGlyphs"',
51
+ ]
52
+ for style in segment.styles:
53
+ if style in COLOURS:
54
+ attributes.append(f'fill="{theme[style]}"')
55
+ elif style == "bold":
56
+ attributes.append('font-weight="700"')
57
+ elif style == "italic":
58
+ attributes.append('font-style="italic"')
59
+ else:
60
+ attributes.append('opacity=".55"')
61
+ texts.append(f"<text {' '.join(attributes)}>{escape(stripped)}</text>")
62
+ if segment.typing is not None and length:
63
+ start = clock + segment.delay
64
+ end = start + segment.typing
65
+ animation = f"{name}-t{index}-{column}"
66
+ shift = length * CHAR_WIDTH
67
+ css.append(
68
+ f"@keyframes {animation}{{0%,{percent(start, total)}"
69
+ f"{{transform:translateX(0);animation-timing-function:steps({length},end)}}"
70
+ f"{percent(end, total)},100%{{transform:translateX({shift:.1f}px)}}}}"
71
+ )
72
+ covers.append((animation, PAD_X + column * CHAR_WIDTH, shift))
73
+ clock = end
74
+ column += length
75
+ body.append(f'<g class="a" style="animation-name:{name}-l{index}">{"".join(texts)}')
76
+ for animation, x, shift in covers:
77
+ body.append(
78
+ f'<g class="a cover" style="animation-name:{animation}">'
79
+ f'<rect x="{x:.1f}" y="{y:.1f}" width="{shift + CHAR_WIDTH:.1f}" height="{LINE_HEIGHT}"'
80
+ f' fill="{theme["bg"]}"/></g>'
81
+ )
82
+ body.append("</g>")
83
+ if line.caret_until is not None:
84
+ x = PAD_X + column * CHAR_WIDTH
85
+ ride = ""
86
+ if covers: # the caret starts where the last typed text starts, and rides its cover
87
+ animation, x, _ = covers[-1]
88
+ ride = f' class="a" style="animation-name:{animation}"'
89
+ css.append(
90
+ f"@keyframes {name}-k{index}{{0%{{opacity:0}}{percent(line.at, total)}{{opacity:1}}"
91
+ f"{percent(line.caret_until, total)},100%{{opacity:0}}}}"
92
+ )
93
+ body.append(
94
+ f'<g class="a caret" style="animation-name:{name}-k{index}"><g{ride}>'
95
+ f'<rect class="blink" x="{x:.1f}" y="{y + 2:.1f}" width="{CHAR_WIDTH:.1f}"'
96
+ f' height="{LINE_HEIGHT - 4}" fill="{theme["fg"]}"/></g></g>'
97
+ )
98
+
99
+ stops = "".join(
100
+ f"{percent(at, total)}{{transform:translateY(-{rows * LINE_HEIGHT}px)}}" for at, rows in timeline.scroll()
101
+ )
102
+ last = max(len(timeline.lines) - timeline.rows, 0) * LINE_HEIGHT
103
+ css.append(
104
+ f"@keyframes {name}-scroll{{0%{{transform:translateY(0)}}{stops}100%{{transform:translateY(-{last}px)}}}}"
105
+ )
106
+ css.append(
107
+ f"@keyframes {name}-fade{{0%{{opacity:1}}{percent(timeline.fade, total)}"
108
+ f"{{opacity:1;animation-timing-function:ease}}100%{{opacity:0}}}}"
109
+ )
110
+
111
+ label = escape(clip.label)
112
+ chrome = ""
113
+ if clip.chrome:
114
+ dots = "".join(
115
+ f'<circle cx="{18 + k * 18}" cy="{BAR / 2}" r="5.5" fill="{theme["fg"]}" opacity=".3"/>' for k in range(3)
116
+ )
117
+ chrome = (
118
+ f'<path d="M0 10a10 10 0 0 1 10-10h{width - 20}a10 10 0 0 1 10 10v{BAR - 10}h-{width}z" fill="{theme["bar"]}"/>'
119
+ f"{dots}"
120
+ f'<text x="{width / 2}" y="{BAR / 2 + 5}" text-anchor="middle" opacity=".5" fill="{theme["fg"]}"'
121
+ f' style="font-size:13px">{escape(clip.title)}</text>'
122
+ )
123
+ newline = "\n"
124
+ return f"""<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="{height}" viewBox="0 0 {width} {height}" role="img" aria-label="{label}">
125
+ <title>{label}</title>
126
+ <style>
127
+ text{{font-family:{FONTS};font-size:{FONT_SIZE}px;white-space:pre}}
128
+ .a{{animation-duration:{total}s;animation-iteration-count:infinite;animation-timing-function:step-end}}
129
+ .blink{{animation:{name}-blink 1s step-end infinite}}
130
+ @keyframes {name}-blink{{50%{{opacity:0}}}}
131
+ {newline.join(css)}
132
+ @media (prefers-reduced-motion:reduce){{.a,.blink{{animation:none!important}}.cover,.caret{{display:none}}.scroll{{transform:translateY(-{last}px)}}}}
133
+ </style>
134
+ <defs><clipPath id="{name}-screen"><rect x="0" y="{top}" width="{width}" height="{timeline.rows * LINE_HEIGHT}"/></clipPath></defs>
135
+ <rect width="{width}" height="{height}" rx="10" fill="{theme["bg"]}"/>
136
+ {chrome}
137
+ <g clip-path="url(#{name}-screen)" fill="{theme["fg"]}"><g class="a" style="animation-name:{name}-fade"><g class="a scroll" style="animation-name:{name}-scroll">
138
+ {newline.join(body)}
139
+ </g></g></g>
140
+ </svg>
141
+ """
zoetty/timeline.py ADDED
@@ -0,0 +1,128 @@
1
+ """Turn a clip into timed lines: what appears on screen, and when."""
2
+
3
+ import re
4
+ from dataclasses import dataclass
5
+ from pathlib import Path
6
+
7
+ from zoetty import ansi
8
+ from zoetty.clip import Clip
9
+ from zoetty.markup import Segment, escape, parse
10
+
11
+ START = 0.4
12
+ FADE = 0.6
13
+ MIN_TYPING, MAX_TYPING = 0.4, 2.2
14
+
15
+
16
+ class MissingCapture(Exception):
17
+ """A run's output file hasn't been recorded yet."""
18
+
19
+ def __init__(self, path: Path) -> None:
20
+ self.path = path
21
+ super().__init__(f"{path} doesn't exist yet: run `zoetty record` first")
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class Line:
26
+ """One line of the screen: shown from `at`, with a caret until `caret_until` if set."""
27
+
28
+ at: float
29
+ segments: list[Segment]
30
+ caret_until: float | None = None
31
+
32
+ @property
33
+ def columns(self) -> int:
34
+ return sum(len(segment.text) for segment in self.segments)
35
+
36
+
37
+ @dataclass(frozen=True)
38
+ class Timeline:
39
+ lines: list[Line]
40
+ duration: float
41
+ rows: int
42
+
43
+ @property
44
+ def fade(self) -> float:
45
+ """When the screen starts fading out before the loop restarts."""
46
+ return max(self.duration - FADE, 0)
47
+
48
+ def scroll(self) -> list[tuple[float, int]]:
49
+ """(time, rows scrolled) each time a line lands below the bottom of the screen."""
50
+ return [(line.at, index - self.rows + 1) for index, line in enumerate(self.lines) if index >= self.rows]
51
+
52
+
53
+ def percent(seconds: float, total: float) -> str:
54
+ """A time as a keyframe percentage of the loop."""
55
+ return f"{min(seconds / total * 100, 100):.3f}%"
56
+
57
+
58
+ def name(path: Path) -> str:
59
+ """A CSS-safe name for a clip, from its output file, used to prefix its keyframes and classes."""
60
+ return "zt-" + re.sub(r"[^a-zA-Z0-9]+", "-", path.stem).strip("-").lower()
61
+
62
+
63
+ def wrap(segments: list[Segment], cols: int) -> list[list[Segment]]:
64
+ """Split a line into rows of at most `cols` characters, the way a terminal wraps output."""
65
+ rows: list[list[Segment]] = [[]]
66
+ used = 0
67
+ for segment in segments:
68
+ text = segment.text
69
+ while text:
70
+ if used == cols:
71
+ rows.append([])
72
+ used = 0
73
+ piece, text = text[: cols - used], text[cols - used :]
74
+ rows[-1].append(Segment(piece, segment.styles, segment.typing, segment.delay))
75
+ used += len(piece)
76
+ return rows
77
+
78
+
79
+ def _from_runs(clip: Clip) -> tuple[list[Line], float]:
80
+ steps: list[tuple[float, list[Segment], bool]] = []
81
+ t = START
82
+ for run in clip.runs:
83
+ typing = min(max(len(run.cmd) / clip.typing_speed, MIN_TYPING), MAX_TYPING)
84
+ prompt = clip.prompt if run.prompt is None else run.prompt
85
+ steps.append((t, parse(f"{prompt}[type {typing:.2f}]{escape(run.cmd)}[/]"), True))
86
+ t += 0.15 + typing + run.think
87
+ if run.output is not None:
88
+ if not run.output.exists():
89
+ raise MissingCapture(run.output)
90
+ output = ansi.to_markup(run.output.read_text(errors="replace"))
91
+ else:
92
+ output = run.lines or []
93
+ gap = clip.line_gap if run.line_gap is None else run.line_gap
94
+ for line in output:
95
+ for row in wrap(parse(line), clip.cols):
96
+ steps.append((round(t, 3), row, False))
97
+ t += gap
98
+ t += run.pause
99
+ final = clip.prompt if clip.final_prompt is None else clip.final_prompt
100
+ steps.append((round(t, 3), parse(final), True))
101
+ duration = clip.duration or round(t + clip.hold, 2)
102
+ return _lines(steps, duration), duration
103
+
104
+
105
+ def _from_steps(clip: Clip) -> tuple[list[Line], float]:
106
+ ordered = sorted(clip.steps, key=lambda step: step.at)
107
+ duration = clip.duration or round(ordered[-1].at + clip.hold, 2)
108
+ steps = []
109
+ for step in ordered:
110
+ for index, line in enumerate(step.lines):
111
+ steps.append((step.at, parse(line), step.caret and index == len(step.lines) - 1))
112
+ return _lines(steps, duration), duration
113
+
114
+
115
+ def _lines(steps: list[tuple[float, list[Segment], bool]], duration: float) -> list[Line]:
116
+ """Lines from (time, segments, has caret) steps. A caret lasts until the next line appears."""
117
+ lines = []
118
+ for index, (at, segments, caret) in enumerate(steps):
119
+ later = [time for time, _, _ in steps[index + 1 :] if time > at]
120
+ until = (later[0] if later else duration) if caret else None
121
+ lines.append(Line(at, segments, until))
122
+ return lines
123
+
124
+
125
+ def build(clip: Clip) -> Timeline:
126
+ """Everything shown in the clip, with times in seconds. Raises MissingCapture."""
127
+ lines, duration = _from_runs(clip) if clip.runs else _from_steps(clip)
128
+ return Timeline(lines, duration, clip.rows or len(lines))
@@ -0,0 +1,145 @@
1
+ Metadata-Version: 2.5
2
+ Name: zoetty
3
+ Version: 0.1.0
4
+ Summary: Looping terminal demo clips as plain SVG or HTML and CSS
5
+ Project-URL: Homepage, https://github.com/phalt/zoetty
6
+ Project-URL: Documentation, https://phalt.github.io/zoetty/
7
+ Project-URL: Issues, https://github.com/phalt/zoetty/issues
8
+ Author-email: Paul Hallett <paulandrewhallett@gmail.com>
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: animation,cli,demo,docs,readme,svg,terminal
12
+ Classifier: Environment :: Console
13
+ Classifier: Operating System :: MacOS
14
+ Classifier: Operating System :: POSIX :: Linux
15
+ Classifier: Topic :: Documentation
16
+ Classifier: Topic :: Multimedia :: Graphics
17
+ Requires-Python: >=3.12
18
+ Requires-Dist: click>=8.5.0
19
+ Requires-Dist: rich>=15.0.0
20
+ Description-Content-Type: text/markdown
21
+
22
+ # ⚜ zoetty
23
+
24
+ ## What is zoetty?
25
+
26
+ zoetty turns terminal sessions into small, looping, animated clips made of plain SVG or HTML and CSS. No video, no GIF, no JavaScript.
27
+
28
+ [![Package version](https://img.shields.io/pypi/v/zoetty?color=%2334D058&label=latest%20version)](https://pypi.org/project/zoetty)
29
+ ![Python versions](https://img.shields.io/badge/python-3.12+-blue)
30
+ ![PyPI - License](https://img.shields.io/pypi/l/zoetty)
31
+
32
+ ![zoetty init writes a starter clip spec, zoetty build renders it to SVG, and zoetty check confirms it is up to date](https://raw.githubusercontent.com/phalt/zoetty/main/docs/clips/quickstart.svg)
33
+
34
+ That's zoetty, recorded by zoetty. Every clip in this README is built from a spec in [`docs/clips/`](https://github.com/phalt/zoetty/tree/main/docs/clips).
35
+
36
+ ## Why use zoetty?
37
+
38
+ Terminal GIFs go stale, weigh megabytes, look blurry, and have to be re-recorded by hand every time the output changes.
39
+
40
+ - **Real output** - `zoetty record` runs your commands in a real terminal and keeps their colours.
41
+ - **Small and sharp** - A clip is a few KB of text, crisp at any size.
42
+ - **Works in READMEs** - The SVG is just an image: it plays on GitHub, PyPI and anywhere else that shows one.
43
+ - **Or in your docs** - The HTML fragment drops into any page, with selectable text.
44
+ - **Kept in your repo** - The spec is a short TOML file. When your tool changes, re-record and rebuild.
45
+ - **Checked in CI** - `zoetty check` fails if a clip is out of date.
46
+
47
+ ## Install
48
+
49
+ ```sh
50
+ uv tool install zoetty
51
+ ```
52
+
53
+ Or with pip:
54
+
55
+ ```sh
56
+ pip install zoetty
57
+ ```
58
+
59
+ zoetty needs Python 3.12 or later, and runs on **macOS and Linux**.
60
+
61
+ ## Quick start
62
+
63
+ ```sh
64
+ zoetty init docs/clips/hello.toml # write a starter spec
65
+ zoetty build docs/clips/hello.toml # render it to docs/clips/hello.svg
66
+ ```
67
+
68
+ Then put it in your README like any image:
69
+
70
+ ```markdown
71
+ ![What the clip shows](docs/clips/hello.svg)
72
+ ```
73
+
74
+ ## A basic clip
75
+
76
+ Two commands, with their output written by hand:
77
+
78
+ ```toml
79
+ title = "~/my-project"
80
+ label = "Typing two commands in a terminal: echo prints a greeting, ls lists three files"
81
+ cols = 60
82
+
83
+ [[run]]
84
+ cmd = "echo 'Hello from zoetty!'"
85
+ lines = ["Hello from zoetty!"]
86
+
87
+ [[run]]
88
+ cmd = "ls"
89
+ lines = ["[blue]docs[/] README.md [green]tool.py[/]"]
90
+ ```
91
+
92
+ ![Typing two commands in a terminal: echo prints a greeting, ls lists three files](https://raw.githubusercontent.com/phalt/zoetty/main/docs/clips/hello.svg)
93
+
94
+ ## Recording real output
95
+
96
+ Give a run an `output` file and `zoetty record` runs the command for real and saves what it printed. `input` is typed into interactive programs, a line at a time, once each prompt is waiting:
97
+
98
+ ```toml
99
+ title = "python"
100
+ label = "A Python REPL importing zoetty's markup parser and parsing some styled text"
101
+ cols = 64
102
+
103
+ [record]
104
+ env = { PYTHON_BASIC_REPL = "1" }
105
+
106
+ [[run]]
107
+ cmd = "python -q"
108
+ output = "captures/repl.ansi"
109
+ input = """
110
+ from zoetty.markup import parse, plain
111
+ plain(parse("[bold]zoe[/]tty"))
112
+ [s.styles for s in parse("[bold green]ok[/] done")]
113
+ """
114
+ ```
115
+
116
+ ```sh
117
+ zoetty record docs/clips/repl.toml
118
+ zoetty build docs/clips/repl.toml
119
+ ```
120
+
121
+ ![A Python REPL importing zoetty's markup parser and parsing some styled text](https://raw.githubusercontent.com/phalt/zoetty/main/docs/clips/repl.svg)
122
+
123
+ Long output scrolls once it passes `rows`, and `[theme]` recolours the whole window:
124
+
125
+ ![python -m this printing the Zen of Python, scrolling past the bottom of a ten-row terminal](https://raw.githubusercontent.com/phalt/zoetty/main/docs/clips/zen.svg)
126
+
127
+ See [more examples](https://phalt.github.io/zoetty/examples/), including the HTML output and hand-timed clips.
128
+
129
+ ## Use it with your coding agent
130
+
131
+ zoetty is easy for coding agents to drive: specs are small text files, and every command says what it did. Paste this into Claude Code, Codex, Cursor or similar:
132
+
133
+ ```text
134
+ Use zoetty to add an animated terminal demo of this project to the README.
135
+ Read https://phalt.github.io/zoetty/agents/ first and follow it: install zoetty,
136
+ write a clip spec in docs/clips/ that shows the most useful commands, record the
137
+ real output with `zoetty record`, build it with `zoetty build`, look at the result,
138
+ embed the SVG in README.md, and add `zoetty check docs/clips/*.toml` to CI.
139
+ ```
140
+
141
+ ## Documentation
142
+
143
+ 👉 Read the [full documentation](https://phalt.github.io/zoetty/) for the clip format, every command, embedding clips and more examples.
144
+
145
+ Want to help? See [CONTRIBUTING.md](https://github.com/phalt/zoetty/blob/main/CONTRIBUTING.md).
@@ -0,0 +1,15 @@
1
+ zoetty/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ zoetty/ansi.py,sha256=WQSXLANIBrkIXzoXHVJdgVegjrCOsC0W9KCfEtu5_ws,2595
3
+ zoetty/cli.py,sha256=hPOyl-CN5LLY3hWQWJoV4mdbdyiWsnFIDgfDsoZ9Xuo,6155
4
+ zoetty/clip.py,sha256=KroTczkAR3hebUdJF88ZiNCVxgbYZ6rtRZX60MDmk-4,9026
5
+ zoetty/html.py,sha256=Sq794bqWKTxfcIJM0mjDVDXgrmTQwr6BNMnDoxWP_gM,4783
6
+ zoetty/markup.py,sha256=2Ot0-iPB1-ERhPP9OpptccSibCTF8aGoMy0BcZD3a10,2959
7
+ zoetty/record.py,sha256=2fD243SiTnZrZsaCAtI6YUTdhX4BmtYLY5saQLwN8GQ,4288
8
+ zoetty/settings.py,sha256=xYRHj7Q8vONJmhQz9ahEDqDREFSdFOGXxaSeb96Yc3A,68
9
+ zoetty/svg.py,sha256=VYbuj2AvQA0kcAWVa7sO385ZZVRPgxwHzPw5pKoO9IA,6619
10
+ zoetty/timeline.py,sha256=q18SLEbgfhP6CYRFadDqjgwuljuFn4rpg5WfIR4nei8,4654
11
+ zoetty-0.1.0.dist-info/METADATA,sha256=arKe8heJd1hrVX8G7JbkE9N2OWw_kUUTwVmGnufLGj0,5208
12
+ zoetty-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
13
+ zoetty-0.1.0.dist-info/entry_points.txt,sha256=cuaHbRQOLQMovQRUN9JRDgbOWkPUHrG1-Ya3Jyd0w3U,42
14
+ zoetty-0.1.0.dist-info/licenses/LICENSE,sha256=_SGo9NmVDb6WDN2zpuqiKioHP-8xpjP82fmhFPco4Iw,1069
15
+ zoetty-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ zoetty = zoetty.cli:cli
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Paul Hallett
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.