"""Core logic for `hd`: the HedgeDoc <-> local-filesystem tag mirror. Read half: discover notes via /history, cache their content under .hd/notes/.md, and reconcile one symlink per tag under //. Write half: `hd tag`/`hd untag` push a real frontmatter edit back to HedgeDoc over the realtime channel (there is no plain HTTP save endpoint for existing notes). Both halves share one real interprocess lock (ReconcileLock, backed by flock) so a sync pass and a tag write can never step on each other's state.json/symlink updates. """ from __future__ import annotations import fcntl import hashlib import http.cookiejar import json import logging import os import re import stat import time import urllib.error import urllib.parse import urllib.request from dataclasses import dataclass, field from pathlib import Path from typing import Any, Callable, Optional import yaml as pyyaml from hd_client import HedgeDocClient logger = logging.getLogger("hd") CONFIG_NAME = "config.json" COOKIES_NAME = "cookies.json" STATE_NAME = "state.json" NOTES_DIRNAME = "notes" UNTAGGED = "untagged" RECONCILE_LOCK_NAME = ".reconciling.lock" LOCK_FILE_NAME = ".lock" PROBLEMS_NAME = "problems.json" # -------------------------------------------------------------------------- # Config (~/notes/.hd/config.json) -- server URL and, if a login (rather # than a pasted cookie) was used, the email address, kept only so a future # re-login can prompt with it prefilled. No password is ever written here. # -------------------------------------------------------------------------- @dataclass class Config: url: str email: Optional[str] = None @staticmethod def load(hd_dir: Path) -> "Config": path = hd_dir / CONFIG_NAME data = json.loads(path.read_text(encoding="utf-8")) return Config(url=data["url"], email=data.get("email")) def save(self, hd_dir: Path) -> None: path = hd_dir / CONFIG_NAME path.write_text( json.dumps({"url": self.url, "email": self.email}, indent=2), encoding="utf-8", ) os.chmod(path, stat.S_IRUSR | stat.S_IWUSR) # 0600 # -------------------------------------------------------------------------- # Cookies (~/notes/.hd/cookies.json) -- kept separate from config.json: # this is the actually-sensitive credential (a live session token, as good # as a password for as long as it's valid), config.json is not. Mode 0600. # -------------------------------------------------------------------------- @dataclass class Cookies: header: str # a ready-to-send "k1=v1; k2=v2" Cookie header value @staticmethod def load(hd_dir: Path) -> "Cookies": path = hd_dir / COOKIES_NAME data = json.loads(path.read_text(encoding="utf-8")) return Cookies(header=data["cookie"]) def save(self, hd_dir: Path) -> None: path = hd_dir / COOKIES_NAME path.write_text(json.dumps({"cookie": self.header}, indent=2), encoding="utf-8") os.chmod(path, stat.S_IRUSR | stat.S_IWUSR) # 0600 class LoginError(RuntimeError): pass class _NoRedirect(urllib.request.HTTPRedirectHandler): """We only care about the Set-Cookie header on the /login response itself -- not whatever page it redirects to, which may not even exist from this script's point of view. Suppressing redirect-following avoids a working login being misread as a failure just because the redirect target 404s or requires a browser session HedgeDoc doesn't expect a plain HTTP client to have (e.g. CSRF-protected pages).""" def redirect_request(self, *args, **kwargs): return None def login(url: str, email: str, password: str, timeout: float = 15.0) -> str: """POST email+password to HedgeDoc's local-auth /login and return a Cookie header string for the resulting session. /login always responds 302 (a browser-form flow with flash messages, not a JSON API) whether the credentials were right or wrong, so success can't be read off the status code. This does the only reliable thing: perform the login, then immediately probe /history with whatever cookies came back. If that 403s, the credentials were rejected. The session cookie's NAME is deliberately not assumed (default is 'connect.sid' but it's a per-deployment config option) -- whatever the session middleware actually set is what gets captured and reused. """ url = url.rstrip("/") jar = http.cookiejar.CookieJar() opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(jar), _NoRedirect()) body = urllib.parse.urlencode({"email": email, "password": password}).encode("ascii") req = urllib.request.Request(f"{url}/login", data=body, method="POST", headers={"Content-Type": "application/x-www-form-urlencoded"}) try: opener.open(req, timeout=timeout) except urllib.error.HTTPError as exc: # A 3xx here means our own handler declined to follow it -- that's # the expected, successful case (cookie already landed in `jar`). if not (300 <= exc.code < 400): raise LoginError(f"Unexpected response from {url}/login: {exc.code} {exc.reason}") from exc except urllib.error.URLError as exc: raise LoginError(f"Could not reach {url}/login: {exc}") from exc header = "; ".join(f"{c.name}={c.value}" for c in jar if c.value is not None) if not header: raise LoginError( "Login request completed but no session cookie was set -- is " "email/password login enabled on this server? If it uses " "LDAP/OAuth/SAML instead, use 'hdc init --cookie ...' " "with a cookie copied from your browser instead." ) verify_req = urllib.request.Request(f"{url}/history", headers={"Cookie": header}) try: urllib.request.urlopen(verify_req, timeout=timeout) except urllib.error.HTTPError as exc: if exc.code in (401, 403): raise LoginError("Login rejected -- wrong email or password.") from exc raise LoginError(f"Login looked ok but /history returned {exc.code}: {exc.reason}") from exc except urllib.error.URLError as exc: raise LoginError(f"Could not verify login against {url}/history: {exc}") from exc return header # -------------------------------------------------------------------------- # State (~/notes/.hd/state.json) -- what the reconciler believes is true. # The symlink name per tag is stored here, not re-derived from the title on # every run: if it were re-derived, a title change would look exactly like # "old symlink deleted, new symlink created" to a filesystem watcher, which # is indistinguishable from a user-initiated untag+retag. Keeping the name # pinned in state means only an actual title-change code path touches it. # -------------------------------------------------------------------------- @dataclass class NoteState: title: str tags: list[str] = field(default_factory=list) symlinks: dict[str, str] = field(default_factory=dict) # tag -> filename content_hash: Optional[str] = None last_seen_time: Optional[int] = None # /history's `time` field, used to # skip re-fetching /download when nothing has changed server-side. tags_confirmed_stale_at: Optional[int] = None # set by # update_note_tags_locally() to the /history `time` it knew was # STALE (pre-write) at the moment of a direct tag update. reconcile() # checks this: as long as /history's *current* time for this note # still equals this value, /history hasn't caught up to the write yet # (HedgeDoc's own DB-flush lag -- the same class of delay # CHANGES-0.7.15 hit for content), so it skips recomputing this note's # tags/symlinks rather than trusting a snapshot it already knows # predates a confirmed write and clobbering the correct local result. # Cleared (set back to None) once /history's time for this note # actually moves past this value -- at that point /history has # genuinely caught up, and its data (whatever it now says) is trusted # again as normal. def to_json(self) -> dict[str, Any]: return { "title": self.title, "tags": self.tags, "symlinks": self.symlinks, "content_hash": self.content_hash, "last_seen_time": self.last_seen_time, "tags_confirmed_stale_at": self.tags_confirmed_stale_at, } @staticmethod def from_json(d: dict[str, Any]) -> "NoteState": return NoteState( title=d.get("title", ""), tags=list(d.get("tags", [])), symlinks=dict(d.get("symlinks", {})), content_hash=d.get("content_hash"), last_seen_time=d.get("last_seen_time"), tags_confirmed_stale_at=d.get("tags_confirmed_stale_at"), ) @dataclass class State: notes: dict[str, NoteState] = field(default_factory=dict) @staticmethod def load(hd_dir: Path) -> "State": path = hd_dir / STATE_NAME if not path.exists(): return State() data = json.loads(path.read_text(encoding="utf-8")) return State(notes={k: NoteState.from_json(v) for k, v in data.get("notes", {}).items()}) def save(self, hd_dir: Path) -> None: path = hd_dir / STATE_NAME tmp = path.with_suffix(".json.tmp") payload = {"notes": {k: v.to_json() for k, v in self.notes.items()}} tmp.write_text(json.dumps(payload, indent=2, ensure_ascii=False), encoding="utf-8") tmp.replace(path) # atomic on the same filesystem # -------------------------------------------------------------------------- # Filename sanitization # -------------------------------------------------------------------------- _UNSAFE = re.compile(r"[\\/\x00-\x1f]") def sanitize_title(title: str) -> str: name = _UNSAFE.sub("_", title or "").strip().strip(".") name = re.sub(r"\s+", " ", name) if not name: name = "untitled" return name[:120] def unique_name(base: str, id_hint: str, taken: set[str]) -> str: """The note's title, deduped against `taken` (existing filenames in the same tag folder) using a short, stable suffix from the note id -- never a counter, so the same note always gets the same name regardless of what order notes happen to be processed in. No .md extension: these are symlinks named after the note's title, not files -- the thing that actually needs a .md extension is the cache file in .hd/notes/, which already has one.""" if base not in taken: return base suffix = id_hint[-6:] if len(id_hint) >= 6 else id_hint candidate = f"{base}-{suffix}" if candidate not in taken: return candidate # Pathological: even the id-suffixed name collides (two different notes # sharing a 6-char id suffix by coincidence). Fall back to the full id. return f"{base}-{id_hint}" # -------------------------------------------------------------------------- # HTTP: /history (discovery) and //download (content) # -------------------------------------------------------------------------- @dataclass class HistoryEntry: id: str title: str tags: list[str] time: int class HedgeDocSource: """Thin HTTP client for the two read-only endpoints this tool needs. Deliberately not the realtime Socket.IO client -- no live editing here.""" def __init__(self, url: str, cookie: str): self.url = url.rstrip("/") self.cookie = cookie def _get(self, path: str) -> bytes: req = urllib.request.Request(f"{self.url}{path}", headers={"Cookie": self.cookie}) with urllib.request.urlopen(req, timeout=15) as resp: return resp.read() def fetch_history(self) -> list[HistoryEntry]: try: data = json.loads(self._get("/history").decode("utf-8")) except urllib.error.HTTPError as exc: raise RuntimeError( f"GET /history failed: {exc.code} {exc.reason} -- " "cookie likely expired; re-run 'hdc init' to log in again" ) from exc entries = [] for item in data.get("history", []): entries.append(HistoryEntry( id=item["id"], title=item.get("text") or "Untitled", tags=list(item.get("tags") or []), time=item.get("time", 0), )) return entries def fetch_content(self, note_id: str) -> str: from urllib.parse import quote raw = self._get(f"/{quote(note_id, safe='')}/download") return raw.decode("utf-8") def content_hash(text: str) -> str: return "sha256:" + hashlib.sha256(text.encode("utf-8")).hexdigest() # -------------------------------------------------------------------------- # Reconciliation # -------------------------------------------------------------------------- @dataclass class ReconcileResult: notes_updated: list[str] = field(default_factory=list) notes_unchanged: list[str] = field(default_factory=list) notes_removed: list[str] = field(default_factory=list) symlinks_created: list[str] = field(default_factory=list) symlinks_removed: list[str] = field(default_factory=list) problems: list["Problem"] = field(default_factory=list) # -------------------------------------------------------------------------- # Konsistenskontroller: things the reconciler notices but can't safely fix # on its own -- a directory where a tag symlink should be, a plain file # where cp-without--P left one, a symlink pointing at nothing or at # something outside .hd/notes/. Written to .hd/problems.json so hd-joe can # print them at every startup without re-scanning the whole tree itself. # -------------------------------------------------------------------------- @dataclass class Problem: kind: str # "nested_dir" | "stray_file" | "broken_symlink" | "foreign_symlink" path: str # relative to root detail: str = "" # e.g. matching note id(s) for a stray file, via checksum def to_json(self) -> dict[str, Any]: return {"kind": self.kind, "path": self.path, "detail": self.detail} @staticmethod def from_json(d: dict[str, Any]) -> "Problem": return Problem(kind=d["kind"], path=d["path"], detail=d.get("detail", "")) def __str__(self) -> str: messages = { "nested_dir": f"{self.path}/ is a real directory where a tag symlink was expected " f"(nested tag folders aren't supported)", "stray_file": f"{self.path} is a plain file, not a symlink -- {self.detail}" if self.detail else f"{self.path} is a plain file, not a symlink, and its content doesn't " f"match any known note (server-side edit since last sync, or not from hd at all)", "broken_symlink": f"{self.path} points at a note that no longer exists in the cache", "foreign_symlink": f"{self.path} is a symlink pointing outside .hd/notes/ -- created by hand?", } return messages.get(self.kind, f"{self.kind}: {self.path}") def save_problems(hd_dir: Path, problems: list[Problem]) -> None: path = hd_dir / PROBLEMS_NAME tmp = path.with_suffix(".json.tmp") tmp.write_text(json.dumps([p.to_json() for p in problems], indent=2, ensure_ascii=False), encoding="utf-8") tmp.replace(path) def load_problems(hd_dir: Path) -> list[Problem]: path = hd_dir / PROBLEMS_NAME if not path.exists(): return [] return [Problem.from_json(d) for d in json.loads(path.read_text(encoding="utf-8"))] def detect_problems(root: Path, state: State) -> list[Problem]: """Walk every top-level entry under root (skipping .hd itself) and flag anything that isn't a healthy symlink into .hd/notes/. Cheap: one level of tag directories, one listdir each -- meant to run on every sync pass, not just on demand.""" hd_dir = root / ".hd" notes_dir = hd_dir / NOTES_DIRNAME problems: list[Problem] = [] # checksum -> note id, for identifying stray files hash_to_id = {n.content_hash: nid for nid, n in state.notes.items() if n.content_hash} if not root.exists(): return problems for tag_dir in sorted(root.iterdir()): if tag_dir.name == ".hd" or not tag_dir.is_dir() or tag_dir.is_symlink(): continue for entry in sorted(tag_dir.iterdir()): rel = str(entry.relative_to(root)) if entry.is_symlink(): target = entry.resolve() if not target.exists(): problems.append(Problem("broken_symlink", rel)) elif notes_dir.resolve() not in target.parents: problems.append(Problem("foreign_symlink", rel)) # else: healthy, matches a note in .hd/notes/ -- nothing to flag elif entry.is_dir(): problems.append(Problem("nested_dir", rel)) elif entry.is_file(): try: file_hash = content_hash(entry.read_text(encoding="utf-8")) except (OSError, UnicodeDecodeError): file_hash = None match = hash_to_id.get(file_hash) if file_hash else None if match: detail = (f"content matches note {match!r}, run " f"'hdc tag {match} {tag_dir.name} --fix-stray {rel}' to replace it with the real symlink") else: detail = "" problems.append(Problem("stray_file", rel, detail)) return problems class ReconcileLock: """Real mutual exclusion (fcntl.flock on .hd/.lock) between hd sync and hd tag/untag, so a pull-reconciliation and a tag write can never interleave their state.json/symlink updates. Also writes the human-readable .reconciling.lock marker (with a timestamp) for the benefit of a future filesystem watcher, which needs to tell "the reconciler just touched this" apart from "the user just touched this" -- the same problem hd_ipc_applying() solves for JOE. Blocks (does not fail fast) if another process holds it; every operation that takes this lock is short-lived (a sync pass or a single tag write), so a bounded wait is the right default over a race-prone "fail if busy". """ def __init__(self, hd_dir: Path): self.hd_dir = hd_dir self.lock_path = hd_dir / LOCK_FILE_NAME self.marker_path = hd_dir / RECONCILE_LOCK_NAME self._fd = None def __enter__(self): self.hd_dir.mkdir(parents=True, exist_ok=True) self._fd = os.open(self.lock_path, os.O_CREAT | os.O_RDWR, 0o600) fcntl.flock(self._fd, fcntl.LOCK_EX) # blocks until available self.marker_path.write_text(str(time.time()), encoding="utf-8") return self def __exit__(self, *exc): try: self.marker_path.unlink() except FileNotFoundError: pass if self._fd is not None: fcntl.flock(self._fd, fcntl.LOCK_UN) os.close(self._fd) self._fd = None def _sync_note_symlinks( root: Path, note_id: str, title: str, tags: list[str], note_path: Path, old_symlinks: dict[str, str], title_changed: bool, ) -> tuple[dict[str, str], list[str], list[str]]: """Create/remove symlinks so exactly one exists per tag in `tags` (or UNTAGGED if empty), pointing at note_path. Returns (new_symlinks, created_paths, removed_paths). Shared by reconcile() (tags come from /history, which can lag a live write by a few seconds -- HedgeDoc's own DB-flush delay, the same class of staleness CHANGES-0.7.15 hit for content) and update_note_tags_locally() (tags come from a write_tags() call's own return value instead, confirmed correct immediately -- sidesteps that lag entirely for the note that was actually just changed). """ new_symlinks: dict[str, str] = {} created: list[str] = [] removed: list[str] = [] effective_tags = tags if tags else [UNTAGGED] for tag in effective_tags: tag_dir = root / tag tag_dir.mkdir(parents=True, exist_ok=True) existing_name = old_symlinks.get(tag) if existing_name and not title_changed and (tag_dir / existing_name).is_symlink(): new_symlinks[tag] = existing_name continue # New tag for this note, or title changed (rename), or the # symlink is missing/broken -- (re)create it. taken = {p.name for p in tag_dir.iterdir()} if tag_dir.exists() else set() if existing_name: taken.discard(existing_name) name = unique_name(sanitize_title(title), note_id, taken) target = os.path.relpath(note_path, tag_dir) link_path = tag_dir / name if existing_name and existing_name != name: old_link = tag_dir / existing_name if old_link.is_symlink(): old_link.unlink() removed.append(str(old_link)) if link_path.is_symlink() or link_path.exists(): link_path.unlink() link_path.symlink_to(target) new_symlinks[tag] = name created.append(str(link_path)) # --- prune symlinks for tags this note no longer has --- for tag, name in old_symlinks.items(): if tag not in new_symlinks: old_link = root / tag / name if old_link.is_symlink(): old_link.unlink() removed.append(str(old_link)) return new_symlinks, created, removed def update_note_tags_locally(hd_root: Path, note_id: str, new_tags: list[str]) -> bool: """After write_tags() confirms a tag change, apply the resulting symlink changes directly using that known-correct tag list -- instead of relying on the next reconcile() pass, which reads tags from /history and can see a stale (pre-write) list for a few seconds after a successful write. Confirmed happening in practice: 'hdc untag' immediately re-syncing via the normal path left a stale symlink in place for several seconds after the write itself had already succeeded. No-op (returns False) if the note isn't in state.json yet -- same reasoning as update_note_cache(): nothing here can safely guess at content or other metadata a real reconcile() pass would fill in from an actual /history entry. Title is taken from what's already in state.json (unaffected by a tag change), so this never invents one. """ hd_dir = hd_root / ".hd" notes_dir = hd_dir / NOTES_DIRNAME with ReconcileLock(hd_dir): state = State.load(hd_dir) ns = state.notes.get(note_id) if ns is None: return False note_path = notes_dir / f"{note_id}.md" old_symlinks = dict(ns.symlinks) new_symlinks, _created, _removed = _sync_note_symlinks( hd_root, note_id, ns.title, new_tags, note_path, old_symlinks, title_changed=False, ) # Matches reconcile()'s own convention (see its `tags = entry.tags # if entry.tags else [UNTAGGED]`): state.json's tags list is never # actually empty, an untagged note is recorded as [UNTAGGED] -- # new_symlinks' keys are exactly that already-substituted list, # since _sync_note_symlinks makes the same substitution internally. ns.tags = list(new_symlinks.keys()) ns.symlinks = new_symlinks # Record the /history time we know is stale (pre-write) so # reconcile() -- run immediately after this, still against # possibly-unflushed /history -- doesn't clobber this correct # result with an older snapshot it can recognize as older. See # NoteState.tags_confirmed_stale_at's docstring for the full story # (found the hard way: the first version of this fix worked in # isolation but was silently undone by the very next reconcile() # call in the same command). ns.tags_confirmed_stale_at = ns.last_seen_time state.save(hd_dir) return True def reconcile(root: Path, source: HedgeDocSource, state: State) -> ReconcileResult: hd_dir = root / ".hd" notes_dir = hd_dir / NOTES_DIRNAME notes_dir.mkdir(parents=True, exist_ok=True) result = ReconcileResult() with ReconcileLock(hd_dir): history = source.fetch_history() seen_ids = set() for entry in history: seen_ids.add(entry.id) prev = state.notes.get(entry.id) tags = entry.tags if entry.tags else [UNTAGGED] # --- content cache --- # /history's `time` field works as a cheap change indicator: skip # the /download round trip entirely when it hasn't moved since # last sync and we already have a cached copy on disk. note_path = notes_dir / f"{entry.id}.md" need_fetch = ( prev is None or prev.last_seen_time != entry.time or prev.content_hash is None or not note_path.exists() ) text = None fetch_failed = False if need_fetch: try: text = source.fetch_content(entry.id) except Exception as exc: logger.error("Could not fetch content for %s (%s): %s", entry.id, entry.title, exc) fetch_failed = True if prev is None: continue # never seen before and unreachable -- skip entirely new_hash = content_hash(text) if text is not None else (prev.content_hash if prev else None) content_changed = text is not None and (prev is None or prev.content_hash != new_hash) if content_changed: note_path.write_text(text, encoding="utf-8") try: os.chmod(note_path, stat.S_IRUSR | stat.S_IWUSR) # 0600: cache, not for editing except OSError: pass # A failed fetch means we don't actually know the server's # current time for this note -- keep the old value so the next # sync retries instead of wrongly believing it's up to date. new_last_seen_time = (prev.last_seen_time if (prev and fetch_failed) else entry.time) # --- desired symlinks for this note --- title = entry.title old_symlinks = dict(prev.symlinks) if prev else {} title_changed = prev is not None and prev.title != title # /history hasn't caught up to a direct tag update yet (see # NoteState.tags_confirmed_stale_at) -- this exact `entry.time` # is one we already know predates that write. Trust the local # result instead of clobbering it with a snapshot recognizably # older than what's already correct on disk. tags_stale = ( prev is not None and prev.tags_confirmed_stale_at is not None and entry.time == prev.tags_confirmed_stale_at ) if tags_stale: new_symlinks = old_symlinks tags = list(prev.tags) new_tags_confirmed_stale_at = prev.tags_confirmed_stale_at else: new_symlinks, created, removed = _sync_note_symlinks( root, entry.id, title, tags, note_path, old_symlinks, title_changed, ) result.symlinks_created.extend(created) result.symlinks_removed.extend(removed) # /history has moved past the known-stale time (whether to # exactly the value the write produced, or further, from # another edit since) -- it's caught up, trust it normally # again from here on. new_tags_confirmed_stale_at = None state.notes[entry.id] = NoteState( title=title, tags=tags, symlinks=new_symlinks, content_hash=new_hash if new_hash is not None else (prev.content_hash if prev else None), last_seen_time=new_last_seen_time, tags_confirmed_stale_at=new_tags_confirmed_stale_at, ) (result.notes_updated if (content_changed or title_changed or old_symlinks != new_symlinks) else result.notes_unchanged).append(entry.id) # --- prune notes that disappeared from /history entirely --- for note_id in list(state.notes.keys()): if note_id in seen_ids: continue prev = state.notes.pop(note_id) for tag, name in prev.symlinks.items(): link = root / tag / name if link.is_symlink(): link.unlink() result.symlinks_removed.append(str(link)) note_path = notes_dir / f"{note_id}.md" if note_path.exists(): note_path.unlink() result.notes_removed.append(note_id) result.problems = detect_problems(root, state) save_problems(hd_dir, result.problems) return result # -------------------------------------------------------------------------- # Tag writing: hd tag / hd untag. The only place in this codebase that # writes to HedgeDoc. There is no plain HTTP save endpoint for existing # notes (confirmed against lib/web/note/router.js), so this opens a # short-lived realtime connection, fetches the document FRESH (never from # the local .hd/notes/ cache, which can be hours stale), edits only the # frontmatter tags line, and closes again. # -------------------------------------------------------------------------- # Mirrors HedgeDoc's own splitFrontmatter() exactly (lib/models/note.js): # the document must start with literal "---", and the block is closed by # the first "\n---" or "\n..." found anywhere after that. _FRONTMATTER_CLOSE_RE = re.compile(r"\n(\.\.\.|---)") class FrontmatterError(RuntimeError): pass def parse_frontmatter(text: str) -> Optional[dict[str, Any]]: if text[:3] != "---": return None m = _FRONTMATTER_CLOSE_RE.search(text) if not m: return None return { "yaml_str": text[:m.start()], # includes the opening "---" line "yaml_end": m.start(), # char index; the edit region is [0, yaml_end) "body_start": m.end(), } def parse_current_tags(meta: dict) -> list[str]: """Mirror HedgeDoc's Note.extractNoteTags: a comma-separated string (or bare number), deduplicated preserving first-seen order. A YAML list is NOT accepted here either -- matches the server, which silently ignores non-string/number `tags` values.""" raw = meta.get("tags") if not isinstance(raw, (str, int, float)) or isinstance(raw, bool): return [] tags: list[str] = [] for part in str(raw).split(","): part = part.strip() if part and part not in tags: tags.append(part) return tags def compute_tag_patch(text: str, new_tags: list[str]) -> tuple[int, int, str]: """Return (start, end, replacement) -- Python character indices into `text` -- for the minimal edit that sets the frontmatter tags to exactly new_tags, touching nothing else. Always writes the comma-string form (a YAML list is silently ignored by the server, verified against lib/models/note.js).""" tags_str = ", ".join(new_tags) fm = parse_frontmatter(text) if fm is None: # No frontmatter at all: insert a fresh block. A pure insert at 0 # is a (0, 0, ...) patch -- same shape, simpler for the caller. block = f"---\ntags: {tags_str}\n---\n" if new_tags else "---\ntags:\n---\n" return (0, 0, block) try: meta = pyyaml.safe_load(fm["yaml_str"]) except pyyaml.YAMLError as exc: raise FrontmatterError( f"Existing frontmatter isn't valid YAML -- refusing to touch it " f"rather than risk destroying it: {exc}" ) from exc if meta is None: meta = {} if not isinstance(meta, dict): raise FrontmatterError( "Existing frontmatter doesn't parse as a mapping (key: value pairs) " "-- refusing to touch it rather than risk destroying it." ) if new_tags: meta["tags"] = tags_str else: meta.pop("tags", None) dumped = pyyaml.safe_dump(meta, default_flow_style=False, sort_keys=False, allow_unicode=True).rstrip("\n") new_yaml_str = "---\n" + dumped if dumped else "---" return (0, fm["yaml_end"], new_yaml_str) def resolve_note_ref(root: Path, state: State, ref: str, cwd: Optional[Path] = None) -> str: """Accept a note id, a path to one of its existing symlinks, or a title (case-insensitive, must be unique) -- whichever the user typed. A relative path (including a bare name with no '/' at all, like 'FOI') is resolved against `cwd` (the real process cwd by default) the same way a shell resolves any other relative argument -- 'FOI' means the symlink named FOI in the directory you're standing in, '../work/FOI' means the one in ../work, never a title search that could silently land on some OTHER note sharing that title somewhere else in the tree. This takes priority over the title-search fallback below: if a symlink genuinely exists at the resolved path, that note wins even if a same-named title also exists elsewhere. Previously this resolved relative paths against `root` instead of cwd, which made '../work/FOI' resolve wrongly (relative to root's parent, not the directory you were actually standing in) and gave a bare name like 'FOI' no cwd-scoping at all -- it just fell straight through to the global title search. """ if cwd is None: cwd = Path.cwd() candidate = Path(ref).expanduser() p = candidate if candidate.is_absolute() else (cwd / candidate) if p.is_symlink(): target = p.resolve() if target.suffix == ".md" and target.parent == (root / ".hd" / NOTES_DIRNAME).resolve(): return target.stem if ref in state.notes: return ref matches = [nid for nid, n in state.notes.items() if n.title.lower() == ref.lower()] if len(matches) == 1: return matches[0] if len(matches) > 1: raise ValueError(f"{len(matches)} notes are titled {ref!r} ({', '.join(matches)}) -- use the note id instead") raise ValueError(f"No known note matches {ref!r} (not an id, a symlink path, or a unique title)") def write_tags( url: str, cookie: str, note_id: str, mutate: Callable[[list[str]], list[str]], timeout: float = 15.0, ) -> list[str]: """Connect, fetch the document FRESH, apply `mutate` to its current frontmatter tags, push the minimal edit, wait for it to be acknowledged, and disconnect. Returns the new tag list. Deliberately a single attempt, not a manual "retry if revision moved" loop: revision always advances after OUR OWN op is acked, so comparing it to the pre-send value can't distinguish a concurrent edit from our own success -- an earlier version of this function got that wrong and replayed mutate() a second time on top of its own already-applied change (caught by test_hd_write.py). A genuinely concurrent edit to the frontmatter tags is still handled correctly at the byte level by the normal OT transform in send_operation/replace(); what isn't handled is a *semantic* merge of two simultaneous tag changes, which is a small residual risk documented rather than papered over with a broken retry. """ client = HedgeDocClient(url, note_id, cookie=cookie, verbose=False) client.connect() try: doc = client.wait_ready(timeout) meta = parse_frontmatter(doc.text) current_tags = parse_current_tags(pyyaml.safe_load(meta["yaml_str"]) or {}) if meta else [] new_tags = mutate(current_tags) if new_tags == current_tags: return current_tags # nothing to do -- no network write at all start, end, replacement = compute_tag_patch(doc.text, new_tags) client.replace(start, end, replacement) deadline = time.monotonic() + timeout while client.pending_count > 0: if time.monotonic() >= deadline: raise TimeoutError( f"Tag write to {note_id} was not acknowledged within {timeout}s" ) time.sleep(0.05) return new_tags finally: client.close() # -------------------------------------------------------------------------- # hd-joe integration: discovering an hd-managed tree from wherever hd-joe # was launched (git-style upward search), deriving a tag from how deep that # is under the root, and creating a brand-new note when the name given # doesn't match an existing symlink. Everything here is read/create-only # from HedgeDoc's point of view -- editing an existing note is still # hd_client.HedgeDocClient's job, started separately once a note id is # known. # -------------------------------------------------------------------------- def find_hd_root(start: Path) -> Optional[Path]: """Climb from `start` looking for a `.hd` directory, git-style. Returns the directory that CONTAINS .hd (the notes root), or None if there isn't one anywhere above `start`.""" current = start.resolve() while True: if (current / ".hd").is_dir(): return current parent = current.parent if parent == current: # reached the filesystem root return None current = parent def tag_from_cwd(root: Path, cwd: Path) -> tuple[Optional[str], Optional[str]]: """Derive a single tag from how deep `cwd` sits under `root`. Returns (tag, error). Nested tag folders were deliberately dropped (see the manual) -- exactly one level is supported, so anything deeper is an error here rather than a silently-accepted compound tag. `tag` is None with no error when `cwd` IS `root` (untagged) or when `cwd` doesn't resolve under `root` at all as a normal path relationship worth acting on -- callers decide what untagged should mean for their operation. """ cwd = cwd.resolve() root = root.resolve() try: rel = cwd.relative_to(root) except ValueError: return None, f"{cwd} is not inside {root}" parts = rel.parts if parts and parts[0] == ".hd": return None, f"{cwd} is inside .hd/ -- hd-joe shouldn't be run from there" if len(parts) == 0: return None, None # at the root itself -- untagged if len(parts) == 1: return parts[0], None return None, ( f"{cwd} is nested {len(parts)} levels under {root} -- nested tag " f"folders aren't supported. Run hd-joe from directly inside one tag " f"folder (e.g. {root / parts[0]})." ) def create_note(url: str, cookie: str, title: str, tags: list[str], timeout: float = 15.0) -> tuple[str, str]: """POST /new with a frontmatter block already containing title+tags, and return (note_id, initial_text). Mirrors login()'s approach to a route that always redirects rather than returning JSON (confirmed against lib/web/note/util.js's newNote(): it redirects to /, the SAME id form /history's `id` field already uses -- no translation needed between creation and the rest of this codebase). """ url = url.rstrip("/") meta: dict[str, Any] = {"title": title} if tags: meta["tags"] = ", ".join(tags) dumped = pyyaml.safe_dump(meta, default_flow_style=False, sort_keys=False, allow_unicode=True).rstrip("\n") content = f"---\n{dumped}\n---\n\n" opener = urllib.request.build_opener(_NoRedirect()) req = urllib.request.Request( f"{url}/new", data=content.encode("utf-8"), method="POST", headers={"Content-Type": "text/markdown; charset=utf-8", "Cookie": cookie}, ) try: opener.open(req, timeout=timeout) except urllib.error.HTTPError as exc: if not (300 <= exc.code < 400): raise RuntimeError(f"POST /new returned {exc.code}: {exc.reason}") from exc location = exc.headers.get("Location") if not location: raise RuntimeError("POST /new redirected but sent no Location header") note_id = location.rstrip("/").rsplit("/", 1)[-1] return note_id, content except urllib.error.URLError as exc: raise RuntimeError(f"Could not reach {url}/new: {exc}") from exc raise RuntimeError("POST /new succeeded outright instead of redirecting -- unexpected server behavior") def register_note(root: Path, state: State, note_id: str, title: str, tags: list[str], text: str) -> NoteState: """Insert a brand-new note into the local cache/state/symlinks without waiting for the next full /history-driven sync. Caller is responsible for holding ReconcileLock around this (and around create_note(), so the two happen as one atomic-from-the-outside step) -- this function itself only touches the filesystem and the in-memory `state`, and does not call state.save() so the caller can batch it with other changes.""" hd_dir = root / ".hd" notes_dir = hd_dir / NOTES_DIRNAME notes_dir.mkdir(parents=True, exist_ok=True) note_path = notes_dir / f"{note_id}.md" note_path.write_text(text, encoding="utf-8") try: os.chmod(note_path, stat.S_IRUSR | stat.S_IWUSR) except OSError: pass effective_tags = tags if tags else [UNTAGGED] symlinks: dict[str, str] = {} for tag in effective_tags: tag_dir = root / tag tag_dir.mkdir(parents=True, exist_ok=True) taken = {p.name for p in tag_dir.iterdir()} if tag_dir.exists() else set() name = unique_name(sanitize_title(title), note_id, taken) target = os.path.relpath(note_path, tag_dir) (tag_dir / name).symlink_to(target) symlinks[tag] = name ns = NoteState( title=title, tags=effective_tags, symlinks=symlinks, content_hash=content_hash(text), last_seen_time=int(time.time() * 1000), ) state.notes[note_id] = ns return ns def strip_md_suffix(name: str) -> str: """'Masten' and 'Masten.md' name the same note -- accept both, matching what a plain `ls` of the tag directory actually shows. Only strips a LITERAL trailing '.md'; 'Masten.md.md' (an unlikely but real note title) is left alone rather than mangled twice.""" if name.endswith(".md") and len(name) > len(".md"): return name[: -len(".md")] return name def find_existing_symlink(root: Path, tag: Optional[str], name: str) -> Optional[str]: """If // is already a symlink into .hd/notes/.md, return that id. None if there's no such symlink (including: it exists but isn't ours -- a stray file, or a symlink pointing elsewhere -- callers should fall through to creating a new note rather than guessing).""" tag_dir = root / (tag if tag else UNTAGGED) candidate = tag_dir / sanitize_title(strip_md_suffix(name)) if not candidate.is_symlink(): return None target = candidate.resolve() notes_dir = (root / ".hd" / NOTES_DIRNAME).resolve() if target.parent != notes_dir or target.suffix != ".md": return None return target.stem def check_target_dir_fresh(root: Path, cwd: Path, state: State) -> Optional[str]: """The manual's stricter special case: before CREATING a note in a directory, verify that directory itself is sound -- freshly, never from the cached .hd/problems.json, which can be a full sync interval stale and is the wrong thing to hang the system's only blocking refusal on. Deliberately narrow and cheap (a listdir of one directory, no checksums, no tree walk): it only looks for problems that would make creating a note *here* wrong. Returns an error string, or None if the directory is fine. """ cwd = cwd.resolve() if cwd == root.resolve(): return None # the root itself is never "a broken tag directory" if not cwd.is_dir(): return f"{cwd} is not a directory" for entry in cwd.iterdir(): if entry.is_dir() and not entry.is_symlink(): return (f"{cwd} contains a subdirectory ({entry.name}/) -- nested tag " f"folders aren't supported, so this tag directory is in a state " f"hd can't reconcile. Fix it before creating notes here.") return None def save_offline_recovery(hd_root: Path, note_id: str, text: str) -> Path: """Preserve locally-typed content that never reached the server (e.g. hd-joe was offline at quit time) somewhere recoverable, WITHOUT touching the tracked cache/state -- see update_note_cache()'s docstring for why that distinction matters. Never overwrites a previous recovery file for the same note; each offline session that fails to sync gets its own timestamped file, so nothing is silently replaced by a later one. """ recovery_dir = hd_root / ".hd" / "offline-recovery" recovery_dir.mkdir(parents=True, exist_ok=True) timestamp = time.strftime("%Y%m%dT%H%M%SZ", time.gmtime()) path = recovery_dir / f"{note_id}-{timestamp}.md" path.write_text(text, encoding="utf-8") return path def update_note_cache(hd_root: Path, note_id: str, text: str) -> bool: """After an hd-joe edit session ends, refresh .hd/notes/.md and state.json's content_hash for that ONE note -- without a full /history-driven sync. Title/tags/symlinks are left untouched (an edit session doesn't change them); this only exists so 'cat' on the symlink right after quitting hd-joe shows what you just typed, instead of whatever the last 'hdc sync' happened to see. No-op (returns False) if the note isn't in state yet -- e.g. it was opened by explicit and has never been through a sync, so there's no title/tags to safely preserve. The next 'hdc sync' will pick it up properly via /history. """ hd_dir = hd_root / ".hd" with ReconcileLock(hd_dir): state = State.load(hd_dir) ns = state.notes.get(note_id) if ns is None: return False note_path = hd_dir / NOTES_DIRNAME / f"{note_id}.md" note_path.write_text(text, encoding="utf-8") try: os.chmod(note_path, stat.S_IRUSR | stat.S_IWUSR) except OSError: pass ns.content_hash = content_hash(text) state.save(hd_dir) return True def resolve_or_create_note( hd_root: Path, cwd: Path, name: str, url: str, cookie: str, ) -> tuple[str, bool]: """The core of `hd-joe `: figure out the tag from `cwd`, open the matching note if a symlink for `name` already exists there, otherwise create it on the server and register it locally. Returns (note_id, created). Raises ValueError for a refusal (e.g. nested tag folder) that callers should report and exit on, not retry. """ name = strip_md_suffix(name) # "Masten" and "Masten.md" mean the same note tag, err = tag_from_cwd(hd_root, cwd) if err: raise ValueError(err) existing_id = find_existing_symlink(hd_root, tag, name) if existing_id: return existing_id, False hd_dir = hd_root / ".hd" state = State.load(hd_dir) # Only gate CREATION on this, not opening: opening an existing note in a # messy directory is harmless, but adding a new one to a directory hd # already can't reconcile just deepens the mess. dir_error = check_target_dir_fresh(hd_root, cwd, state) if dir_error: raise ValueError(dir_error) tags = [tag] if tag else [] with ReconcileLock(hd_dir): note_id, initial_text = create_note(url, cookie, name, tags) register_note(hd_root, state, note_id, name, tags, initial_text) state.save(hd_dir) return note_id, True