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/config.py ADDED
@@ -0,0 +1,278 @@
1
+ """User config (corpora, profiles) and per-corpus divan.toml."""
2
+ import functools
3
+ import hashlib
4
+ import os
5
+ import re
6
+ import tomllib
7
+ from dataclasses import dataclass, field
8
+ from pathlib import Path
9
+
10
+ DEFAULT_CONFIG = "~/.config/divan/config.toml"
11
+ DEFAULT_CACHE = "~/.cache/divan"
12
+
13
+
14
+ LEAK_RULES = ("local-path", "private-ip", "email", "secret", "private-corpus-link")
15
+
16
+
17
+ class ConfigError(Exception):
18
+ pass
19
+
20
+
21
+ @functools.lru_cache(maxsize=256)
22
+ def glob_re(g: str) -> re.Pattern:
23
+ if g.endswith("/"):
24
+ g += "**"
25
+ out, i = "", 0
26
+ while i < len(g):
27
+ if g.startswith("**/", i):
28
+ out += "(?:.*/)?"
29
+ i += 3
30
+ elif g.startswith("**", i):
31
+ out += ".*"
32
+ i += 2
33
+ elif g[i] == "*":
34
+ out += "[^/]*"
35
+ i += 1
36
+ elif g[i] == "?":
37
+ out += "[^/]"
38
+ i += 1
39
+ else:
40
+ out += re.escape(g[i])
41
+ i += 1
42
+ return re.compile("^" + out + "$")
43
+
44
+
45
+ @dataclass
46
+ class Collection:
47
+ name: str
48
+ paths: list[str]
49
+ template: str | None = None
50
+ required: list[str] = field(default_factory=list)
51
+ severity: str = "warn"
52
+ weight: float = 1.0
53
+ search: bool = True
54
+ filename: str = "{slug}.md" # what `divan new` calls the file
55
+ dir: str | None = None # folder pattern for `divan new`, relative to the corpus root
56
+
57
+ def __post_init__(self):
58
+ self._res = [glob_re(p) for p in self.paths]
59
+
60
+ def matches(self, rel: str) -> bool:
61
+ return any(r.match(rel) for r in self._res)
62
+
63
+ def base_dir(self) -> str:
64
+ """Static folder prefix of the first path glob (where `divan new` writes)."""
65
+ parts = []
66
+ for seg in self.paths[0].split("/")[:-1]:
67
+ if re.search(r"[*?\[]", seg):
68
+ break
69
+ parts.append(seg)
70
+ return "/".join(parts)
71
+
72
+
73
+ @dataclass
74
+ class CorpusConfig:
75
+ name: str | None = None
76
+ shared: bool = False
77
+ guide: str | None = None
78
+ exclude: list[str] = field(default_factory=list)
79
+ allow_emails: list[str] = field(default_factory=list)
80
+ private_corpora: list[str] = field(default_factory=list)
81
+ severity: dict[str, str] = field(default_factory=dict)
82
+ collections: list[Collection] = field(default_factory=list)
83
+ fingerprint: str = ""
84
+
85
+ def templates(self) -> set[str]:
86
+ return {c.template for c in self.collections if c.template}
87
+
88
+ def excluded(self, rel: str) -> bool:
89
+ return any(glob_re(g).match(rel) for g in self.exclude)
90
+
91
+ def resolve(self, rel: str) -> list[Collection]:
92
+ return [c for c in self.collections if c.matches(rel)]
93
+
94
+ def first(self, rel: str) -> Collection | None:
95
+ r = self.resolve(rel)
96
+ return r[0] if r else None
97
+
98
+ def collection(self, name: str) -> Collection | None:
99
+ return next((c for c in self.collections if c.name == name), None)
100
+
101
+
102
+ def _list(v, what) -> list[str]:
103
+ if v is None:
104
+ return []
105
+ if isinstance(v, str):
106
+ return [v]
107
+ if isinstance(v, list) and all(isinstance(x, str) for x in v):
108
+ return v
109
+ raise ConfigError(f"{what} must be a string or list of strings")
110
+
111
+
112
+ def load_corpus_config(root: Path) -> CorpusConfig:
113
+ p = root / "divan.toml"
114
+ if not p.is_file():
115
+ return CorpusConfig()
116
+ from .safe import contain
117
+ raw = contain(root, p, "divan.toml").read_bytes()
118
+ try:
119
+ data = tomllib.loads(raw.decode("utf-8"))
120
+ except (tomllib.TOMLDecodeError, UnicodeDecodeError) as e:
121
+ raise ConfigError(f"{p}: {e}") from e
122
+ cc = CorpusConfig(fingerprint=hashlib.sha1(raw).hexdigest())
123
+ corpus = data.get("corpus", {})
124
+ cc.name = corpus.get("name")
125
+ cc.shared = bool(corpus.get("shared", False))
126
+ cc.exclude = _list(corpus.get("exclude"), "[corpus] exclude")
127
+ if corpus.get("guide") is not None:
128
+ if not isinstance(corpus["guide"], str):
129
+ raise ConfigError(f"{p}: [corpus] guide must be a file path")
130
+ cc.guide = corpus["guide"]
131
+ chk = data.get("check", {})
132
+ cc.allow_emails = _list(chk.get("allow_emails"), "[check] allow_emails")
133
+ cc.private_corpora = _list(chk.get("private_corpora"), "[check] private_corpora")
134
+ for rule, lvl in chk.get("severity", {}).items():
135
+ if rule not in LEAK_RULES or lvl not in ("error", "warn", "off"):
136
+ raise ConfigError(f"{p}: [check.severity] {rule} = {lvl!r}: rule must be one of "
137
+ f"{', '.join(LEAK_RULES)}; level error, warn or off")
138
+ cc.severity[rule] = lvl
139
+ for i, c in enumerate(data.get("collections", [])):
140
+ if "name" not in c or "path" not in c:
141
+ raise ConfigError(f"{p}: collection #{i + 1} needs name and path")
142
+ sev = c.get("severity", "warn")
143
+ if sev not in ("warn", "error"):
144
+ raise ConfigError(f"{p}: collection {c['name']}: severity must be warn or error")
145
+ cc.collections.append(Collection(
146
+ name=c["name"], paths=_list(c["path"], "path"), template=c.get("template"),
147
+ required=_list(c.get("required"), "required"), severity=sev,
148
+ weight=float(c.get("weight", 1.0)), search=bool(c.get("search", True)),
149
+ filename=c.get("filename", "{slug}.md"), dir=c.get("dir")))
150
+ return cc
151
+
152
+
153
+ @dataclass
154
+ class Corpus:
155
+ name: str
156
+ root: Path
157
+ remote: str | None = None
158
+ branch: str | None = None
159
+ _cfg: CorpusConfig | None = None
160
+
161
+ @property
162
+ def cfg(self) -> CorpusConfig:
163
+ if self._cfg is None:
164
+ self._cfg = load_corpus_config(self.root)
165
+ return self._cfg
166
+
167
+
168
+ def guide_file(self) -> Path | None:
169
+ """The corpus guide: [corpus] guide, else AGENTS.md, CLAUDE.md, README.md (first that exists)."""
170
+ from .safe import contain
171
+ for rel in ([self.cfg.guide] if self.cfg.guide else ["AGENTS.md", "CLAUDE.md", "README.md"]):
172
+ f = self.root / rel
173
+ if f.is_file():
174
+ return contain(self.root, f, "guide")
175
+ if self.cfg.guide:
176
+ raise ConfigError(f"corpus '{self.name}': guide file {rel} does not exist")
177
+ return None
178
+
179
+
180
+ @dataclass
181
+ class Context:
182
+ profile: str
183
+ corpora: dict[str, Corpus]
184
+ write: str | None
185
+ cache_dir: Path
186
+ denylist_file: Path | None = None
187
+ path_mode: bool = False
188
+ vars: dict[str, str] = field(default_factory=dict) # defaults for {placeholders} in `divan new`
189
+
190
+ def select(self, names: list[str] | None) -> list[Corpus]:
191
+ if not names:
192
+ return list(self.corpora.values())
193
+ out = []
194
+ for n in names:
195
+ if n not in self.corpora:
196
+ raise ConfigError(
197
+ f"corpus '{n}' is not in profile '{self.profile}' "
198
+ f"(its corpora: {', '.join(self.corpora) or 'none'})")
199
+ out.append(self.corpora[n])
200
+ return out
201
+
202
+ def shared_names(self) -> set[str]:
203
+ return {n for n, c in self.corpora.items() if c.cfg.shared}
204
+
205
+ def index_path(self, c: Corpus) -> Path:
206
+ """One cache file per (profile, canonical root), never per name."""
207
+ h = hashlib.sha1(f"{self.profile}\0{c.root}".encode()).hexdigest()[:12]
208
+ return self.cache_dir / f"{c.name}-{h}.sqlite"
209
+
210
+
211
+ def _expand(p: str, base: Path | None = None) -> Path:
212
+ q = Path(os.path.expanduser(p))
213
+ return q if q.is_absolute() or base is None else base / q
214
+
215
+
216
+ def _check_cache(cache: Path, corpora: dict) -> None:
217
+ rc = os.path.realpath(cache)
218
+ for c in corpora.values():
219
+ root = os.path.realpath(c.root)
220
+ if rc == root or rc.startswith(root + os.sep):
221
+ raise ConfigError(f"cache directory {cache} is inside corpus '{c.name}'; "
222
+ "set DIVAN_CACHE to a folder outside every corpus")
223
+
224
+
225
+ def load_context(profile: str | None = None, path: str | None = None,
226
+ config: str | None = None, env=os.environ) -> Context:
227
+ if path and (profile or env.get("DIVAN_PROFILE")):
228
+ raise ConfigError("--path cannot be combined with --profile or DIVAN_PROFILE")
229
+ cache = Path(os.path.expanduser(env.get("DIVAN_CACHE", DEFAULT_CACHE)))
230
+ cfg_path = Path(os.path.expanduser(config or env.get("DIVAN_CONFIG", DEFAULT_CONFIG)))
231
+ data: dict = {}
232
+ if cfg_path.is_file():
233
+ try:
234
+ data = tomllib.loads(cfg_path.read_text(encoding="utf-8"))
235
+ except tomllib.TOMLDecodeError as e:
236
+ raise ConfigError(f"{cfg_path}: {e}") from e
237
+ deny = data.get("check", {}).get("denylist_file")
238
+ denylist = _expand(deny, cfg_path.parent) if deny else None
239
+
240
+ if path:
241
+ root = Path(os.path.expanduser(path)).resolve()
242
+ if not root.is_dir():
243
+ raise ConfigError(f"--path {path}: not a directory")
244
+ c = Corpus(root.name, root)
245
+ name = c.cfg.name or root.name
246
+ c.name = re.sub(r"[^\w.-]+", "-", name)
247
+ _check_cache(cache, {c.name: c})
248
+ return Context("(path)", {c.name: c}, c.name, cache, denylist, path_mode=True)
249
+
250
+ if not data.get("corpora"):
251
+ raise ConfigError(
252
+ f"no corpora configured (looked for {cfg_path}); "
253
+ "pass --path DIR to work on one repo directly")
254
+ pname = profile or env.get("DIVAN_PROFILE") or "default"
255
+ profiles = data.get("profiles", {})
256
+ if pname not in profiles:
257
+ if pname != "default":
258
+ raise ConfigError(f"profile '{pname}' not found in {cfg_path}")
259
+ prof = {"corpora": list(data["corpora"]),
260
+ "write": next(iter(data["corpora"])) if len(data["corpora"]) == 1 else None}
261
+ else:
262
+ prof = profiles[pname]
263
+ names = prof.get("corpora", [])
264
+ unknown = [n for n in names if n not in data["corpora"]]
265
+ if unknown:
266
+ raise ConfigError(f"profile '{pname}' lists unknown corpora: {', '.join(unknown)}")
267
+ write = prof.get("write")
268
+ if write and write not in names:
269
+ raise ConfigError(f"profile '{pname}': write corpus '{write}' is not in its corpora list")
270
+ corpora = {}
271
+ for n in names: # only the profile's own roots are ever resolved or touched
272
+ v = data["corpora"][n]
273
+ if "path" not in v:
274
+ raise ConfigError(f"{cfg_path}: corpus '{n}' needs a path")
275
+ corpora[n] = Corpus(n, _expand(v["path"], cfg_path.parent).resolve(), v.get("remote"), v.get("branch"))
276
+ _check_cache(cache, corpora)
277
+ uvars = {str(k): str(v) for k, v in data.get("vars", {}).items()}
278
+ return Context(pname, corpora, write, cache, denylist, vars=uvars)
divan/doc.py ADDED
@@ -0,0 +1,90 @@
1
+ """Markdown documents: frontmatter, title, tags."""
2
+ import json
3
+ import os
4
+ import re
5
+ from dataclasses import dataclass, field
6
+
7
+ import yaml
8
+
9
+
10
+ class _Loader(yaml.SafeLoader):
11
+ """YAML 1.2-style booleans: only true/false, so `no` and `on` stay strings."""
12
+
13
+
14
+ _Loader.yaml_implicit_resolvers = {
15
+ k: [(t, r) for t, r in v if t != "tag:yaml.org,2002:bool"]
16
+ for k, v in yaml.SafeLoader.yaml_implicit_resolvers.items()
17
+ }
18
+ _Loader.add_implicit_resolver(
19
+ "tag:yaml.org,2002:bool", re.compile(r"^(?:true|True|TRUE|false|False|FALSE)$"), list("tTfF")
20
+ )
21
+
22
+ _FM = re.compile(r"\A---[ \t]*\r?\n(.*?)^---[ \t]*\r?$", re.S | re.M)
23
+
24
+
25
+ @dataclass
26
+ class Doc:
27
+ title: str
28
+ tags: str
29
+ fm: dict
30
+ body: str
31
+ has_frontmatter: bool = False
32
+ error: str | None = None
33
+ fm_end_line: int = 0
34
+ extra: dict = field(default_factory=dict)
35
+
36
+
37
+ def _lenient(raw: str) -> dict:
38
+ fm = {}
39
+ for line in raw.splitlines():
40
+ m = re.match(r"([A-Za-z_][\w-]*):\s*(.*)$", line)
41
+ if m:
42
+ fm[m.group(1)] = m.group(2).strip().strip("\"'")
43
+ return fm
44
+
45
+
46
+ def _norm(v):
47
+ if isinstance(v, dict):
48
+ return {str(k): _norm(x) for k, x in v.items()}
49
+ if isinstance(v, (list, tuple)):
50
+ return [_norm(x) for x in v]
51
+ if v is None or isinstance(v, (bool, int, float, str)):
52
+ return v
53
+ return str(v) # dates etc.
54
+
55
+
56
+ def parse(text: str, name: str) -> Doc:
57
+ fm, body, err, has, end_line = {}, text, None, False, 0
58
+ m = _FM.match(text)
59
+ if m:
60
+ has = True
61
+ body = text[m.end():]
62
+ end_line = text.count("\n", 0, m.end()) + 1
63
+ try:
64
+ data = yaml.load(m.group(1), Loader=_Loader)
65
+ if data is None:
66
+ data = {}
67
+ if not isinstance(data, dict):
68
+ raise ValueError("frontmatter is not a mapping")
69
+ fm = _norm(data)
70
+ except Exception as e: # yaml.YAMLError or ValueError
71
+ err = f"frontmatter does not parse: {str(e).splitlines()[0] if str(e) else type(e).__name__}"
72
+ fm = _lenient(m.group(1))
73
+ title = str(fm.get("title") or "").strip()
74
+ if not title:
75
+ h = re.search(r"^#\s+(.+)$", body, re.M)
76
+ title = h.group(1).strip() if h else os.path.splitext(name)[0].replace("-", " ")
77
+ t = fm.get("tags", "")
78
+ if isinstance(t, list):
79
+ t = " ".join(str(x) for x in t)
80
+ tags = re.sub(r"[\[\]\"',]", " ", str(t or ""))
81
+ return Doc(title, tags, fm, body, has, err, end_line)
82
+
83
+
84
+ def fm_json(fm: dict) -> str:
85
+ return json.dumps(fm, default=str, ensure_ascii=False)
86
+
87
+
88
+ def slugify(title: str) -> str:
89
+ s = re.sub(r"[^a-z0-9]+", "-", title.lower()).strip("-")
90
+ return s[:80].rstrip("-")