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/land.py ADDED
@@ -0,0 +1,271 @@
1
+ """divan land: build one commit with exactly the named files on the fetched destination tip, push only that commit, retry on a race."""
2
+ import os
3
+ import re
4
+ import stat
5
+ import subprocess
6
+ import tempfile
7
+ import time
8
+ from pathlib import Path
9
+
10
+ from .check import check_corpus
11
+ from .config import ConfigError, Context, Corpus
12
+ from .safe import contain, is_inside
13
+
14
+
15
+ # Every git process land starts runs with repo hooks off (no pre-push, no reference-transaction ...).
16
+ GIT = ["git", "-c", "core.hooksPath=/dev/null"]
17
+
18
+
19
+ def git(repo: Path, *args, check=True, env=None, input=None) -> subprocess.CompletedProcess:
20
+ r = subprocess.run([*GIT, "--literal-pathspecs", "-C", str(repo), *args], capture_output=True,
21
+ env=env, input=input)
22
+ r.stdout, r.stderr = r.stdout.decode("utf-8", "replace"), r.stderr.decode("utf-8", "replace")
23
+ if check and r.returncode != 0:
24
+ raise ConfigError(f"git {' '.join(args[:2])} failed: {(r.stderr or r.stdout).strip()}")
25
+ return r
26
+
27
+
28
+ def corpus_of(ctx: Context, path: Path) -> tuple[Corpus, str]:
29
+ for c in ctx.corpora.values():
30
+ if is_inside(c.root, path):
31
+ return c, os.path.relpath(os.path.realpath(path), c.root)
32
+ raise ConfigError(f"{path} is not inside any corpus of profile '{ctx.profile}'")
33
+
34
+
35
+ def literal_file(path: Path) -> None:
36
+ """Only existing regular files (not symlinks, directories or globs) can be landed."""
37
+ try:
38
+ st = os.lstat(path)
39
+ except OSError:
40
+ raise ConfigError(f"{path}: no such file (land takes literal paths, not globs)") from None
41
+ if not stat.S_ISREG(st.st_mode):
42
+ raise ConfigError(f"{path}: not a regular file (no directories, globs or symlinks)")
43
+
44
+
45
+ def build_commit(top: Path, parent: str | None, blobs: dict[str, tuple[bytes, str]], message: str) -> str | None:
46
+ """A commit on `parent` that changes only these (path -> bytes, mode). Touches neither the
47
+ working tree, the index nor any ref. Returns None if it would change nothing."""
48
+ gitdir = Path(git(top, "rev-parse", "--absolute-git-dir").stdout.strip())
49
+ with tempfile.TemporaryDirectory(dir=gitdir) as td:
50
+ env = dict(os.environ, GIT_INDEX_FILE=os.path.join(td, "index"))
51
+ if parent:
52
+ git(top, "read-tree", parent, env=env)
53
+ for rel, (data, mode) in blobs.items():
54
+ sha = subprocess.run([*GIT, "-C", str(top), "hash-object", "-w", "--stdin"], input=data,
55
+ capture_output=True, check=True).stdout.decode().strip()
56
+ git(top, "update-index", "--add", "--cacheinfo", f"{mode},{sha},{rel}", env=env)
57
+ tree = git(top, "write-tree", env=env).stdout.strip()
58
+ if parent and tree == git(top, "rev-parse", f"{parent}^{{tree}}").stdout.strip():
59
+ return None
60
+ return git(top, "commit-tree", tree, "-m", message, *(["-p", parent] if parent else [])).stdout.strip()
61
+
62
+
63
+ BRANCH_OK = re.compile(r"[A-Za-z0-9._][A-Za-z0-9._/-]*")
64
+
65
+
66
+ def default_branch(top: Path, remote: str) -> str:
67
+ """The branch the remote's HEAD points at, read from the remote itself. `remote` is the
68
+ validated URL (see one_destination), not a remote name."""
69
+ r = git(top, "ls-remote", "--symref", "--", remote, "HEAD", check=False)
70
+ for line in r.stdout.splitlines():
71
+ if line.startswith("ref:"):
72
+ ref = line.split()[1]
73
+ if ref.startswith("refs/heads/") and BRANCH_OK.fullmatch(ref[len("refs/heads/"):]):
74
+ return ref[len("refs/heads/"):]
75
+ raise ConfigError(f"cannot tell the default branch of remote '{remote}'; "
76
+ "set `branch` for this corpus in your config")
77
+
78
+
79
+ def push_remote(top: Path) -> str:
80
+ """The remote a landing goes to: origin, else the only remote. No network."""
81
+ remotes = git(top, "remote").stdout.split()
82
+ remote = "origin" if "origin" in remotes else (remotes[0] if len(remotes) == 1 else "")
83
+ if remote not in remotes:
84
+ raise ConfigError("cannot tell which remote to push to; name it origin")
85
+ return remote
86
+
87
+
88
+ def destination_branch(top: Path, remote: str, branch: str | None = None) -> str:
89
+ """The branch a landing is pushed to: the corpus config's `branch`, else the remote's
90
+ default branch (this contacts the remote). The local upstream setting never picks it."""
91
+ if branch:
92
+ if not BRANCH_OK.fullmatch(branch):
93
+ raise ConfigError(f"invalid `branch` '{branch}' in the corpus config")
94
+ return branch
95
+ return default_branch(top, remote)
96
+
97
+
98
+ def fetch_tip(top: Path, remote: str, branch: str) -> str:
99
+ tmp = f"refs/divan/tmp-{os.getpid()}"
100
+ r = git(top, "fetch", "-q", "--", remote, f"+refs/heads/{branch}:{tmp}", check=False)
101
+ if r.returncode != 0:
102
+ raise ConfigError(f"cannot fetch {remote}/{branch}: {r.stderr.strip()}")
103
+ try:
104
+ return git(top, "rev-parse", tmp).stdout.strip()
105
+ finally:
106
+ git(top, "update-ref", "-d", tmp, check=False)
107
+
108
+
109
+ def hash_blob(top: Path, data: bytes) -> str:
110
+ return subprocess.run([*GIT, "-C", str(top), "hash-object", "--stdin"], input=data,
111
+ capture_output=True, check=True).stdout.decode().strip()
112
+
113
+
114
+ def entry_at(top: Path, rev: str | None, path: str) -> tuple[str, str] | None:
115
+ """(mode, object id) of `path` in `rev`, or None if absent. Mode counts: a chmod is a change."""
116
+ if not rev:
117
+ return None
118
+ out = git(top, "ls-tree", "-z", rev, "--", path).stdout.split("\0")[0]
119
+ if not out:
120
+ return None
121
+ mode, _type, sha = out.split("\t", 1)[0].split()
122
+ return mode, sha
123
+
124
+
125
+ def one_destination(top: Path, remote: str) -> str:
126
+ """A push must have exactly one receiver, and it must be the place we fetched from.
127
+ Returns that URL: land then talks to this literal URL, never to the remote's name again, so a
128
+ later change to the remote's settings cannot redirect a retry. (URLs are not printed: they can
129
+ carry credentials.)"""
130
+ fetch = git(top, "remote", "get-url", remote).stdout.strip()
131
+ pushes = git(top, "remote", "get-url", "--push", "--all", remote).stdout.splitlines()
132
+ if len(pushes) != 1:
133
+ raise ConfigError(f"remote '{remote}' has more than one push URL; "
134
+ "land needs one destination for fetch and push")
135
+ if pushes[0] != fetch:
136
+ raise ConfigError(f"remote '{remote}': its fetch and push destinations differ; "
137
+ "land needs one destination for fetch and push")
138
+ return pushes[0]
139
+
140
+
141
+ DEFAULT_PORTS = {"ssh": "22", "https": "443", "http": "80", "git": "9418"}
142
+ # Hosts where the ssh and https addresses of a repository are known to reach the same repository.
143
+ # Anywhere else (a self-hosted server) they can be two different services, so they do not match.
144
+ SAME_REPO_HOSTS = {"github.com", "gitlab.com", "bitbucket.org", "codeberg.org"}
145
+
146
+
147
+ def normalize_url(u: str) -> str:
148
+ """Identity of a git address, used to compare the configured remote with the actual one.
149
+
150
+ Known hosts (SAME_REPO_HOSTS): transport, host, port and path; the login user does not count
151
+ and ssh, scp-style and https on default ports are one repository.
152
+ Any other host: the address must be equal as a string after only three changes: the host is
153
+ lower-cased, trailing slashes are dropped, and an explicit default port is dropped. A trailing
154
+ .git is kept there: `notes` and `notes.git` can be two different repositories. So scp-style (a path relative to the login's home) and ssh:// (an absolute path) differ,
155
+ and so do different users, transports and paths."""
156
+ u = u.strip()
157
+ m = re.match(r"^([A-Za-z][A-Za-z0-9+.-]*)://(?:([^@/]*)@)?([^/:]+)(?::(\d+))?/(.*)$", u)
158
+ if m:
159
+ scheme, user, host, port, path = m.groups()
160
+ scheme, style = scheme.lower(), "url"
161
+ else:
162
+ m = re.match(r"^(?:([^@/]*)@)?([^/:]+):(.*)$", u) # scp-style [user@]host:path (ssh, port 22)
163
+ if not m:
164
+ return u.rstrip("/")
165
+ user, host, path = m.groups()
166
+ scheme, port, style = "ssh", None, "scp"
167
+ host = host.lower()
168
+ path = path.strip("/") if style == "url" else path.rstrip("/")
169
+ default = not port or port == DEFAULT_PORTS.get(scheme)
170
+ if host in SAME_REPO_HOSTS and scheme in ("ssh", "https"):
171
+ path = path.removesuffix(".git")
172
+ where = host if default else f"{host}:{port}"
173
+ return f"{'web' if default else scheme}://{where}/{path.strip('/')}"
174
+ who = f"{user}@" if user is not None else ""
175
+ where = host if default else f"{host}:{port}"
176
+ if style == "scp":
177
+ return f"scp:{who}{where}:{path}"
178
+ return f"{scheme}://{who}{where}/{path}"
179
+
180
+
181
+ def matches_configured(url: str, remote: str, configured: str) -> None:
182
+ """The corpus config says where this corpus lives; the git remote is mutable
183
+ (an upstream setting, a checkout's .git/config). Refuse a push elsewhere."""
184
+ if normalize_url(url) != normalize_url(configured):
185
+ raise ConfigError(f"remote '{remote}' does not point at this corpus's configured "
186
+ "remote (divan.toml `remote`); refusing to push")
187
+
188
+
189
+ def _before_push(top: Path, candidate: str) -> None:
190
+ """Seam between building the candidate and pushing it (tests use it to race)."""
191
+
192
+
193
+ def land(ctx: Context, files: list[str], message: str, retries: int = 4, log=print) -> list[str]:
194
+ by_corpus: dict[str, tuple[Corpus, list[str]]] = {}
195
+ for f in files:
196
+ p = Path(f).expanduser().absolute()
197
+ literal_file(p)
198
+ c, rel = corpus_of(ctx, p)
199
+ by_corpus.setdefault(c.name, (c, []))[1].append(rel)
200
+ shas = []
201
+ for c, rels in by_corpus.values():
202
+ data = {r: contain(c.root, c.root / r, "file").read_bytes() for r in rels} # inspected == committed
203
+ if c.cfg.shared:
204
+ findings, _ = check_corpus(ctx, c, rels, read=lambda r: data[r])
205
+ errs = [f for f in findings if f.severity == "error"]
206
+ if errs:
207
+ for f in errs:
208
+ log(f"{c.name}:{f.path}:{f.line}: {f.rule}: {f.message}")
209
+ raise ConfigError(f"refusing to land in shared corpus '{c.name}': divan check has errors")
210
+ top = Path(git(c.root, "rev-parse", "--show-toplevel").stdout.strip())
211
+ blobs = {}
212
+ for r in rels:
213
+ rel_top = os.path.relpath(os.path.realpath(c.root / r), os.path.realpath(top))
214
+ mode = "100755" if os.access(c.root / r, os.X_OK) else "100644"
215
+ blobs[rel_top] = (data[r], mode)
216
+ own = list(blobs)
217
+ head = git(top, "rev-parse", "--verify", "-q", "HEAD", check=False).stdout.strip() or None
218
+ branch = git(top, "rev-parse", "--abbrev-ref", "HEAD").stdout.strip()
219
+ if not git(top, "remote").stdout.split():
220
+ cand = build_commit(top, head, blobs, message)
221
+ if cand is None:
222
+ log(f"{c.name}: nothing to land (files unchanged)")
223
+ continue
224
+ git(top, "update-ref", "-m", "divan land", "HEAD", cand, head or "")
225
+ git(top, "reset", "-q", "--", *own, check=False)
226
+ log(f"{c.name}: committed {cand[:10]} (no remote, not pushed)")
227
+ shas.append(cand)
228
+ continue
229
+ if branch == "HEAD":
230
+ raise ConfigError(f"{c.name}: detached HEAD; check out a branch first")
231
+ remote = push_remote(top)
232
+ url = one_destination(top, remote) # both URL checks come before any contact with the remote
233
+ if c.remote:
234
+ matches_configured(url, remote, c.remote)
235
+ dbranch = destination_branch(top, url, c.branch) # from here on: the validated URL, not the name
236
+ last, base = "", None
237
+ for attempt in range(retries + 1):
238
+ tip = fetch_tip(top, url, dbranch)
239
+ if attempt == 0: # the commit your copy of each note was based on
240
+ mb = git(top, "merge-base", head, tip, check=False) if head else None
241
+ base = mb.stdout.strip() if mb is not None and mb.returncode == 0 else None
242
+ for rel_top, (blob, mode) in blobs.items():
243
+ theirs = entry_at(top, tip, rel_top)
244
+ if theirs != entry_at(top, base, rel_top) and theirs != (mode, hash_blob(top, blob)):
245
+ raise ConfigError(
246
+ f"{c.name}: conflict on {rel_top}: it changed on {remote}/{dbranch} after your copy "
247
+ "was made. Run git pull and redo your change on top of it; nothing was pushed")
248
+ # the candidate sits on the destination tip: only your checked files differ from it
249
+ cand = build_commit(top, tip, blobs, message)
250
+ if cand is None:
251
+ log(f"{c.name}: nothing to land (files unchanged)")
252
+ break
253
+ if git(top, "rev-list", "--count", f"{tip}..{cand}").stdout.strip() != "1":
254
+ raise ConfigError(f"{c.name}: internal error: outgoing range is not exactly one commit")
255
+ _before_push(top, cand)
256
+ # this SHA, never HEAD; the lease makes the receiver check its tip is still `tip` at send time.
257
+ # No tags or submodules ride along, whatever push.followTags or push.recurseSubmodules say.
258
+ ps = git(top, "push", "--no-follow-tags", "--recurse-submodules=no",
259
+ f"--force-with-lease=refs/heads/{dbranch}:{tip}", "--", url,
260
+ f"{cand}:refs/heads/{dbranch}", check=False)
261
+ if ps.returncode == 0:
262
+ log(f"{c.name}: landed {cand} on {remote}/{dbranch}. Your local files were not touched; "
263
+ "run git pull to bring the local branch up to date (if git pull complains that a "
264
+ "landed new file is untracked, run git add on it first: its content already matches)")
265
+ shas.append(cand)
266
+ break
267
+ last = ps.stderr.strip()
268
+ time.sleep(0.3 * (attempt + 1))
269
+ else:
270
+ raise ConfigError(f"{c.name}: push failed after {retries + 1} tries: {last}")
271
+ return shas
divan/privdir.py ADDED
@@ -0,0 +1,53 @@
1
+ """Small helper for folders divan writes into from hooks (session state, the hook log).
2
+
3
+ The folder is opened once with O_DIRECTORY|O_NOFOLLOW and checked on that descriptor (owned by
4
+ you, not writable by others); every later create, stat, list and unlink is relative to the
5
+ descriptor with O_NOFOLLOW, so a symlink swapped in afterwards cannot redirect it.
6
+
7
+ The state and log roots are trusted as named by your environment (XDG_STATE_HOME, DIVAN_HOOK_LOG):
8
+ only the final folder and its contents are pinned, not its ancestors. See SECURITY.md, "Threat model".
9
+ """
10
+ import os
11
+ import stat
12
+ from pathlib import Path
13
+
14
+ DIR_FLAGS = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | getattr(os, "O_CLOEXEC", 0)
15
+
16
+
17
+ def open_dir(path: Path, create: bool, forbidden_mode: int) -> int | None:
18
+ """A descriptor for `path`, or None if it is unsafe or unavailable. A folder divan creates is
19
+ 0700. An existing one is refused when it is a symlink, not owned by you, or has any of the
20
+ permission bits in `forbidden_mode` (0o022: others may write; 0o077: others may do anything)."""
21
+ try:
22
+ try:
23
+ fd = os.open(path, DIR_FLAGS)
24
+ except FileNotFoundError:
25
+ if not create:
26
+ return None
27
+ path.parent.mkdir(parents=True, exist_ok=True)
28
+ try:
29
+ os.mkdir(path, 0o700)
30
+ except FileExistsError:
31
+ pass
32
+ fd = os.open(path, DIR_FLAGS)
33
+ st = os.fstat(fd)
34
+ if not stat.S_ISDIR(st.st_mode) or st.st_uid != os.getuid() or st.st_mode & forbidden_mode:
35
+ os.close(fd)
36
+ return None
37
+ return fd
38
+ except OSError:
39
+ return None
40
+
41
+
42
+ def create_file(fd: int, name: str, excl: bool, mode: int = 0o600) -> int:
43
+ """Create (or, without excl, open) `name` inside the folder; returns the file descriptor."""
44
+ flags = os.O_WRONLY | os.O_CREAT | os.O_NOFOLLOW | getattr(os, "O_CLOEXEC", 0) | (os.O_EXCL if excl else 0)
45
+ return os.open(name, flags, mode, dir_fd=fd)
46
+
47
+
48
+ def exists(fd: int, name: str) -> bool:
49
+ try:
50
+ os.stat(name, dir_fd=fd, follow_symlinks=False)
51
+ return True
52
+ except OSError:
53
+ return False
divan/safe.py ADDED
@@ -0,0 +1,27 @@
1
+ """One boundary for every path divan reads or writes inside a corpus."""
2
+ import os
3
+ from pathlib import Path
4
+
5
+ from .config import ConfigError
6
+
7
+
8
+ def real(p) -> Path:
9
+ return Path(os.path.realpath(p))
10
+
11
+
12
+ def is_inside(root, p) -> bool:
13
+ try:
14
+ real(p).relative_to(real(root))
15
+ return True
16
+ except ValueError:
17
+ return False
18
+
19
+
20
+ def contain(root, p, what: str = "path") -> Path:
21
+ """Return the real path of p, or raise if it resolves outside root."""
22
+ r = real(p)
23
+ try:
24
+ r.relative_to(real(root))
25
+ except ValueError:
26
+ raise ConfigError(f"{what} {p} resolves outside the corpus {root}") from None
27
+ return r
divan/settings.py ADDED
@@ -0,0 +1,123 @@
1
+ """The `[agent]` table in the user config: what the hooks do, and how a person changes it.
2
+
3
+ Precedence: DIVAN_AGENT=off in the environment, then the config file, then the defaults.
4
+ Hooks read this on every call, so an edit takes effect without restarting anything.
5
+ """
6
+ import os
7
+ import tomllib
8
+ from pathlib import Path
9
+
10
+ from .config import DEFAULT_CONFIG, ConfigError
11
+ from .tomledit import locked, q, set_key, write_checked
12
+
13
+ ONOFF = ("on", "off")
14
+ SPEC = { # key: (default, allowed, what it does)
15
+ "enabled": (True, "bool", "master switch for every divan hook"),
16
+ "session_note": (True, "bool", "short search-first/save-after note when a session starts"),
17
+ "search_first": ("deny-once", ("deny-once", "remind", "off"),
18
+ "first web search before `divan find`: deny it once, only remind, or do nothing"),
19
+ "capture_reminder": (True, "bool", "remind to save after the first web research"),
20
+ "compact_reminder": (True, "bool", "before compaction, remind to save unsaved research"),
21
+ "stop_gate": ("block-once", ("block-once", "remind", "off"),
22
+ "unsaved research at stop: block once, only show a note, or do nothing"),
23
+ "gate_headless": (False, "bool", "also block Stop in headless runs such as `claude -p`"),
24
+ "note_extra": ("", "text", "text, or a file path whose text is appended to the session note"),
25
+ }
26
+ TRUE = {"true", "on", "yes", "1"}
27
+ FALSE = {"false", "off", "no", "0"}
28
+ NOTE_EXTRA_MAX = 800
29
+
30
+
31
+ def config_path(env=os.environ) -> Path:
32
+ return Path(os.path.expanduser(env.get("DIVAN_CONFIG", DEFAULT_CONFIG)))
33
+
34
+
35
+ def parse_value(key: str, raw: str):
36
+ """Validate a command-line value for a key; returns the Python value."""
37
+ if key not in SPEC:
38
+ raise ConfigError(f"unknown setting '{key}' (settings: {', '.join(SPEC)})")
39
+ _, allowed, _ = SPEC[key]
40
+ if allowed == "bool":
41
+ v = raw.strip().lower()
42
+ if v in TRUE:
43
+ return True
44
+ if v in FALSE:
45
+ return False
46
+ raise ConfigError(f"{key} is on or off, got '{raw}'")
47
+ if allowed == "text":
48
+ return raw
49
+ if raw not in allowed:
50
+ raise ConfigError(f"{key} must be one of {', '.join(allowed)}, got '{raw}'")
51
+ return raw
52
+
53
+
54
+ def _valid(key: str, v) -> bool:
55
+ _, allowed, _ = SPEC[key]
56
+ if allowed == "bool":
57
+ return isinstance(v, bool)
58
+ if allowed == "text":
59
+ return isinstance(v, str)
60
+ return v in allowed
61
+
62
+
63
+ def _read(cfg: Path) -> dict:
64
+ try:
65
+ return tomllib.loads(cfg.read_text(encoding="utf-8")).get("agent", {}) if cfg.is_file() else {}
66
+ except (OSError, ValueError):
67
+ return {}
68
+
69
+
70
+ def effective(env=os.environ) -> dict:
71
+ """{key: (value, source)}; source is 'default', 'config', 'env DIVAN_AGENT' or 'config (invalid, ignored)'."""
72
+ cfg = _read(config_path(env))
73
+ out = {}
74
+ for k, (default, _, _) in SPEC.items():
75
+ if k in cfg:
76
+ out[k] = (cfg[k], "config") if _valid(k, cfg[k]) else (default, "config (invalid, ignored)")
77
+ else:
78
+ out[k] = (default, "default")
79
+ if env.get("DIVAN_AGENT", "").strip().lower() in FALSE:
80
+ out["enabled"] = (False, "env DIVAN_AGENT")
81
+ return out
82
+
83
+
84
+ def values(env=os.environ) -> dict:
85
+ return {k: v for k, (v, _) in effective(env).items()}
86
+
87
+
88
+ def note_extra_text(value: str, env=os.environ) -> str:
89
+ """note_extra is literal text, or the path of a file (relative to the config's folder)."""
90
+ v = value.strip()
91
+ if not v:
92
+ return ""
93
+ p = Path(os.path.expanduser(v))
94
+ if not p.is_absolute():
95
+ p = config_path(env).parent / p
96
+ try:
97
+ if p.is_file():
98
+ v = p.read_text(encoding="utf-8").strip()
99
+ except OSError:
100
+ return ""
101
+ return v[:NOTE_EXTRA_MAX]
102
+
103
+
104
+ def set_value(key: str, raw: str, env=os.environ):
105
+ value = parse_value(key, raw)
106
+ cfg = config_path(env)
107
+ with locked(cfg):
108
+ _set_value_locked(cfg, key, value)
109
+ return value, cfg
110
+
111
+
112
+ def _set_value_locked(cfg, key, value):
113
+ text = cfg.read_text(encoding="utf-8") if cfg.is_file() else ""
114
+ try:
115
+ before = tomllib.loads(text)
116
+ except tomllib.TOMLDecodeError as e:
117
+ raise ConfigError(f"{cfg}: {e}") from e
118
+ if "agent" in before and not isinstance(before["agent"], dict):
119
+ raise ConfigError(f"{cfg}: [agent] is not a table")
120
+ literal = ("true" if value else "false") if isinstance(value, bool) else q(value)
121
+ new = set_key(text, "agent", key, literal)
122
+ exp = {**before, "agent": {**before.get("agent", {}), key: value}}
123
+ write_checked(cfg, text, new, exp)
divan/tomledit.py ADDED
@@ -0,0 +1,97 @@
1
+ """Text-level TOML edits that keep the rest of the file exactly as it was."""
2
+ import contextlib
3
+ import fcntl
4
+ import json
5
+ import os
6
+ import re
7
+ import time
8
+ import tomllib
9
+ from pathlib import Path
10
+
11
+ from .config import ConfigError
12
+
13
+ HEADER = re.compile(r"^\s*\[\[?\s*([^\]]+?)\s*\]\]?\s*(#.*)?$")
14
+
15
+
16
+ def q(s: str) -> str:
17
+ """A TOML basic string."""
18
+ return json.dumps(s, ensure_ascii=False)
19
+
20
+
21
+ def table_span(lines: list[str], table: str):
22
+ """(header_index, end_index) of `[table]`, end exclusive; None if absent."""
23
+ for i, ln in enumerate(lines):
24
+ m = HEADER.match(ln)
25
+ if m and not ln.lstrip().startswith("[[") and m.group(1).replace(" ", "") == table:
26
+ j = i + 1
27
+ while j < len(lines) and not HEADER.match(lines[j]):
28
+ j += 1
29
+ return i, j
30
+ return None
31
+
32
+
33
+ def set_key(text: str, table: str, key: str, literal: str) -> str:
34
+ """Set `key = literal` inside `[table]`: replace the value in place (keeping any trailing
35
+ comment), else add the key under the table header, else append the table."""
36
+ lines = text.splitlines(keepends=True)
37
+ span = table_span([l.rstrip("\n") for l in lines], table)
38
+ if span is None:
39
+ sep = "" if not text or text.endswith("\n\n") else ("\n" if text.endswith("\n") else "\n\n")
40
+ return text + sep + f"[{table}]\n{key} = {literal}\n"
41
+ h, end = span
42
+ pat = re.compile(rf"^(\s*{re.escape(key)}\s*=\s*)(\"(?:[^\"\\]|\\.)*\"|'[^']*'|[^#\n]*?)(\s*(?:#.*)?)$")
43
+ for i in range(h + 1, end):
44
+ body = lines[i].rstrip("\n")
45
+ m = pat.match(body)
46
+ if m:
47
+ nl = "\n" if lines[i].endswith("\n") else ""
48
+ lines[i] = f"{m.group(1)}{literal}{m.group(3) if m.group(3).strip() else ''}{nl}"
49
+ return "".join(lines)
50
+ if not lines[h].endswith("\n"):
51
+ lines[h] += "\n"
52
+ lines.insert(h + 1, f"{key} = {literal}\n")
53
+ return "".join(lines)
54
+
55
+
56
+ @contextlib.contextmanager
57
+ def locked(path: Path, timeout: float | None = None):
58
+ """Hold an exclusive lock on a sidecar file while a config is read, edited and
59
+ written, so two divan processes cannot both edit the same original text.
60
+ With `timeout` (seconds), give up with a ConfigError instead of waiting forever."""
61
+ path.parent.mkdir(parents=True, exist_ok=True)
62
+ with open(path.with_name(path.name + ".lock"), "a") as lk:
63
+ if timeout is None:
64
+ fcntl.flock(lk, fcntl.LOCK_EX)
65
+ else:
66
+ deadline = time.monotonic() + timeout
67
+ while True:
68
+ try:
69
+ fcntl.flock(lk, fcntl.LOCK_EX | fcntl.LOCK_NB)
70
+ break
71
+ except BlockingIOError:
72
+ if time.monotonic() > deadline:
73
+ raise ConfigError(f"another divan process is holding {path.name}.lock; "
74
+ f"waited {timeout:g}s. Try again when it finishes") from None
75
+ time.sleep(0.05)
76
+ try:
77
+ yield
78
+ finally:
79
+ fcntl.flock(lk, fcntl.LOCK_UN)
80
+
81
+
82
+ def write_checked(path: Path, old: str, new: str, expected: dict) -> None:
83
+ """Write `new` only if it parses to exactly `expected` and the file still holds
84
+ `old` (the text the edit was computed from); atomic replace. Call inside `locked`."""
85
+ current = path.read_text(encoding="utf-8") if path.is_file() else ""
86
+ if current != old:
87
+ raise ConfigError(f"{path} changed while it was being edited; nothing was written, try again")
88
+ try:
89
+ after = tomllib.loads(new)
90
+ except tomllib.TOMLDecodeError as e:
91
+ raise ConfigError(f"could not edit {path} safely ({e}); edit it by hand") from e
92
+ if after != expected:
93
+ raise ConfigError(f"could not edit {path} safely; edit it by hand")
94
+ path.parent.mkdir(parents=True, exist_ok=True)
95
+ tmp = path.with_name(path.name + f".{os.getpid()}.tmp")
96
+ tmp.write_text(new, encoding="utf-8")
97
+ os.replace(tmp, path)
divan/write.py ADDED
@@ -0,0 +1,72 @@
1
+ """divan new: create an entry from a collection template."""
2
+ import datetime
3
+ import re
4
+ from pathlib import Path
5
+
6
+ from .config import ConfigError, Context, Corpus
7
+ from .doc import slugify
8
+ from .safe import contain
9
+
10
+
11
+ def _q(s: str) -> str:
12
+ return '"' + s.replace("\\", "\\\\").replace('"', '\\"') + '"'
13
+
14
+
15
+ def _fill(pattern: str, values: dict[str, str], what: str, as_path: bool) -> str:
16
+ """Replace {name} placeholders. Values that become path parts may not contain a slash or be dots."""
17
+ def sub(m):
18
+ k = m.group(1)
19
+ if k not in values:
20
+ raise ConfigError(f"{what} needs {{{k}}}: set it with --var {k}=VALUE or [vars] {k} in the user config")
21
+ v = values[k]
22
+ if as_path and (not v or "/" in v or "\\" in v or v in (".", "..")):
23
+ raise ConfigError(f"{{{k}}} = {v!r} cannot be part of a path")
24
+ return v
25
+ return re.sub(r"\{(\w+)\}", sub, pattern)
26
+
27
+
28
+ def new_entry(ctx: Context, corpus: Corpus, title: str, collection: str | None, subdir: str | None,
29
+ variables: dict[str, str] | None = None) -> Path:
30
+ cfg = corpus.cfg
31
+ col = None
32
+ if collection:
33
+ col = cfg.collection(collection)
34
+ if col is None:
35
+ known = ", ".join(c.name for c in cfg.collections) or "none declared"
36
+ raise ConfigError(f"corpus '{corpus.name}' has no collection '{collection}' ({known})")
37
+ slug = slugify(title)
38
+ if not slug:
39
+ raise ConfigError("title has no letters or digits to make a filename from")
40
+ date = datetime.date.today().isoformat()
41
+ values = {**ctx.vars, **(variables or {}), "slug": slug, "date": date, "title": title}
42
+ rel_dir = col.base_dir() if col else ""
43
+ if subdir:
44
+ rel_dir = f"{rel_dir}/{subdir}" if rel_dir else subdir
45
+ elif col and col.dir:
46
+ rel_dir = _fill(col.dir, values, f"collection '{col.name}' dir", True)
47
+ parts = [p for p in rel_dir.split("/") if p]
48
+ if ".." in parts or Path(rel_dir).is_absolute():
49
+ raise ConfigError("--dir must stay inside the corpus")
50
+ folder = corpus.root.joinpath(*parts)
51
+ contain(corpus.root, folder, "output folder")
52
+ if col and col.template:
53
+ tpl = contain(corpus.root, corpus.root / col.template, "template")
54
+ if not tpl.is_file():
55
+ raise ConfigError(f"template not found: {tpl}")
56
+ text = tpl.read_text(encoding="utf-8")
57
+ text = re.sub(r"\{\{(\w+)\}\}", lambda m: values.get(m.group(1), m.group(0)), text)
58
+ else:
59
+ text = f"---\ntitle: {_q(title)}\ndate: {date}\n---\n\n# {title}\n\n"
60
+ fname = _fill(col.filename, values, f"collection '{col.name}' filename", True) if col else f"{slug}.md"
61
+ if not fname or "/" in fname or fname in (".", ".."):
62
+ raise ConfigError(f"filename {fname!r} must be a plain file name")
63
+ dest = folder / fname
64
+ contain(corpus.root, dest.parent, "output folder")
65
+ folder.mkdir(parents=True, exist_ok=True)
66
+ contain(corpus.root, folder, "output folder")
67
+ try:
68
+ with open(dest, "x", encoding="utf-8") as fh: # exclusive: never overwrite
69
+ fh.write(text)
70
+ except FileExistsError:
71
+ raise ConfigError(f"refusing to overwrite existing file: {dest}") from None
72
+ return dest