1"""``fm store.ls`` and ``fm store.show``: the state store, read by hand.
3Every row the workshop keeps is a declared series of the state store
4([livery.git][]), gathered in one place
5([livery.workshop._series][]). ``store.ls`` names each series and
6family with its scope (local, or remote and mirrored by a sync, or
7remote and fetched on read), its window, and what it holds; ``store.show``
8prints a series' rows newest first through the same reader the
9verdicts use, so what a person reads is what the gate judged. Both
10only read: the gate's verbs write, and the janitor bounds.
11"""
13from __future__ import annotations
15import json as _json
16from pathlib import Path
17from typing import Annotated, Any
19from livery import git
20from livery.footman import doc, fail, group
21from livery.workshop._ci_context import state_store
22from livery.workshop._extensions import workspace_root
24store = group("store", help="The state store, read by hand")
27def _root() -> Path:
28 root = workspace_root()
29 if root is None:
30 fail("no workspace: no workshop.toml above the working directory")
31 return root
34def _declared(root: Path) -> tuple[git.Series | git.Keyed, ...]:
35 from livery.workshop._series import declared
37 return declared(root)
40def _scope(item: git.Series | git.Keyed) -> str:
41 """Where *item* lives, how a desk reads it, and its window."""
42 from livery.workshop._series import mirrored
44 window = "no window" if item.window is None else f"window {item.window}"
45 if item.local:
46 where = "local"
47 elif mirrored(item):
48 where = "remote, mirrored by sync"
49 else:
50 where = "remote, fetched on read"
51 return f"{where}, {window}"
54def ls_flow(root: Path) -> list[str]:
55 """One line per declared series or family: scope, window, and what it holds.
57 One listing of the remote namespace and one fetch of what the
58 checkout lacks serve every series, so the call costs two round
59 trips whatever the store holds.
60 """
61 with git.remote_snapshot(state_store(root), fetch=git.WHOLE):
62 return _ls_lines(root)
65def _ls_lines(root: Path) -> list[str]:
66 lines: list[str] = []
67 for item in _declared(root):
68 if isinstance(item, git.Series):
69 found = item.rows(state_store(root))
70 if found.failed:
71 held = found.reason
72 else:
73 held = f"{len(found.rows)} row(s)"
74 if found.skipped:74 ↛ 75line 74 didn't jump to line 75 because the condition on line 74 was never true
75 held += f", {len(found.skipped)} skipped"
76 lines.append(f" {item.name}: {_scope(item)}; {held}")
77 continue
78 keys = item.listed(state_store(root))
79 held = "could not be listed" if keys is None else f"{len(keys)} key(s)"
80 spelled = "/".join(f"<{part}>" for part in item.keys)
81 lines.append(f" {item.name}/{spelled}: {_scope(item)}; {held}")
82 return lines
85def _compact(fields: dict[str, Any]) -> str:
86 """The row's fields on one line: scalars as they are, containers by size."""
87 parts: list[str] = []
88 for name, value in sorted(fields.items()):
89 if isinstance(value, dict):89 ↛ 90line 89 didn't jump to line 90 because the condition on line 89 was never true
90 parts.append(f"{name}: {{{len(value)} entries}}")
91 elif isinstance(value, list):
92 parts.append(f"{name}: [{len(value)} items]")
93 else:
94 parts.append(f"{name}: {value}")
95 return ", ".join(parts)
98def show_flow(
99 root: Path, name: str, *, key: str = "", as_json: bool = False
100) -> list[str]:
101 """A series' rows newest first, a family's by its key, or the rows as JSON.
103 Refuses an unknown name (naming the known ones), a family without
104 its key (listing the keys it holds), a key of the wrong shape, and
105 a series the store cannot read (with the store's reason). The
106 read goes through one listing of the remote namespace.
107 """
108 with git.remote_snapshot(state_store(root), fetch=(name,)):
109 return _show_lines(root, name, key=key, as_json=as_json)
112def _show_lines(
113 root: Path, name: str, *, key: str = "", as_json: bool = False
114) -> list[str]:
115 declared = _declared(root)
116 item = next((each for each in declared if each.name == name), None)
117 if item is None:
118 fail(
119 f"no series named {name!r}; the series are"
120 f" {', '.join(each.name for each in declared)}"
121 )
122 parts = tuple(part for part in key.split(",") if part) if key else ()
123 if isinstance(item, git.Keyed):
124 if not parts:
125 keys = item.listed(state_store(root))
126 if keys is None:126 ↛ 127line 126 didn't jump to line 127 because the condition on line 126 was never true
127 fail(f"{item.name}: its keys could not be listed")
128 spelled = ",".join(f"<{part}>" for part in item.keys)
129 lines = [f" {item.name} is keyed; --key={spelled} picks one of:"]
130 lines += [f" {','.join(found)}" for found in keys] or [" (none yet)"]
131 return lines
132 if len(parts) != len(item.keys):
133 fail(
134 f"{item.name} is keyed by {', '.join(item.keys)}; --key names"
135 f" {len(parts)} part(s)"
136 )
137 series = item.at(*parts)
138 elif parts:
139 fail(f"{item.name} is not keyed; drop --key")
140 else:
141 series = item
142 found = series.rows(state_store(root))
143 if found.failed:
144 fail(found.reason)
145 if as_json:
146 rows = [{"name": row.name, **row.data} for row in found.rows]
147 return [_json.dumps(rows, indent=1, sort_keys=True)]
148 lines = [f" {series.ref}: {len(found.rows)} row(s)"]
149 for row in found.rows:
150 fields = {k: v for k, v in row.data.items() if k not in ("schema", "when")}
151 lines.append(f" {row.name} {row.when or '(unstamped)'}")
152 lines.append(f" {_compact(fields)}")
153 lines.extend(f" {skipped}" for skipped in found.skipped)
154 return lines
157@store.task(name="ls")
158def store_ls() -> None:
159 """List every series the workshop keeps: its scope, its window, what it holds.
161 A remote series is read from origin, a local one from this
162 checkout's git directory; a series that cannot be read prints the
163 store's reason in its place.
164 """
165 for line in ls_flow(_root()):
166 print(line)
169@store.task(name="show")
170def store_show(
171 series: Annotated[str, doc("the series' name, as store.ls lists it")],
172 key: Annotated[str, doc("a family's key, its parts comma-separated")] = "",
173 json: Annotated[bool, doc("the rows as JSON, newest first")] = False,
174) -> None:
175 """Print a series' rows newest first, through the reader the verdicts use.
177 Each row prints as its file name and stamp, then its fields on one
178 line with containers by size; ``--json`` prints every field as it
179 is. A family (``store.ls`` shows its key parts) is shown one key at
180 a time, and without ``--key`` lists the keys it holds.
181 """
182 for line in show_flow(_root(), series, key=key, as_json=json):
183 print(line)