dalea 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.
- dalea/__init__.py +266 -0
- dalea/cli.py +60 -0
- dalea-0.1.0.dist-info/METADATA +67 -0
- dalea-0.1.0.dist-info/RECORD +7 -0
- dalea-0.1.0.dist-info/WHEEL +5 -0
- dalea-0.1.0.dist-info/entry_points.txt +2 -0
- dalea-0.1.0.dist-info/top_level.txt +1 -0
dalea/__init__.py
ADDED
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
"""dalea — Python client for the Dalea wiki engine.
|
|
2
|
+
|
|
3
|
+
Typed models for pages, sections, revisions, and backlinks, with read + small
|
|
4
|
+
write surfaces. The HTTP layer is injectable so tests never hit the network.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
import urllib.error
|
|
12
|
+
import urllib.parse
|
|
13
|
+
import urllib.request
|
|
14
|
+
from dataclasses import dataclass, field
|
|
15
|
+
from typing import Any, Iterator, Protocol
|
|
16
|
+
|
|
17
|
+
__version__ = "0.1.0"
|
|
18
|
+
|
|
19
|
+
__all__ = [
|
|
20
|
+
"DaleaError",
|
|
21
|
+
"DaleaClient",
|
|
22
|
+
"Page",
|
|
23
|
+
"Section",
|
|
24
|
+
"Revision",
|
|
25
|
+
"Backlink",
|
|
26
|
+
"Diff",
|
|
27
|
+
"render",
|
|
28
|
+
]
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class DaleaError(Exception):
|
|
32
|
+
"""Raised on Dalea API or rendering errors."""
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass
|
|
36
|
+
class Section:
|
|
37
|
+
"""A titled section of a page body."""
|
|
38
|
+
|
|
39
|
+
title: str
|
|
40
|
+
body: str
|
|
41
|
+
level: int = 1
|
|
42
|
+
children: list["Section"] = field(default_factory=list)
|
|
43
|
+
|
|
44
|
+
def to_markdown(self) -> str:
|
|
45
|
+
out = f"{'#' * self.level} {self.title}\n\n{self.body}\n"
|
|
46
|
+
for c in self.children:
|
|
47
|
+
out += "\n" + c.to_markdown()
|
|
48
|
+
return out
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass
|
|
52
|
+
class Revision:
|
|
53
|
+
"""A page revision."""
|
|
54
|
+
|
|
55
|
+
id: str
|
|
56
|
+
slug: str
|
|
57
|
+
body: str
|
|
58
|
+
author: str
|
|
59
|
+
created_at: str
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@dataclass
|
|
63
|
+
class Backlink:
|
|
64
|
+
"""An inbound link to a page."""
|
|
65
|
+
|
|
66
|
+
source_slug: str
|
|
67
|
+
context: str
|
|
68
|
+
anchor: str = ""
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
@dataclass
|
|
72
|
+
class Diff:
|
|
73
|
+
"""A diff between two revisions."""
|
|
74
|
+
|
|
75
|
+
added_lines: list[str] = field(default_factory=list)
|
|
76
|
+
removed_lines: list[str] = field(default_factory=list)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
@dataclass
|
|
80
|
+
class Page:
|
|
81
|
+
"""A Dalea wiki page."""
|
|
82
|
+
|
|
83
|
+
slug: str
|
|
84
|
+
title: str
|
|
85
|
+
sections: list[Section] = field(default_factory=list)
|
|
86
|
+
latest: str = "" # revision id
|
|
87
|
+
revisions: list[Revision] = field(default_factory=list)
|
|
88
|
+
|
|
89
|
+
@property
|
|
90
|
+
def body(self) -> str:
|
|
91
|
+
return "\n\n".join(s.to_markdown() for s in self.sections)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
class _Transport(Protocol):
|
|
95
|
+
def request(self, method: str, url: str, *, headers: dict[str, str], body: bytes | None, timeout: float) -> tuple[int, bytes]: ...
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class _HttpTransport:
|
|
99
|
+
def request(self, method, url, *, headers, body, timeout):
|
|
100
|
+
req = urllib.request.Request(url, data=body, method=method, headers=headers)
|
|
101
|
+
try:
|
|
102
|
+
with urllib.request.urlopen(req, timeout=timeout) as resp: # noqa: S310
|
|
103
|
+
return resp.status, resp.read()
|
|
104
|
+
except urllib.error.HTTPError as exc:
|
|
105
|
+
return exc.code, exc.read() if exc.fp else b""
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
class _PagesAPI:
|
|
109
|
+
def __init__(self, root: "DaleaClient") -> None:
|
|
110
|
+
self._root = root
|
|
111
|
+
|
|
112
|
+
def get(self, slug: str) -> Page:
|
|
113
|
+
if not slug:
|
|
114
|
+
raise ValueError("slug is required")
|
|
115
|
+
data = self._root._get(f"/pages/{urllib.parse.quote(slug)}")
|
|
116
|
+
return _page_from(data)
|
|
117
|
+
|
|
118
|
+
def list(self, *, prefix: str | None = None) -> list[Page]:
|
|
119
|
+
params = {"prefix": prefix} if prefix else {}
|
|
120
|
+
q = urllib.parse.urlencode(params)
|
|
121
|
+
data = self._root._get(f"/pages{('?' + q) if q else ''}")
|
|
122
|
+
return [_page_from(p) for p in data.get("items", [])]
|
|
123
|
+
|
|
124
|
+
def stream(self) -> Iterator[Page]:
|
|
125
|
+
cursor: str | None = None
|
|
126
|
+
while True:
|
|
127
|
+
q = f"?cursor={cursor}" if cursor else ""
|
|
128
|
+
data = self._root._get(f"/pages{q}")
|
|
129
|
+
for p in data.get("items", []):
|
|
130
|
+
yield _page_from(p)
|
|
131
|
+
cursor = data.get("next_cursor")
|
|
132
|
+
if not cursor:
|
|
133
|
+
return
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
class _RevisionsAPI:
|
|
137
|
+
def __init__(self, root: "DaleaClient") -> None:
|
|
138
|
+
self._root = root
|
|
139
|
+
|
|
140
|
+
def list(self, slug: str) -> list[Revision]:
|
|
141
|
+
data = self._root._get(f"/pages/{urllib.parse.quote(slug)}/revisions")
|
|
142
|
+
return [Revision(**r) for r in data.get("items", [])]
|
|
143
|
+
|
|
144
|
+
def diff(self, a: Revision, b: Revision) -> Diff:
|
|
145
|
+
"""Compute a line diff between two revisions (stdlib difflib)."""
|
|
146
|
+
import difflib
|
|
147
|
+
a_lines = a.body.splitlines()
|
|
148
|
+
b_lines = b.body.splitlines()
|
|
149
|
+
added: list[str] = []
|
|
150
|
+
removed: list[str] = []
|
|
151
|
+
for line in difflib.unified_diff(a_lines, b_lines, lineterm=""):
|
|
152
|
+
if line.startswith("+") and not line.startswith("+++"):
|
|
153
|
+
added.append(line[1:])
|
|
154
|
+
elif line.startswith("-") and not line.startswith("---"):
|
|
155
|
+
removed.append(line[1:])
|
|
156
|
+
return Diff(added_lines=added, removed_lines=removed)
|
|
157
|
+
|
|
158
|
+
def propose(self, slug: str, body: str) -> Revision:
|
|
159
|
+
if not slug:
|
|
160
|
+
raise ValueError("slug is required")
|
|
161
|
+
data = self._root._post(f"/pages/{urllib.parse.quote(slug)}/propose", {"body": body})
|
|
162
|
+
return Revision(**data)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
class DaleaClient:
|
|
166
|
+
"""Client for the Dalea wiki engine.
|
|
167
|
+
|
|
168
|
+
Args:
|
|
169
|
+
base_url: wiki base URL (defaults to ``DALEA_BASE_URL``).
|
|
170
|
+
token: bearer token (defaults to ``DALEA_TOKEN``).
|
|
171
|
+
timeout: per-request timeout in seconds.
|
|
172
|
+
transport: injectable HTTP transport for tests.
|
|
173
|
+
"""
|
|
174
|
+
|
|
175
|
+
def __init__(
|
|
176
|
+
self,
|
|
177
|
+
*,
|
|
178
|
+
base_url: str | None = None,
|
|
179
|
+
token: str | None = None,
|
|
180
|
+
timeout: float = 30.0,
|
|
181
|
+
transport: _Transport | None = None,
|
|
182
|
+
) -> None:
|
|
183
|
+
self.base_url = base_url or os.environ.get("DALEA_BASE_URL", "https://dalea.wiki")
|
|
184
|
+
self.token = token or os.environ.get("DALEA_TOKEN")
|
|
185
|
+
self.timeout = timeout
|
|
186
|
+
self._transport: _Transport = transport or _HttpTransport()
|
|
187
|
+
self.pages = _PagesAPI(self)
|
|
188
|
+
self.revisions = _RevisionsAPI(self)
|
|
189
|
+
|
|
190
|
+
def _headers(self) -> dict[str, str]:
|
|
191
|
+
h = {"accept": "application/json"}
|
|
192
|
+
if self.token:
|
|
193
|
+
h["authorization"] = f"Bearer {self.token}"
|
|
194
|
+
return h
|
|
195
|
+
|
|
196
|
+
def _request(self, method: str, path: str, json_body: dict[str, Any] | None = None) -> Any:
|
|
197
|
+
url = f"{self.base_url}{path}"
|
|
198
|
+
body = json.dumps(json_body).encode() if json_body is not None else None
|
|
199
|
+
headers = self._headers()
|
|
200
|
+
if body is not None:
|
|
201
|
+
headers["content-type"] = "application/json"
|
|
202
|
+
status, resp = self._transport.request(method, url, headers=headers, body=body, timeout=self.timeout)
|
|
203
|
+
if status >= 400:
|
|
204
|
+
raise DaleaError(f"{method} {path} failed (status {status})")
|
|
205
|
+
if not resp:
|
|
206
|
+
return None
|
|
207
|
+
return json.loads(resp)
|
|
208
|
+
|
|
209
|
+
def _get(self, path: str) -> Any:
|
|
210
|
+
return self._request("GET", path)
|
|
211
|
+
|
|
212
|
+
def _post(self, path: str, body: dict[str, Any]) -> Any:
|
|
213
|
+
return self._request("POST", path, body)
|
|
214
|
+
|
|
215
|
+
def backlinks(self, slug: str) -> list[Backlink]:
|
|
216
|
+
if not slug:
|
|
217
|
+
raise ValueError("slug is required")
|
|
218
|
+
data = self._get(f"/pages/{urllib.parse.quote(slug)}/backlinks")
|
|
219
|
+
return [Backlink(**b) for b in data.get("items", [])]
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def render(page: Page, *, to: str = "markdown") -> str:
|
|
223
|
+
"""Render a ``Page`` to ``markdown``, ``html`` or ``text``."""
|
|
224
|
+
md = page.body
|
|
225
|
+
if to == "markdown":
|
|
226
|
+
return md
|
|
227
|
+
if to == "html":
|
|
228
|
+
return _markdown_to_html(md)
|
|
229
|
+
if to == "text":
|
|
230
|
+
return _strip_markdown(md)
|
|
231
|
+
raise ValueError(f"unknown render target: {to}")
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def _markdown_to_html(md: str) -> str:
|
|
235
|
+
out = []
|
|
236
|
+
for block in md.split("\n\n"):
|
|
237
|
+
if block.startswith("#"):
|
|
238
|
+
level = len(block) - len(block.lstrip("#"))
|
|
239
|
+
text = block.lstrip("# ").strip()
|
|
240
|
+
out.append(f"<h{level}>{text}</h{level}>")
|
|
241
|
+
else:
|
|
242
|
+
out.append(f"<p>{block}</p>")
|
|
243
|
+
return "\n".join(out)
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def _strip_markdown(md: str) -> str:
|
|
247
|
+
out_lines = []
|
|
248
|
+
for line in md.splitlines():
|
|
249
|
+
s = line.lstrip("#").strip()
|
|
250
|
+
if s:
|
|
251
|
+
out_lines.append(s)
|
|
252
|
+
return "\n".join(out_lines)
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def _page_from(data: dict[str, Any]) -> Page:
|
|
256
|
+
sections = [
|
|
257
|
+
Section(title=s.get("title", ""), body=s.get("body", ""), level=s.get("level", 1)) for s in data.get("sections", [])
|
|
258
|
+
]
|
|
259
|
+
revs = [Revision(**r) for r in data.get("revisions", [])]
|
|
260
|
+
return Page(
|
|
261
|
+
slug=data["slug"],
|
|
262
|
+
title=data.get("title", ""),
|
|
263
|
+
sections=sections,
|
|
264
|
+
latest=data.get("latest", revs[-1].id if revs else ""),
|
|
265
|
+
revisions=revs,
|
|
266
|
+
)
|
dalea/cli.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"""CLI for dalea."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import os
|
|
7
|
+
import sys
|
|
8
|
+
|
|
9
|
+
from . import DaleaClient, DaleaError, render
|
|
10
|
+
|
|
11
|
+
__all__ = ["main"]
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _client() -> DaleaClient:
|
|
15
|
+
return DaleaClient()
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _cmd_get(args: argparse.Namespace) -> int:
|
|
19
|
+
try:
|
|
20
|
+
page = _client().pages.get(args.slug)
|
|
21
|
+
print(render(page, to=args.format))
|
|
22
|
+
return 0
|
|
23
|
+
except DaleaError as exc:
|
|
24
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
25
|
+
return 1
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _cmd_backlinks(args: argparse.Namespace) -> int:
|
|
29
|
+
try:
|
|
30
|
+
for b in _client().backlinks(args.slug):
|
|
31
|
+
print(f"{b.source_slug}\t{b.context}")
|
|
32
|
+
return 0
|
|
33
|
+
except DaleaError as exc:
|
|
34
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
35
|
+
return 1
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
39
|
+
parser = argparse.ArgumentParser(prog="dalea", description="Dalea wiki client")
|
|
40
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
41
|
+
|
|
42
|
+
p_g = sub.add_parser("get", help="fetch and render a page")
|
|
43
|
+
p_g.add_argument("slug")
|
|
44
|
+
p_g.add_argument("--format", choices=["markdown", "html", "text"], default="markdown")
|
|
45
|
+
p_g.set_defaults(func=_cmd_get)
|
|
46
|
+
|
|
47
|
+
p_b = sub.add_parser("backlinks", help="list backlinks to a page")
|
|
48
|
+
p_b.add_argument("slug")
|
|
49
|
+
p_b.set_defaults(func=_cmd_backlinks)
|
|
50
|
+
|
|
51
|
+
return parser
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def main(argv: list[str] | None = None) -> int:
|
|
55
|
+
args = build_parser().parse_args(argv)
|
|
56
|
+
return args.func(args)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
if __name__ == "__main__":
|
|
60
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: dalea
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Python client for the Dalea wiki engine: typed pages, revisions, and backlinks.
|
|
5
|
+
Author:
|
|
6
|
+
License: MIT
|
|
7
|
+
Requires-Python: >=3.9
|
|
8
|
+
Description-Content-Type: text/markdown
|
|
9
|
+
|
|
10
|
+
# dalea
|
|
11
|
+
|
|
12
|
+
`dalea` is a Python client for the [Dalea](https://dalea.wiki) wiki engine. It
|
|
13
|
+
turns wiki pages into typed Python objects — pages, sections, backlinks, and
|
|
14
|
+
revision diffs — and gives you a small write surface for scripted edits. It is
|
|
15
|
+
useful for agents that read structured wikis, for CI jobs that reconcile links,
|
|
16
|
+
and for analysts who want to pull a wiki into a notebook.
|
|
17
|
+
|
|
18
|
+
## Features
|
|
19
|
+
|
|
20
|
+
- `Page`, `Section`, `Revision`, and `Backlink` models with `pydantic`.
|
|
21
|
+
- Read pages by slug or id; stream the page tree with a single iterator.
|
|
22
|
+
- Render page bodies to Markdown, HTML, or plain text via pluggable renderers.
|
|
23
|
+
- Compute and apply revision diffs; propose an edit as a pending revision.
|
|
24
|
+
- Backlink graph export to `networkx` for downstream analysis.
|
|
25
|
+
- Built-in retry and `requests.Session` reuse; thread-safe client instance.
|
|
26
|
+
|
|
27
|
+
## Installation
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
pip install dalea
|
|
31
|
+
# extras for rendering and graph export:
|
|
32
|
+
pip install "dalea[render,graph]"
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
## Quick start
|
|
36
|
+
|
|
37
|
+
```python
|
|
38
|
+
from dalea import DaleaClient
|
|
39
|
+
|
|
40
|
+
client = DaleaClient(base_url="https://dalea.wiki", token="ptn_...")
|
|
41
|
+
|
|
42
|
+
page = client.pages.get("python/asyncio")
|
|
43
|
+
print(page.title, len(page.sections))
|
|
44
|
+
|
|
45
|
+
for ref in client.backlinks("python/asyncio"):
|
|
46
|
+
print(ref.source_slug, ref.context)
|
|
47
|
+
|
|
48
|
+
diff = client.revisions.diff(page.latest, page.revisions[-2])
|
|
49
|
+
print(diff.added_lines)
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
## API
|
|
53
|
+
|
|
54
|
+
- `DaleaClient.pages` — `.get(slug)`, `.list(prefix=)`, `.stream()`.
|
|
55
|
+
- `DaleaClient.revisions` — `.list(slug)`, `.diff(a, b)`, `.propose(slug, body)`.
|
|
56
|
+
- `DaleaClient.backlinks(slug)` — return `Backlink` objects with surrounding
|
|
57
|
+
context spans.
|
|
58
|
+
- `dalea.render(page, to="markdown")` — render a `Page` to the target format.
|
|
59
|
+
|
|
60
|
+
## Configuration
|
|
61
|
+
|
|
62
|
+
`DaleaClient` accepts `base_url`, `token`, and `timeout`. The token can also be
|
|
63
|
+
read from `DALEA_TOKEN`, and the base URL from `DALEA_BASE_URL`.
|
|
64
|
+
|
|
65
|
+
## License
|
|
66
|
+
|
|
67
|
+
MIT
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
dalea/__init__.py,sha256=W6P4xt_fBwoAqZEU3JKkogPOM7EeBSKBQL5Xd6W5RY4,8061
|
|
2
|
+
dalea/cli.py,sha256=jNQi_7tUoESijwCyO3fEmCcUk5BLkW-8Xl22sfJUICY,1512
|
|
3
|
+
dalea-0.1.0.dist-info/METADATA,sha256=hnYBThmyje-eyUTxSfPkomWM-xRp933RURwHVKgEEvQ,2093
|
|
4
|
+
dalea-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
5
|
+
dalea-0.1.0.dist-info/entry_points.txt,sha256=Z39rhIDJ6eZiL39TDV-s3CMbkLUuHK0voFEAQiXMXGE,41
|
|
6
|
+
dalea-0.1.0.dist-info/top_level.txt,sha256=lc6mAtofp9XAM_f8aEUHTQ9KacerlZPdlX68M-MEXeM,6
|
|
7
|
+
dalea-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
dalea
|