divan-cli 0.2.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.
divan/index.py ADDED
@@ -0,0 +1,229 @@
1
+ """One FTS5 index per corpus, outside git, updated incrementally under a file lock."""
2
+ import contextlib
3
+ import fcntl
4
+ import os
5
+ import re
6
+ import sqlite3
7
+ from dataclasses import dataclass
8
+ from pathlib import Path
9
+
10
+ from .config import Corpus
11
+ from .doc import fm_json, parse
12
+ from .safe import is_inside
13
+
14
+ SKIP_DIRS = {".git", "node_modules", "__pycache__", ".venv", ".worktrees"}
15
+ ROOT_DOCS = {"README.md", "AGENTS.md", "CLAUDE.md", "CONTRIBUTING.md"} # the corpus's own docs, at its root only
16
+ BODY_CAP = 200_000
17
+ SCHEMA = 6
18
+
19
+
20
+ def is_excluded(rel: str, cfg) -> bool:
21
+ """Skipped by default: the corpus's own root docs and its configured template files.
22
+ A corpus adds more with `[corpus] exclude = [globs]`. Nested README.md files are entries."""
23
+ if rel in ROOT_DOCS or (cfg is not None and (rel in cfg.templates() or cfg.excluded(rel))):
24
+ return True
25
+ return False
26
+
27
+
28
+ def walk_md(root: Path, cfg=None, only_indexable=True):
29
+ for dp, dns, fns in os.walk(root):
30
+ dns[:] = [d for d in dns if d not in SKIP_DIRS
31
+ and (not os.path.islink(os.path.join(dp, d)) or is_inside(root, os.path.join(dp, d)))]
32
+ for fn in fns:
33
+ if fn.endswith(".md"):
34
+ full = Path(dp) / fn
35
+ if only_indexable and is_excluded(full.relative_to(root).as_posix(), cfg):
36
+ continue
37
+ if full.is_symlink() and not is_inside(root, full):
38
+ continue
39
+ yield full.relative_to(root).as_posix(), full
40
+
41
+
42
+ @contextlib.contextmanager
43
+ def locked(db_path: Path):
44
+ db_path.parent.mkdir(parents=True, exist_ok=True)
45
+ with open(str(db_path) + ".lock", "w") as lf:
46
+ fcntl.flock(lf, fcntl.LOCK_EX)
47
+ try:
48
+ yield
49
+ finally:
50
+ fcntl.flock(lf, fcntl.LOCK_UN)
51
+
52
+
53
+ def _connect(path: Path) -> sqlite3.Connection:
54
+ db = sqlite3.connect(path, timeout=60, isolation_level=None)
55
+ db.execute("PRAGMA journal_mode=WAL")
56
+ if db.execute("PRAGMA user_version").fetchone()[0] != SCHEMA:
57
+ db.executescript("DROP TABLE IF EXISTS meta; DROP TABLE IF EXISTS fts; DROP TABLE IF EXISTS kv;")
58
+ db.execute(f"PRAGMA user_version={SCHEMA}")
59
+ db.execute("""CREATE TABLE IF NOT EXISTS meta(
60
+ id INTEGER PRIMARY KEY, path TEXT UNIQUE, mtime_ns INTEGER, size INTEGER,
61
+ title TEXT, fm TEXT, collection TEXT, searchable INTEGER, w REAL)""")
62
+ db.execute("""CREATE VIRTUAL TABLE IF NOT EXISTS fts USING fts5(
63
+ title, tags, body, summary, tokenize='porter unicode61')""")
64
+ db.execute("CREATE TABLE IF NOT EXISTS kv(k TEXT PRIMARY KEY, v TEXT)")
65
+ return db
66
+
67
+
68
+ def _kv(db, k):
69
+ r = db.execute("SELECT v FROM kv WHERE k=?", (k,)).fetchone()
70
+ return r[0] if r else None
71
+
72
+
73
+ def _tag(cfg, rel):
74
+ """(collection name, searchable, weight) for a path."""
75
+ col = cfg.first(rel)
76
+ depth_w = 1.0 if rel.count("/") <= 1 else 0.6 # entries outrank nested evidence files
77
+ if col is None:
78
+ return None, 1, depth_w
79
+ return col.name, int(col.search), depth_w * col.weight
80
+
81
+
82
+ def refresh(db, corpus: Corpus):
83
+ cfg = corpus.cfg
84
+ db.execute("BEGIN IMMEDIATE")
85
+ try:
86
+ if _kv(db, "root") != str(corpus.root):
87
+ db.execute("DELETE FROM meta")
88
+ db.execute("DELETE FROM fts")
89
+ db.execute("INSERT OR REPLACE INTO kv VALUES('root',?)", (str(corpus.root),))
90
+ retag = _kv(db, "cfg") != cfg.fingerprint
91
+ known = {r[0]: r[1:] for r in db.execute("SELECT path,mtime_ns,size,id FROM meta")}
92
+ seen = set()
93
+ for rel, full in walk_md(corpus.root, corpus.cfg):
94
+ try:
95
+ st = full.stat()
96
+ except OSError:
97
+ continue
98
+ seen.add(rel)
99
+ old = known.get(rel)
100
+ col, srch, w = _tag(cfg, rel)
101
+ if old and old[0] == st.st_mtime_ns and old[1] == st.st_size:
102
+ if retag:
103
+ db.execute("UPDATE meta SET collection=?,searchable=?,w=? WHERE id=?",
104
+ (col, srch, w, old[2]))
105
+ continue
106
+ try:
107
+ text = full.read_text(encoding="utf-8", errors="replace")[:BODY_CAP * 2]
108
+ except OSError:
109
+ continue
110
+ d = parse(text, full.name)
111
+ if old:
112
+ db.execute("DELETE FROM fts WHERE rowid=?", (old[2],))
113
+ db.execute("DELETE FROM meta WHERE id=?", (old[2],))
114
+ cur = db.execute(
115
+ "INSERT INTO meta(path,mtime_ns,size,title,fm,collection,searchable,w) "
116
+ "VALUES(?,?,?,?,?,?,?,?)",
117
+ (rel, st.st_mtime_ns, st.st_size, d.title, fm_json(d.fm), col, srch, w))
118
+ summary = str(d.fm.get("summary") or d.fm.get("description") or "")
119
+ db.execute("INSERT INTO fts(rowid,title,tags,body,summary) VALUES(?,?,?,?,?)",
120
+ (cur.lastrowid, d.title, d.tags, d.body[:BODY_CAP], summary))
121
+ for rel, (_, _, rid) in known.items():
122
+ if rel not in seen:
123
+ db.execute("DELETE FROM fts WHERE rowid=?", (rid,))
124
+ db.execute("DELETE FROM meta WHERE id=?", (rid,))
125
+ db.execute("INSERT OR REPLACE INTO kv VALUES('cfg',?)", (cfg.fingerprint,))
126
+ db.execute("INSERT OR REPLACE INTO kv VALUES('updated',strftime('%s','now'))")
127
+ db.execute("COMMIT")
128
+ except BaseException:
129
+ db.execute("ROLLBACK")
130
+ raise
131
+
132
+
133
+ @contextlib.contextmanager
134
+ def session(ctx, corpus: Corpus, rebuild=False):
135
+ """Index brought up to date and queried under one lock: nothing can swap the
136
+ data between the freshness check and the query."""
137
+ path = ctx.index_path(corpus)
138
+ with locked(path):
139
+ db = _connect(path)
140
+ try:
141
+ if rebuild:
142
+ db.execute("DELETE FROM kv WHERE k='root'")
143
+ refresh(db, corpus)
144
+ yield db
145
+ finally:
146
+ db.close()
147
+
148
+
149
+ def terms(words):
150
+ out = []
151
+ for w in words:
152
+ out += re.findall(r"[A-Za-z0-9_]+", w)
153
+ return [t for t in out if len(t) > 1 or t.isdigit()]
154
+
155
+
156
+ @dataclass
157
+ class Hit:
158
+ path: str
159
+ title: str
160
+ snippet: str
161
+ collection: str | None
162
+
163
+
164
+ def search(db, ts, mode, collection=None, include_all=False, n=8, path_prefix=None):
165
+ q = (" AND " if mode == "AND" else " OR ").join(f'"{t}"' for t in ts)
166
+ where, params = "fts MATCH ?", [q]
167
+ if collection:
168
+ where += " AND m.collection = ?"
169
+ params.append(collection)
170
+ elif not include_all:
171
+ where += " AND m.searchable = 1"
172
+ if path_prefix:
173
+ where += " AND m.path LIKE ?"
174
+ params.append(path_prefix.strip("/") + "/%")
175
+ total = db.execute(f"SELECT count(*) FROM fts JOIN meta m ON m.id=fts.rowid WHERE {where}",
176
+ params).fetchone()[0]
177
+ rows = db.execute(
178
+ f"""SELECT m.path, m.title, snippet(fts,2,'[',']','...',10), m.collection
179
+ FROM fts JOIN meta m ON m.id=fts.rowid WHERE {where}
180
+ ORDER BY bm25(fts,6.0,4.0,1.0,3.0) * m.w, m.path LIMIT ?""", params + [n]).fetchall()
181
+ return total, [Hit(*r) for r in rows]
182
+
183
+
184
+ def find(db, words, **kw):
185
+ """divan-find's query handling: all words must match; else fall back to any word."""
186
+ ts = terms(words)
187
+ if not ts:
188
+ return 0, [], False
189
+ total, hits = search(db, ts, "AND", **kw)
190
+ if hits or len(ts) < 2:
191
+ return total, hits, False
192
+ total, hits = search(db, ts, "OR", **kw)
193
+ return total, hits, bool(hits)
194
+
195
+
196
+ def listing(db):
197
+ return db.execute("SELECT path,title,fm,collection,mtime_ns FROM meta ORDER BY path").fetchall()
198
+
199
+
200
+ def status(ctx, corpus: Corpus) -> dict:
201
+ """Index freshness without creating or modifying anything."""
202
+ p = ctx.index_path(corpus)
203
+ out = {"index": str(p), "indexed": 0, "stale": None, "updated": None}
204
+ if not p.exists():
205
+ return out
206
+ try:
207
+ with locked(p):
208
+ db = sqlite3.connect(f"file:{p}?mode=ro", uri=True, timeout=30)
209
+ try:
210
+ known = {r[0]: (r[1], r[2]) for r in db.execute("SELECT path,mtime_ns,size FROM meta")}
211
+ upd = db.execute("SELECT v FROM kv WHERE k='updated'").fetchone()
212
+ root = db.execute("SELECT v FROM kv WHERE k='root'").fetchone()
213
+ finally:
214
+ db.close()
215
+ except sqlite3.Error:
216
+ return out
217
+ if not root or root[0] != str(corpus.root):
218
+ return out
219
+ out["indexed"] = len(known)
220
+ out["updated"] = int(upd[0]) if upd and upd[0] else None
221
+ stale, seen = 0, set()
222
+ for rel, full in walk_md(corpus.root, corpus.cfg):
223
+ seen.add(rel)
224
+ st = full.stat()
225
+ if known.get(rel) != (st.st_mtime_ns, st.st_size):
226
+ stale += 1
227
+ stale += len(set(known) - seen)
228
+ out["stale"] = stale
229
+ return out
divan/join.py ADDED
@@ -0,0 +1,213 @@
1
+ """`divan join`: clone a corpus repo and register it in the user config.
2
+
3
+ The config is edited as text so comments and layout survive; the result is
4
+ re-parsed and compared with the old config before anything is written.
5
+ """
6
+ import json
7
+ import os
8
+ import re
9
+ import subprocess
10
+ import tomllib
11
+ from pathlib import Path
12
+
13
+ from .config import DEFAULT_CONFIG, ConfigError
14
+ from .tomledit import q as _q, set_key, table_span as _table_span, write_checked, locked
15
+
16
+ DEFAULT_HOME = "~/divan"
17
+
18
+
19
+ def default_name(url: str) -> str:
20
+ base = re.split(r"[/:\\]", url.rstrip("/\\"))[-1]
21
+ base = re.sub(r"\.git$", "", base)
22
+ name = re.sub(r"[^\w.-]+", "-", base).strip("-.")
23
+ if not name:
24
+ raise ConfigError(f"cannot derive a corpus name from '{url}'; pass --name")
25
+ return name
26
+
27
+
28
+ def _array_end(text: str, start: int) -> int:
29
+ """Index of the `]` closing the array whose `[` is at `start` (strings and comments aware)."""
30
+ depth, i, n = 0, start, len(text)
31
+ while i < n:
32
+ ch = text[i]
33
+ if ch in "\"'":
34
+ q = ch
35
+ i += 1
36
+ while i < n and text[i] != q:
37
+ i += 2 if (q == '"' and text[i] == "\\") else 1
38
+ elif ch == "#":
39
+ while i < n and text[i] != "\n":
40
+ i += 1
41
+ elif ch == "[":
42
+ depth += 1
43
+ elif ch == "]":
44
+ depth -= 1
45
+ if depth == 0:
46
+ return i
47
+ i += 1
48
+ raise ConfigError("unterminated array in config")
49
+
50
+
51
+ def _add_to_default_profile(text: str, name: str) -> str:
52
+ lines = text.splitlines(keepends=True)
53
+ span = _table_span([l.rstrip("\n") for l in lines], "profiles.default")
54
+ if span is None:
55
+ return text
56
+ h, end = span
57
+ for i in range(h + 1, end):
58
+ m = re.match(r"^(\s*)corpora\s*=\s*\[", lines[i])
59
+ if not m:
60
+ continue
61
+ offset = sum(len(l) for l in lines[:i]) + m.end() - 1
62
+ close = _array_end(text, offset)
63
+ inner = text[offset + 1:close]
64
+ if "\n" in inner and not text[text.rfind("\n", 0, close) + 1:close].strip():
65
+ # multi-line array, `]` on its own line: new element on its own line before it
66
+ at = text.rfind("\n", 0, close) + 1
67
+ prev = text[:at].rstrip("\n").rsplit("\n", 1)[-1]
68
+ pad = re.match(r"\s*", prev).group(0) if prev.strip() not in ("", "[") else " "
69
+ if "#" not in prev and prev.strip() and not prev.rstrip().endswith(("[", ",")):
70
+ head = text[:at].rstrip("\n") + ",\n"
71
+ else:
72
+ head = text[:at]
73
+ return head + f"{pad}{_q(name)},\n" + text[at:]
74
+ body = text[:close].rstrip()
75
+ if inner.strip() == "":
76
+ return text[:offset + 1] + _q(name) + text[close:]
77
+ sep = " " if body.endswith(",") else ", "
78
+ return body + sep + _q(name) + text[close:]
79
+ lines.insert(h + 1, f"corpora = [{_q(name)}]\n")
80
+ return "".join(lines)
81
+
82
+
83
+ def register(cfg: Path, name: str, path: Path, remote: str, author: str | None) -> list[str]:
84
+ """Add the corpus (and default-profile entry, author) to the config; returns what changed."""
85
+ with locked(cfg):
86
+ return _register_locked(cfg, name, path, remote, author)
87
+
88
+
89
+ def _register_locked(cfg: Path, name: str, path: Path, remote: str, author: str | None) -> list[str]:
90
+ text = cfg.read_text(encoding="utf-8") if cfg.is_file() else ""
91
+ try:
92
+ before = tomllib.loads(text)
93
+ except tomllib.TOMLDecodeError as e:
94
+ raise ConfigError(f"{cfg}: {e}") from e
95
+ done = []
96
+ new = text
97
+ existing = before.get("corpora", {}).get(name)
98
+ if existing is not None:
99
+ if Path(os.path.expanduser(existing.get("path", ""))).resolve() != path.resolve():
100
+ raise ConfigError(f"corpus '{name}' is already registered at {existing.get('path')}; "
101
+ "pass --name to register this one under another name")
102
+ else:
103
+ sep = "" if not new or new.endswith("\n\n") else ("\n" if new.endswith("\n") else "\n\n")
104
+ key = name if re.fullmatch(r"[A-Za-z0-9_-]+", name) else _q(name)
105
+ new += sep + f"[corpora.{key}]\npath = {_q(str(path))}\nremote = {_q(remote)}\n"
106
+ done.append("registered corpus")
107
+ prof = before.get("profiles", {}).get("default")
108
+ if prof is not None and name not in prof.get("corpora", []):
109
+ new = _add_to_default_profile(new, name)
110
+ done.append("added to profile 'default'")
111
+ if author and "author" not in before.get("vars", {}):
112
+ new = set_key(new, "vars", "author", _q(author))
113
+ done.append(f"set author = {author}")
114
+ if new == text:
115
+ return done
116
+ exp = json.loads(json.dumps(before))
117
+ exp.setdefault("corpora", {}).setdefault(name, {"path": str(path), "remote": remote})
118
+ if prof is not None and name not in prof.get("corpora", []):
119
+ exp["profiles"]["default"].setdefault("corpora", []).append(name)
120
+ if author and "author" not in before.get("vars", {}):
121
+ exp.setdefault("vars", {})["author"] = author
122
+ write_checked(cfg, text, new, exp)
123
+ return done
124
+
125
+
126
+ def _git(*args, cwd=None, env=None):
127
+ return subprocess.run(["git", *args], cwd=cwd, capture_output=True, text=True, env=env)
128
+
129
+
130
+ _SCP = re.compile(r"^[\w.-]+@[\w][\w.-]*:(?!:)")
131
+
132
+
133
+ def check_url(url: str, allow_local: bool = False) -> None:
134
+ """Only https and ssh, unless the person says --allow-local. Refused here,
135
+ before git runs: `ext::`, `file://`, other transports and bare paths can
136
+ execute commands or read local repositories."""
137
+ if url.startswith("-") or "\n" in url or "\0" in url:
138
+ raise ConfigError("git URL must not start with '-' or contain control characters")
139
+ m = re.match(r"^([A-Za-z][A-Za-z0-9+.-]*)://([^/]*)", url)
140
+ if m:
141
+ scheme, host = m.group(1).lower(), m.group(2).rsplit("@", 1)[-1]
142
+ if scheme in ("https", "ssh") and not host.startswith("-") and host:
143
+ return
144
+ if scheme == "file" and allow_local:
145
+ return
146
+ raise ConfigError(f"'{scheme}://' URLs are not allowed; use https or ssh"
147
+ + (" (or --allow-local for file://)" if scheme == "file" else ""))
148
+ if _SCP.match(url):
149
+ return
150
+ if "::" in url.split("/", 1)[0]:
151
+ raise ConfigError("remote-helper URLs (transport::address) are not allowed")
152
+ if allow_local:
153
+ return
154
+ raise ConfigError("not an https or ssh git URL; local paths need --allow-local")
155
+
156
+
157
+ def clone_env(env, allow_local: bool) -> dict:
158
+ """Environment and flags for a clone that cannot run hooks or use other transports."""
159
+ e = dict(env)
160
+ e["GIT_CONFIG_NOSYSTEM"] = "1"
161
+ e["GIT_ALLOW_PROTOCOL"] = "https:ssh" + (":file" if allow_local else "")
162
+ e["GIT_TERMINAL_PROMPT"] = "0"
163
+ return e
164
+
165
+
166
+ def checkout_env(env) -> dict:
167
+ """Environment for the checkout: no global or system git config at all, so no filter,
168
+ smudge or hook defined there can run on files a corpus chooses."""
169
+ e = dict(env)
170
+ e["GIT_CONFIG_NOSYSTEM"] = "1"
171
+ e["GIT_CONFIG_GLOBAL"] = os.devnull
172
+ e.pop("GIT_CONFIG_COUNT", None)
173
+ return e
174
+
175
+
176
+ def clone_flags(allow_local: bool) -> list[str]:
177
+ flags = ["-c", "core.hooksPath=/dev/null", "-c", "protocol.allow=never",
178
+ "-c", "protocol.https.allow=always", "-c", "protocol.ssh.allow=always"]
179
+ if allow_local:
180
+ flags += ["-c", "protocol.file.allow=always"]
181
+ return flags
182
+
183
+
184
+ def join(url: str, path: str | None, name: str | None, author: str | None, env=os.environ,
185
+ allow_local: bool = False) -> int:
186
+ check_url(url, allow_local)
187
+ name = name or default_name(url)
188
+ if not re.fullmatch(r"[\w.-]+", name):
189
+ raise ConfigError(f"corpus name '{name}' may only use letters, digits, '.', '_' and '-'")
190
+ dest = Path(os.path.expanduser(path or f"{env.get('DIVAN_HOME', DEFAULT_HOME)}/{name}")).resolve()
191
+ cfg = Path(os.path.expanduser(env.get("DIVAN_CONFIG", DEFAULT_CONFIG)))
192
+ if (dest / ".git").exists():
193
+ r = _git("remote", "get-url", "origin", cwd=dest)
194
+ if r.returncode != 0 or r.stdout.strip() != url:
195
+ raise ConfigError(f"{dest} is already a git repo with a different origin; pass --path")
196
+ print(f"using existing clone at {dest}")
197
+ elif dest.exists() and any(dest.iterdir()):
198
+ raise ConfigError(f"{dest} exists and is not empty; pass --path")
199
+ else:
200
+ dest.parent.mkdir(parents=True, exist_ok=True)
201
+ r = _git(*clone_flags(allow_local), "clone", "--no-checkout", "--template=", "--", url, str(dest),
202
+ env=clone_env(env, allow_local))
203
+ if r.returncode != 0:
204
+ raise ConfigError(f"git clone failed: {r.stderr.strip()}")
205
+ # The clone used your git config (credential helpers). The checkout does not: a corpus's
206
+ # .gitattributes could otherwise select a filter your global config defines.
207
+ r = _git("-c", "core.hooksPath=/dev/null", "reset", "-q", "--hard", cwd=dest, env=checkout_env(env))
208
+ if r.returncode != 0:
209
+ raise ConfigError(f"git checkout failed: {r.stderr.strip()}")
210
+ print(f"cloned {url} to {dest}")
211
+ done = register(cfg, name, dest, url, author)
212
+ print(f"{name}: " + ("; ".join(done) if done else "already set up") + f" (config: {cfg})")
213
+ return 0