codersforge 0.0.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.
- codersforge/__init__.py +4 -0
- codersforge/__main__.py +8 -0
- codersforge/_core/CORE_VERSION +33 -0
- codersforge/_core/__init__.py +8 -0
- codersforge/_core/archive.py +319 -0
- codersforge/_core/backup.py +417 -0
- codersforge/_core/config.py +206 -0
- codersforge/_core/domain.py +382 -0
- codersforge/_core/errors.py +36 -0
- codersforge/_core/events.py +381 -0
- codersforge/_core/findings.py +265 -0
- codersforge/_core/gates.py +395 -0
- codersforge/_core/identity.py +259 -0
- codersforge/_core/index.py +262 -0
- codersforge/_core/items.py +513 -0
- codersforge/_core/ledger.py +194 -0
- codersforge/_core/lessons.py +142 -0
- codersforge/_core/messages.py +293 -0
- codersforge/_core/migrate.py +221 -0
- codersforge/_core/output.py +41 -0
- codersforge/_core/paths.py +62 -0
- codersforge/_core/py.typed +0 -0
- codersforge/_core/schema.py +113 -0
- codersforge/_core/ulid.py +36 -0
- codersforge/_core/upgrade.py +57 -0
- codersforge/_core/versions.py +20 -0
- codersforge/_core/views.py +67 -0
- codersforge/_core/walls.py +231 -0
- codersforge/_core/workflow.py +745 -0
- codersforge/_docs.py +33 -0
- codersforge/checks.py +94 -0
- codersforge/cli.py +865 -0
- codersforge/domain.py +270 -0
- codersforge/py.typed +0 -0
- codersforge/workflows.yaml +129 -0
- codersforge-0.0.1.dist-info/METADATA +81 -0
- codersforge-0.0.1.dist-info/RECORD +41 -0
- codersforge-0.0.1.dist-info/WHEEL +4 -0
- codersforge-0.0.1.dist-info/entry_points.txt +2 -0
- codersforge-0.0.1.dist-info/licenses/LICENSE +202 -0
- codersforge-0.0.1.dist-info/licenses/NOTICE +7 -0
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
"""The index: a SQLite cache of the log, for queries.
|
|
3
|
+
|
|
4
|
+
The event log is the record; the index is generated from it and is safe to
|
|
5
|
+
delete. It remembers the log's size and the hash of its last line; when either
|
|
6
|
+
differs, the index is rebuilt from a full replay before it answers. A rebuild
|
|
7
|
+
writes a new file and renames it into place, so a reader never sees half of
|
|
8
|
+
one.
|
|
9
|
+
|
|
10
|
+
``reindex`` also repairs the item files: a front-matter ``state`` that
|
|
11
|
+
disagrees with the log is rewritten (the log wins), and a missing primary file
|
|
12
|
+
is recreated from the log with its type's starting body.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import hashlib
|
|
18
|
+
import json
|
|
19
|
+
import os
|
|
20
|
+
import re
|
|
21
|
+
import sqlite3
|
|
22
|
+
import tempfile
|
|
23
|
+
from collections.abc import Iterable, Mapping, Sequence
|
|
24
|
+
from contextlib import closing
|
|
25
|
+
from dataclasses import dataclass
|
|
26
|
+
from pathlib import Path
|
|
27
|
+
from typing import Any
|
|
28
|
+
|
|
29
|
+
from .domain import Domain
|
|
30
|
+
from .errors import ExitCode, ForgeError
|
|
31
|
+
from .events import EventStore
|
|
32
|
+
from .items import (
|
|
33
|
+
Item,
|
|
34
|
+
_write_atomic,
|
|
35
|
+
fold,
|
|
36
|
+
parse_item_file,
|
|
37
|
+
render_front_matter,
|
|
38
|
+
)
|
|
39
|
+
from .paths import Layout
|
|
40
|
+
from .versions import FRONT_MATTER_SCHEMA_VERSION
|
|
41
|
+
|
|
42
|
+
INDEX_SCHEMA = 2
|
|
43
|
+
_ID = re.compile(r"^([A-Z]+)-(\d+)$")
|
|
44
|
+
|
|
45
|
+
_DDL = """
|
|
46
|
+
CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);
|
|
47
|
+
CREATE TABLE items (
|
|
48
|
+
id TEXT PRIMARY KEY,
|
|
49
|
+
prefix TEXT NOT NULL,
|
|
50
|
+
number INTEGER NOT NULL,
|
|
51
|
+
type TEXT NOT NULL,
|
|
52
|
+
title TEXT NOT NULL,
|
|
53
|
+
state TEXT NOT NULL,
|
|
54
|
+
path TEXT NOT NULL,
|
|
55
|
+
created TEXT NOT NULL,
|
|
56
|
+
assignee TEXT,
|
|
57
|
+
fields TEXT NOT NULL,
|
|
58
|
+
archive_sha256 TEXT
|
|
59
|
+
);
|
|
60
|
+
CREATE INDEX items_by_type ON items (type);
|
|
61
|
+
CREATE INDEX items_by_state ON items (state);
|
|
62
|
+
"""
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _order(item_id: str) -> tuple[str, int]:
|
|
66
|
+
match = _ID.match(item_id)
|
|
67
|
+
return (match.group(1), int(match.group(2))) if match else (item_id, 0)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
@dataclass(frozen=True)
|
|
71
|
+
class Repair:
|
|
72
|
+
"""What ``reindex`` changed in the item files."""
|
|
73
|
+
|
|
74
|
+
states_fixed: tuple[str, ...] = ()
|
|
75
|
+
files_recreated: tuple[str, ...] = ()
|
|
76
|
+
archives_damaged: tuple[str, ...] = () # missing or not matching the logged hash
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class Index:
|
|
80
|
+
"""Queries over a project's items, served from ``.index.sqlite``."""
|
|
81
|
+
|
|
82
|
+
def __init__(self, layout: Layout, domain: Domain) -> None:
|
|
83
|
+
self.layout = layout
|
|
84
|
+
self.domain = domain
|
|
85
|
+
self.store = EventStore(layout, domain)
|
|
86
|
+
|
|
87
|
+
# ------------------------------------------------------------ freshness
|
|
88
|
+
|
|
89
|
+
def _stored_tip(self) -> tuple[int, str] | None:
|
|
90
|
+
if not self.layout.index.exists():
|
|
91
|
+
return None
|
|
92
|
+
try:
|
|
93
|
+
with closing(sqlite3.connect(f"file:{self.layout.index}?mode=ro", uri=True)) as db:
|
|
94
|
+
rows = dict(db.execute("SELECT key, value FROM meta").fetchall())
|
|
95
|
+
except sqlite3.DatabaseError:
|
|
96
|
+
return None
|
|
97
|
+
if rows.get("schema") != str(INDEX_SCHEMA):
|
|
98
|
+
return None
|
|
99
|
+
return int(rows.get("size", "-1")), rows.get("last_hash", "")
|
|
100
|
+
|
|
101
|
+
def is_fresh(self) -> bool:
|
|
102
|
+
"""Whether the index matches the log as it is now."""
|
|
103
|
+
return self._stored_tip() == self.store.tip()
|
|
104
|
+
|
|
105
|
+
def rebuild(self) -> int:
|
|
106
|
+
"""Replay the log into a new index file. Returns the number of items."""
|
|
107
|
+
tip = self.store.tip()
|
|
108
|
+
items = fold(self.store.events(), self.domain)
|
|
109
|
+
self.layout.state.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
110
|
+
fd, tmp = tempfile.mkstemp(dir=self.layout.state, prefix=".index.", suffix=".tmp")
|
|
111
|
+
os.close(fd)
|
|
112
|
+
try:
|
|
113
|
+
with closing(sqlite3.connect(tmp)) as db:
|
|
114
|
+
db.executescript(_DDL)
|
|
115
|
+
db.executemany(
|
|
116
|
+
"INSERT INTO meta (key, value) VALUES (?, ?)",
|
|
117
|
+
[("schema", str(INDEX_SCHEMA)), ("size", str(tip[0])), ("last_hash", tip[1])],
|
|
118
|
+
)
|
|
119
|
+
db.executemany(
|
|
120
|
+
"INSERT INTO items VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
|
121
|
+
[
|
|
122
|
+
(
|
|
123
|
+
i.id,
|
|
124
|
+
*_order(i.id),
|
|
125
|
+
i.type,
|
|
126
|
+
i.title,
|
|
127
|
+
i.state,
|
|
128
|
+
i.path,
|
|
129
|
+
i.created,
|
|
130
|
+
i.assignee,
|
|
131
|
+
json.dumps(dict(i.fields), sort_keys=True),
|
|
132
|
+
i.archive_sha256,
|
|
133
|
+
)
|
|
134
|
+
for i in items.values()
|
|
135
|
+
],
|
|
136
|
+
)
|
|
137
|
+
db.commit()
|
|
138
|
+
os.chmod(tmp, 0o600)
|
|
139
|
+
os.replace(tmp, self.layout.index)
|
|
140
|
+
except BaseException:
|
|
141
|
+
Path(tmp).unlink(missing_ok=True)
|
|
142
|
+
raise
|
|
143
|
+
return len(items)
|
|
144
|
+
|
|
145
|
+
def ensure(self) -> None:
|
|
146
|
+
"""Rebuild if the log has changed since the index was built."""
|
|
147
|
+
if not self.is_fresh():
|
|
148
|
+
self.rebuild()
|
|
149
|
+
|
|
150
|
+
# ------------------------------------------------------------ queries
|
|
151
|
+
|
|
152
|
+
def items(
|
|
153
|
+
self,
|
|
154
|
+
*,
|
|
155
|
+
type_name: str | None = None,
|
|
156
|
+
state: str | None = None,
|
|
157
|
+
epic: str | None = None,
|
|
158
|
+
open_only: bool = False,
|
|
159
|
+
) -> list[Item]:
|
|
160
|
+
"""Items in ID order, filtered. ``open_only`` keeps items a workflow still works on."""
|
|
161
|
+
self.ensure()
|
|
162
|
+
sql = (
|
|
163
|
+
"SELECT id, type, title, state, path, created, assignee, fields, archive_sha256"
|
|
164
|
+
" FROM items"
|
|
165
|
+
)
|
|
166
|
+
where: list[str] = []
|
|
167
|
+
args: list[Any] = []
|
|
168
|
+
if type_name is not None:
|
|
169
|
+
where.append("type = ?")
|
|
170
|
+
args.append(type_name)
|
|
171
|
+
if state is not None:
|
|
172
|
+
where.append("state = ?")
|
|
173
|
+
args.append(state)
|
|
174
|
+
if where:
|
|
175
|
+
sql += " WHERE " + " AND ".join(where)
|
|
176
|
+
sql += " ORDER BY prefix, number"
|
|
177
|
+
with closing(sqlite3.connect(f"file:{self.layout.index}?mode=ro", uri=True)) as db:
|
|
178
|
+
rows = db.execute(sql, args).fetchall()
|
|
179
|
+
found = [
|
|
180
|
+
Item(
|
|
181
|
+
id=row[0],
|
|
182
|
+
type=row[1],
|
|
183
|
+
title=row[2],
|
|
184
|
+
state=row[3],
|
|
185
|
+
path=row[4],
|
|
186
|
+
created=row[5],
|
|
187
|
+
assignee=row[6],
|
|
188
|
+
fields=json.loads(row[7]),
|
|
189
|
+
archive_sha256=row[8],
|
|
190
|
+
)
|
|
191
|
+
for row in rows
|
|
192
|
+
]
|
|
193
|
+
if epic is not None:
|
|
194
|
+
found = [i for i in found if i.fields.get("epic") == epic]
|
|
195
|
+
if open_only:
|
|
196
|
+
found = [i for i in found if self._is_open(i)]
|
|
197
|
+
return found
|
|
198
|
+
|
|
199
|
+
def _is_open(self, item: Item) -> bool:
|
|
200
|
+
workflow = self.domain.workflows.get(item.type)
|
|
201
|
+
return workflow.is_open(item.state) if workflow is not None else True
|
|
202
|
+
|
|
203
|
+
# ------------------------------------------------------------ repair
|
|
204
|
+
|
|
205
|
+
def reindex(self) -> Repair:
|
|
206
|
+
"""Rebuild the index and make every item file agree with the log."""
|
|
207
|
+
self.rebuild()
|
|
208
|
+
fixed: list[str] = []
|
|
209
|
+
recreated: list[str] = []
|
|
210
|
+
damaged: list[str] = []
|
|
211
|
+
for item in fold(self.store.events(), self.domain).values():
|
|
212
|
+
path = self.layout.state / item.path
|
|
213
|
+
if item.archived:
|
|
214
|
+
# A rollup cannot be rebuilt from the log: report it, never rewrite it.
|
|
215
|
+
if not path.is_file() or (
|
|
216
|
+
hashlib.sha256(path.read_bytes()).hexdigest() != item.archive_sha256
|
|
217
|
+
):
|
|
218
|
+
damaged.append(item.id)
|
|
219
|
+
continue
|
|
220
|
+
if not path.is_file():
|
|
221
|
+
_write_atomic(path, self._fresh_file(item))
|
|
222
|
+
recreated.append(item.id)
|
|
223
|
+
continue
|
|
224
|
+
front, body = parse_item_file(path.read_text(encoding="utf-8"), self.domain, str(path))
|
|
225
|
+
if front["state"] != item.state or front["title"] != item.title:
|
|
226
|
+
front["state"] = item.state
|
|
227
|
+
front["title"] = item.title
|
|
228
|
+
_write_atomic(path, render_front_matter(front, self.domain) + body)
|
|
229
|
+
fixed.append(item.id)
|
|
230
|
+
return Repair(tuple(fixed), tuple(recreated), tuple(damaged))
|
|
231
|
+
|
|
232
|
+
def _fresh_file(self, item: Item) -> str:
|
|
233
|
+
try:
|
|
234
|
+
body = self.domain.item_type(item.type).body
|
|
235
|
+
except KeyError:
|
|
236
|
+
body = "# {id} — {title}\n"
|
|
237
|
+
front = {
|
|
238
|
+
"schema": FRONT_MATTER_SCHEMA_VERSION,
|
|
239
|
+
"id": item.id,
|
|
240
|
+
"title": item.title,
|
|
241
|
+
"type": item.type,
|
|
242
|
+
"state": item.state,
|
|
243
|
+
**{k: v.default for k, v in self.domain.item_schema.items()},
|
|
244
|
+
**dict(item.fields),
|
|
245
|
+
"created": item.created,
|
|
246
|
+
}
|
|
247
|
+
return (
|
|
248
|
+
render_front_matter(front, self.domain)
|
|
249
|
+
+ "\n"
|
|
250
|
+
+ body.format(id=item.id, title=item.title)
|
|
251
|
+
)
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def replay(events: Iterable[Mapping[str, Any]], domain: Domain) -> Sequence[Item]:
|
|
255
|
+
"""Every item in ID order, straight from the log (what the index must equal)."""
|
|
256
|
+
return sorted(fold(events, domain).values(), key=lambda i: _order(i.id))
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def require_type(domain: Domain, type_name: str | None) -> None:
|
|
260
|
+
"""USAGE error for an unknown ``--type``."""
|
|
261
|
+
if type_name is not None and type_name not in {t.name for t in domain.item_types}:
|
|
262
|
+
raise ForgeError(ExitCode.USAGE, "unknown_type", f"{type_name!r} is not an item type")
|