first commit
This commit is contained in:
149
hd-cli/README.md
Normal file
149
hd-cli/README.md
Normal file
@@ -0,0 +1,149 @@
|
||||
# hdc -- HedgeDoc as a tag-organized local folder
|
||||
|
||||
Run `../install.sh` from the repo root first (builds patched JOE, sets up a
|
||||
venv, links `hdc` and `hd-joe` onto your PATH). This README covers `hdc`
|
||||
specifically once that's done; see the top-level README for the whole repo.
|
||||
|
||||
## Setup
|
||||
|
||||
hdc init https://your-hedgedoc.example --dir ~/notes
|
||||
|
||||
Interactive dialog: email, then password (not echoed), logs in against
|
||||
`/login`, keeps only the resulting session cookie. SSO/LDAP servers: use
|
||||
`--cookie 'connect.sid=...'` instead (copied from your browser).
|
||||
|
||||
hdc sync # one-shot pull + reconcile
|
||||
hdc sync --watch # poll every 30s (--interval to change)
|
||||
hdc tag <note> <tag> # add a tag -- writes to HedgeDoc
|
||||
hdc untag <note> <tag> # remove a tag -- writes to HedgeDoc
|
||||
|
||||
`--dir` is optional on `sync`/`tag`/`untag`: standing anywhere inside an
|
||||
hd-managed folder (not just at its root) is enough -- `hdc` walks up
|
||||
looking for `.hd/`, the same discovery `hd-joe` already does, falling
|
||||
back to `~/notes` if that finds nothing. Pass `--dir` explicitly to
|
||||
override this (e.g. managing more than one hd-managed folder).
|
||||
|
||||
`<note>` in `tag`/`untag` accepts a note id, or a path to one of its
|
||||
existing symlinks -- resolved from wherever you're actually standing, the
|
||||
same way a shell resolves any other path: a bare `FOI` means the symlink
|
||||
named `FOI` right here, `../work/FOI` means the one in `../work`. This
|
||||
takes priority over title matching, so a same-named note elsewhere never
|
||||
gets picked by accident. Only if no symlink matches at all does it fall
|
||||
back to searching by title (must be unique) across every note.
|
||||
|
||||
## Layout under --dir (default: auto-detected, see above; ~/notes if nothing is found)
|
||||
|
||||
.hd/config.json server URL (+ email if you logged in). No secrets.
|
||||
.hd/cookies.json session cookie, mode 0600.
|
||||
.hd/state.json what the reconciler believes is true right now.
|
||||
.hd/problems.json things sync noticed but can't safely fix itself.
|
||||
.hd/.lock real interprocess lock (fcntl.flock) shared by
|
||||
every command that touches state/symlinks.
|
||||
.hd/notes/<id>.md cached content -- read-only, do not edit directly.
|
||||
<tag>/<title> symlink into .hd/notes/<id>.md, one per tag.
|
||||
No .md on the symlink itself -- it's named
|
||||
after the note's title, not a file.
|
||||
untagged/<title> symlink for notes with no tags.
|
||||
|
||||
## What `sync` does
|
||||
|
||||
`GET /history` (cookie-authenticated) is the only source of truth for which
|
||||
notes exist and what tags they have -- confirmed against HedgeDoc 1.12.0's
|
||||
own `lib/history.js`, not guessed. Content is only re-fetched via
|
||||
`/<id>/download` when `/history`'s `time` field has actually moved since
|
||||
last sync (skips the network round trip entirely otherwise). Every sync
|
||||
pass also runs a cheap structural check over the tag directories and writes
|
||||
whatever it finds to `.hd/problems.json`:
|
||||
|
||||
- a real directory where a tag symlink was expected (nested tag folders
|
||||
aren't supported -- one tag is always exactly one directory level)
|
||||
- a plain file where a symlink was expected (the classic `cp` without `-P`
|
||||
mistake) -- its checksum is looked up against the cache; a match names
|
||||
the note and the exact fix command, no match says so plainly
|
||||
- a broken symlink (target no longer exists)
|
||||
- a symlink pointing outside `.hd/notes/` entirely (created by hand)
|
||||
|
||||
## What `tag`/`untag` do
|
||||
|
||||
There is no plain HTTP save endpoint for an existing note's content
|
||||
(checked against the router source) -- the only way to change a note at
|
||||
all is the realtime Socket.IO channel, same as any live edit. `hdc tag`/`hdc
|
||||
untag` open a short-lived connection, fetch the document **fresh** (never
|
||||
from the local cache, which can be hours old), parse the YAML frontmatter
|
||||
exactly the way HedgeDoc itself does (`lib/models/note.js`'s
|
||||
`splitFrontmatter`: must start with literal `---`, closed by the first
|
||||
`\n---` or `\n...`), edit only the `tags:` line, and send the minimal patch
|
||||
-- title and everything else in the frontmatter, and the entire body, are
|
||||
left untouched. Tags are always written as a comma-separated string, never
|
||||
a YAML list -- a list is silently ignored by the real server's own tag
|
||||
parser. Untagging down to zero removes the `tags` key entirely rather than
|
||||
leaving it empty. A note with no frontmatter at all gets a fresh block
|
||||
inserted at the very top.
|
||||
|
||||
If the existing frontmatter doesn't parse as valid YAML, or parses to
|
||||
something that isn't a mapping, `hdc tag`/`hdc untag` refuse to touch it
|
||||
rather than risk destroying whatever's actually there.
|
||||
|
||||
After a successful write, the command immediately runs a normal sync pass
|
||||
so the local symlinks catch up right away instead of waiting for the next
|
||||
scheduled sync.
|
||||
|
||||
## Known gaps
|
||||
|
||||
- **No filesystem watcher.** Moving a symlink between tag folders yourself
|
||||
doesn't do anything -- only the explicit `hdc tag`/`hdc untag` commands,
|
||||
and hd-joe's note creation, write to the server. `ReconcileLock` (a real
|
||||
`fcntl.flock` on `.hd/.lock`) is already shared by all three, so a future
|
||||
watcher has something correct to coordinate with -- the watcher itself
|
||||
isn't built.
|
||||
- **`/history` is the most fragile dependency in this whole system** -- it's
|
||||
HedgeDoc's internal "recently visited" feature, not an API designed for
|
||||
this purpose. It only lists notes the account has opened at least once,
|
||||
and a note's tags there only refresh while someone is actively viewing
|
||||
or editing it server-side.
|
||||
- **No protection against two truly simultaneous tag edits** to the same
|
||||
note landing at the same moment -- the OT layer resolves the byte
|
||||
positions correctly either way, but a genuine semantic race (both edits
|
||||
reading the same "current tags" before either's write lands) isn't
|
||||
specially detected. Rare in practice for a single-user tool; worth
|
||||
revisiting if `hdc tag` ever gets called from automation.
|
||||
|
||||
## Tests
|
||||
|
||||
cd hd-cli
|
||||
python3 test_hd_core.py # reconciliation: create/retag/rename/
|
||||
# collision/deletion/idempotency (34)
|
||||
python3 test_hd_cli.py # hdc init/sync via subprocess, login flow,
|
||||
# file permissions, --dir auto-detection (30)
|
||||
python3 test_hd_tags.py # frontmatter parsing/patching, note
|
||||
# reference resolution incl. cwd-relative
|
||||
# path priority over title matching (31)
|
||||
python3 test_hd_problems.py # stray/nested/broken/foreign detection,
|
||||
# real flock mutual exclusion (16)
|
||||
python3 test_hd_write.py # write_tags against a fake realtime
|
||||
# server: minimal edits, no-op skip (13)
|
||||
python3 test_hd_tag_cli.py # hdc tag/untag via subprocess against a
|
||||
# combined history+download+realtime
|
||||
# fake server (13)
|
||||
python3 test_hd_tag_stale_history.py # tag/untag against a fake server
|
||||
# that deliberately delays /history's
|
||||
# view of a write, like real HedgeDoc's
|
||||
# own DB-flush lag (9)
|
||||
|
||||
148 checks total. Three real bugs were found and fixed by these tests
|
||||
during development, not just by reading the code: `write_tags` originally
|
||||
had a "retry if revision moved" check that couldn't tell its own
|
||||
successful write's natural revision bump apart from a genuine concurrent
|
||||
edit, `hdc tag`/`hdc untag`'s immediate re-sync could be fooled by
|
||||
`/history`'s own delayed view of the write it had just made (found only
|
||||
once a fake server was built that actually reproduces that delay, instead
|
||||
of the instant consistency every other fake server here gives for free --
|
||||
see CHANGES-0.7.28.md), and
|
||||
replayed the tag mutation a second time on top of itself -- caught by
|
||||
`test_hd_write.py` producing `['urgent', 'urgent']` instead of `['urgent']`.
|
||||
Separately, `test_hd_tag_cli.py`'s own fake server hung on every `hdc tag`
|
||||
call at first, from constructing a fresh `socketio.WSGIApp` per HTTP
|
||||
request and from parsing `QUERY_STRING` through `urlparse()` a second time
|
||||
(which returns nothing, since `QUERY_STRING` isn't a full URL) -- both bugs
|
||||
were in the test's own scaffolding, not in `hdc`, but neither test would
|
||||
have caught anything real until both were fixed.
|
||||
257
hd-cli/hdc
Executable file
257
hd-cli/hdc
Executable file
@@ -0,0 +1,257 @@
|
||||
#!/usr/bin/env python3
|
||||
"""hdc -- local filesystem mirror of a HedgeDoc account, organized by tag.
|
||||
|
||||
(Named hdc, not hd: hd already means hexdump on Debian/Ubuntu --
|
||||
bsdextrautils ships it as a standard alias, and it beat us to the name.)
|
||||
|
||||
hdc init [<hedgedoc-url>] [--email E] [--cookie '...'] [--dir ~/notes]
|
||||
hdc sync [--dir ~/notes] [-v] [--watch [--interval SECONDS]]
|
||||
hdc tag <note> <tag> [--dir ~/notes]
|
||||
hdc untag <note> <tag> [--dir ~/notes]
|
||||
|
||||
Layout created under --dir (default: ~/notes):
|
||||
.hd/config.json server url (+ email, if you logged in), mode 0600
|
||||
.hd/cookies.json session cookie, mode 0600 -- kept separate from
|
||||
config.json since this is the actual credential
|
||||
.hd/state.json what the reconciler believes is true
|
||||
.hd/problems.json things sync noticed but can't safely fix itself
|
||||
.hd/notes/<id>.md cached note content (read-only cache -- do not edit)
|
||||
<tag>/<title>.md symlink into .hd/notes/<id>.md, one per tag
|
||||
untagged/<title>.md symlink for notes with no tags
|
||||
|
||||
`sync` only ever pulls from HedgeDoc. `tag`/`untag` are the only commands
|
||||
that write back -- they edit the note's own YAML frontmatter over the
|
||||
realtime channel (there's no plain HTTP save endpoint for existing notes)
|
||||
and then re-run a sync pass so the local symlinks catch up immediately.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import getpass
|
||||
import logging
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
# hd_core.py/hd_client.py live in ../hd_common, shared verbatim with hd-joe
|
||||
# (see hd_common/README.md) -- add it to sys.path before importing either,
|
||||
# regardless of where this script is actually invoked from.
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "hd_common"))
|
||||
|
||||
from hd_core import (
|
||||
Config, Cookies, HedgeDocSource, LoginError, State,
|
||||
find_hd_root, login, reconcile, resolve_note_ref, update_note_tags_locally, write_tags,
|
||||
)
|
||||
|
||||
logger = logging.getLogger("hdc")
|
||||
|
||||
|
||||
def cmd_init(args: argparse.Namespace) -> int:
|
||||
root = Path(args.dir).expanduser()
|
||||
hd_dir = root / ".hd"
|
||||
if hd_dir.exists():
|
||||
print(f"{hd_dir} already exists -- refusing to overwrite. "
|
||||
f"Delete it yourself first if you really want to re-init.", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
url = args.url or input("HedgeDoc server URL: ").strip()
|
||||
if not url:
|
||||
print("A server URL is required.", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
email: str | None = None
|
||||
if args.cookie:
|
||||
cookie_header = args.cookie
|
||||
else:
|
||||
# Interactive login dialog: server (above), then email + password.
|
||||
email = args.email or input("Email: ").strip()
|
||||
if not email:
|
||||
print("An email address is required for login "
|
||||
"(or pass --cookie if this server uses SSO/LDAP instead).", file=sys.stderr)
|
||||
return 1
|
||||
password = getpass.getpass("Password: ")
|
||||
try:
|
||||
cookie_header = login(url, email, password)
|
||||
except LoginError as exc:
|
||||
print(f"Login failed: {exc}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
hd_dir.mkdir(parents=True, exist_ok=True)
|
||||
(hd_dir / "notes").mkdir(parents=True, exist_ok=True)
|
||||
|
||||
config = Config(url=url.rstrip("/"), email=email)
|
||||
config.save(hd_dir)
|
||||
Cookies(header=cookie_header).save(hd_dir)
|
||||
|
||||
print(f"Initialized {root}. Running first sync...")
|
||||
return _do_sync(root)
|
||||
|
||||
|
||||
def _resolve_root(dir_arg: Optional[str]) -> Path:
|
||||
"""--dir was given explicitly: use it, unchanged from before. Otherwise
|
||||
walk up from the current directory looking for .hd/ -- same discovery
|
||||
hd-joe already does -- so standing anywhere inside an hd-managed
|
||||
folder (not just its root) just works, without needing --dir spelled
|
||||
out every time. Falls back to the old hardcoded ~/notes only if that
|
||||
search finds nothing, so running these commands from somewhere
|
||||
unrelated still behaves the way it always has."""
|
||||
if dir_arg is not None:
|
||||
return Path(dir_arg).expanduser()
|
||||
found = find_hd_root(Path.cwd())
|
||||
if found is not None:
|
||||
return found
|
||||
return Path("~/notes").expanduser()
|
||||
|
||||
|
||||
def _do_sync(root: Path) -> int:
|
||||
hd_dir = root / ".hd"
|
||||
if not hd_dir.exists():
|
||||
print(f"{hd_dir} does not exist -- run 'hdc init' first.", file=sys.stderr)
|
||||
return 1
|
||||
config = Config.load(hd_dir)
|
||||
cookies = Cookies.load(hd_dir)
|
||||
state = State.load(hd_dir)
|
||||
source = HedgeDocSource(config.url, cookies.header)
|
||||
try:
|
||||
result = reconcile(root, source, state)
|
||||
except RuntimeError as exc:
|
||||
print(str(exc), file=sys.stderr)
|
||||
return 1
|
||||
state.save(hd_dir)
|
||||
|
||||
if result.notes_updated:
|
||||
print(f"Updated: {len(result.notes_updated)} note(s)")
|
||||
if result.notes_removed:
|
||||
print(f"Removed: {len(result.notes_removed)} note(s) no longer in your history")
|
||||
if result.symlinks_created:
|
||||
logger.info("Created %d symlink(s)", len(result.symlinks_created))
|
||||
if result.symlinks_removed:
|
||||
logger.info("Removed %d symlink(s)", len(result.symlinks_removed))
|
||||
if not (result.notes_updated or result.notes_removed):
|
||||
print("Up to date.")
|
||||
if result.problems:
|
||||
print(f"\n{len(result.problems)} problem(s) found:")
|
||||
for p in result.problems:
|
||||
print(f" - {p}")
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_sync(args: argparse.Namespace) -> int:
|
||||
root = _resolve_root(args.dir)
|
||||
if not args.watch:
|
||||
return _do_sync(root)
|
||||
print(f"Watching (polling every {args.interval}s). Ctrl-C to stop.")
|
||||
try:
|
||||
while True:
|
||||
rc = _do_sync(root)
|
||||
if rc != 0:
|
||||
return rc
|
||||
time.sleep(args.interval)
|
||||
except KeyboardInterrupt:
|
||||
return 0
|
||||
|
||||
|
||||
def _cmd_retag(args: argparse.Namespace, mutate) -> int:
|
||||
root = _resolve_root(args.dir)
|
||||
hd_dir = root / ".hd"
|
||||
if not hd_dir.exists():
|
||||
print(f"{hd_dir} does not exist -- run 'hdc init' first.", file=sys.stderr)
|
||||
return 1
|
||||
config = Config.load(hd_dir)
|
||||
cookies = Cookies.load(hd_dir)
|
||||
state = State.load(hd_dir) # read-only here; write_tags never touches local state
|
||||
|
||||
try:
|
||||
# cwd, not root: 'FOI' means the symlink named FOI in the
|
||||
# directory the user is actually standing in, '../work/FOI' the
|
||||
# one in ../work -- see resolve_note_ref's docstring.
|
||||
note_id = resolve_note_ref(root, state, args.note, cwd=Path.cwd())
|
||||
except ValueError as exc:
|
||||
print(str(exc), file=sys.stderr)
|
||||
return 1
|
||||
|
||||
try:
|
||||
new_tags = write_tags(config.url, cookies.header, note_id, mutate)
|
||||
except Exception as exc:
|
||||
print(f"Could not update tags for {note_id}: {exc}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
print(f"{note_id}: tags now [{', '.join(new_tags) if new_tags else '(none)'}]")
|
||||
# Apply the symlink change directly from the write's own confirmed
|
||||
# result, before the /history-driven sync below -- /history can lag a
|
||||
# just-completed write by a few seconds (HedgeDoc's DB-flush delay),
|
||||
# which left a stale symlink in place after a real 'hdc untag'. This
|
||||
# makes the CLI's own view correct immediately regardless of that;
|
||||
# _do_sync() below still runs as the general catch-all for anything
|
||||
# else that may have changed elsewhere since the last sync.
|
||||
try:
|
||||
update_note_tags_locally(root, note_id, new_tags)
|
||||
except Exception as exc:
|
||||
logger.warning("Could not apply the local symlink update directly (%s); "
|
||||
"the sync below is still the safety net.", exc)
|
||||
print("Syncing local symlinks...")
|
||||
return _do_sync(root) # reconcile() takes its own lock; nothing held across this call
|
||||
|
||||
|
||||
def cmd_tag(args: argparse.Namespace) -> int:
|
||||
tag = args.tag
|
||||
return _cmd_retag(args, lambda tags: tags if tag in tags else [*tags, tag])
|
||||
|
||||
|
||||
def cmd_untag(args: argparse.Namespace) -> int:
|
||||
tag = args.tag
|
||||
return _cmd_retag(args, lambda tags: [t for t in tags if t != tag])
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser(prog="hdc", description=__doc__,
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
ap.add_argument("-v", "--verbose", action="store_true")
|
||||
sub = ap.add_subparsers(dest="command", required=True)
|
||||
|
||||
p_init = sub.add_parser("init", help="Set up a new hd-managed folder")
|
||||
p_init.add_argument("url", nargs="?", help="HedgeDoc server URL (prompted for if omitted)")
|
||||
p_init.add_argument("--email", help="Email to log in with (prompted for if omitted and no --cookie)")
|
||||
p_init.add_argument("--cookie", help="Skip the login dialog: use this Cookie header directly "
|
||||
"(needed for SSO/LDAP servers with no local password login)")
|
||||
p_init.add_argument("--dir", default="~/notes", help="Target folder (default: ~/notes)")
|
||||
p_init.set_defaults(func=cmd_init)
|
||||
|
||||
dir_help = ("Target folder. Default: auto-detected by walking up from the "
|
||||
"current directory looking for .hd/ (same as hd-joe), falling "
|
||||
"back to ~/notes if that finds nothing.")
|
||||
|
||||
p_sync = sub.add_parser("sync", help="Pull notes and reconcile tag symlinks")
|
||||
p_sync.add_argument("--dir", default=None, help=dir_help)
|
||||
p_sync.add_argument("--watch", action="store_true", help="Keep syncing in a loop instead of once")
|
||||
p_sync.add_argument("--interval", type=float, default=30.0, help="Seconds between syncs with --watch")
|
||||
p_sync.set_defaults(func=cmd_sync)
|
||||
|
||||
p_tag = sub.add_parser("tag", help="Add a tag to a note (writes to HedgeDoc)")
|
||||
p_tag.add_argument("note", help="Note id, or a path to one of its symlinks -- resolved from where "
|
||||
"you're standing, like any other path (bare 'Title' means the symlink "
|
||||
"named Title right here; '../work/Title' means the one in ../work) -- "
|
||||
"or, only if no symlink matches, its (unique) title anywhere")
|
||||
p_tag.add_argument("tag", help="Tag to add")
|
||||
p_tag.add_argument("--dir", default=None, help=dir_help)
|
||||
p_tag.set_defaults(func=cmd_tag)
|
||||
|
||||
p_untag = sub.add_parser("untag", help="Remove a tag from a note (writes to HedgeDoc)")
|
||||
p_untag.add_argument("note", help="Note id, or a path to one of its symlinks -- resolved from where "
|
||||
"you're standing, like any other path (bare 'Title' means the symlink "
|
||||
"named Title right here; '../work/Title' means the one in ../work) -- "
|
||||
"or, only if no symlink matches, its (unique) title anywhere")
|
||||
p_untag.add_argument("tag", help="Tag to remove")
|
||||
p_untag.add_argument("--dir", default=None, help=dir_help)
|
||||
p_untag.set_defaults(func=cmd_untag)
|
||||
|
||||
args = ap.parse_args()
|
||||
logging.basicConfig(level=logging.DEBUG if args.verbose else logging.WARNING,
|
||||
format="%(levelname)s %(message)s")
|
||||
return args.func(args)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
2
hd-cli/requirements.txt
Normal file
2
hd-cli/requirements.txt
Normal file
@@ -0,0 +1,2 @@
|
||||
-r ../hd_common/requirements.txt
|
||||
werkzeug>=3.0 # tests only, not needed to run hd itself
|
||||
215
hd-cli/test_hd_cli.py
Normal file
215
hd-cli/test_hd_cli.py
Normal file
@@ -0,0 +1,215 @@
|
||||
#!/usr/bin/env python3
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(__import__("pathlib").Path(__file__).resolve().parent.parent / "hd_common"))
|
||||
from werkzeug.serving import make_server
|
||||
from werkzeug.wrappers import Request, Response
|
||||
|
||||
PASS = []
|
||||
FAIL = []
|
||||
|
||||
|
||||
def check(name, cond, detail=""):
|
||||
if cond:
|
||||
PASS.append(name)
|
||||
else:
|
||||
FAIL.append((name, detail))
|
||||
print(f"FAIL: {name} {detail}")
|
||||
|
||||
|
||||
class FakeServer:
|
||||
"""Serves /history, /<id>/download, and a fake /login that accepts
|
||||
exactly one email+password pair and sets a session cookie -- mirrors
|
||||
real HedgeDoc's local-auth /login: always 302s, whether accepted or
|
||||
rejected, and the caller must probe /history to find out which."""
|
||||
|
||||
VALID_EMAIL = "joakim@example.com"
|
||||
VALID_PASSWORD = "correct horse battery staple"
|
||||
|
||||
def __init__(self, port, notes):
|
||||
self.notes = notes
|
||||
self.port = port
|
||||
self.valid_sessions = {"session=abc123"}
|
||||
|
||||
def app(environ, start_response):
|
||||
request = Request(environ)
|
||||
if request.path == "/login" and request.method == "POST":
|
||||
from urllib.parse import parse_qs
|
||||
body = request.get_data(as_text=True)
|
||||
fields = parse_qs(body)
|
||||
email = (fields.get("email") or [""])[0]
|
||||
password = (fields.get("password") or [""])[0]
|
||||
resp = Response(status=302, headers={"Location": "/"})
|
||||
if email == self.VALID_EMAIL and password == self.VALID_PASSWORD:
|
||||
resp.set_cookie("connect.sid", "loggedinsession")
|
||||
self.valid_sessions.add("connect.sid=loggedinsession")
|
||||
return resp(environ, start_response)
|
||||
if request.path == "/history":
|
||||
cookie = request.headers.get("Cookie", "")
|
||||
if not any(v in cookie for v in self.valid_sessions):
|
||||
resp = Response("forbidden", status=403)
|
||||
else:
|
||||
history = [{"id": nid, "text": n["title"], "tags": n["tags"], "time": 0}
|
||||
for nid, n in self.notes.items()]
|
||||
resp = Response(json.dumps({"history": history}), mimetype="application/json")
|
||||
elif request.path.endswith("/download"):
|
||||
nid = request.path.split("/")[1]
|
||||
resp = Response(self.notes[nid]["content"], mimetype="text/markdown")
|
||||
else:
|
||||
resp = Response("not found", status=404)
|
||||
return resp(environ, start_response)
|
||||
|
||||
self.srv = make_server("127.0.0.1", port, app, threaded=True)
|
||||
self.thread = threading.Thread(target=self.srv.serve_forever, daemon=True)
|
||||
|
||||
def start(self):
|
||||
self.thread.start()
|
||||
|
||||
def stop(self):
|
||||
self.srv.shutdown()
|
||||
|
||||
|
||||
def free_port():
|
||||
import socket
|
||||
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
s.bind(("127.0.0.1", 0))
|
||||
p = s.getsockname()[1]
|
||||
s.close()
|
||||
return p
|
||||
|
||||
|
||||
def run_hd(*args, cwd, input_text=None):
|
||||
return subprocess.run(
|
||||
[sys.executable, str(Path(__file__).parent / "hdc"), *args],
|
||||
cwd=cwd, capture_output=True, text=True, timeout=15, input=input_text,
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
port = free_port()
|
||||
notes = {
|
||||
"n1": {"title": "Fox Hunt Notes", "tags": ["radio"], "content": "# Fox Hunt\nfrequencies here"},
|
||||
}
|
||||
server = FakeServer(port, notes)
|
||||
server.start()
|
||||
|
||||
tmpdir = Path(tempfile.mkdtemp(prefix="hd-cli-test-"))
|
||||
target = tmpdir / "notes"
|
||||
|
||||
try:
|
||||
# --- init with --cookie, wrong value: files saved, but sync fails ---
|
||||
r = run_hd("init", f"http://127.0.0.1:{port}", "--cookie", "session=wrong",
|
||||
"--dir", str(target), cwd=tmpdir)
|
||||
check("init with bad cookie exits nonzero (sync fails)", r.returncode != 0, r.stderr)
|
||||
check("init with bad cookie still saved cookies.json",
|
||||
(target / ".hd" / "cookies.json").exists())
|
||||
|
||||
shutil.rmtree(target)
|
||||
|
||||
# --- init with --cookie, correct value ---
|
||||
r = run_hd("init", f"http://127.0.0.1:{port}", "--cookie", "session=abc123",
|
||||
"--dir", str(target), cwd=tmpdir)
|
||||
check("init with good cookie exits 0", r.returncode == 0, r.stderr)
|
||||
check("config.json created", (target / ".hd" / "config.json").exists())
|
||||
check("cookies.json created", (target / ".hd" / "cookies.json").exists())
|
||||
for fname in ("config.json", "cookies.json"):
|
||||
mode = stat.S_IMODE((target / ".hd" / fname).stat().st_mode)
|
||||
check(f"{fname} is mode 0600", mode == 0o600, oct(mode))
|
||||
check("cookie not leaked into config.json",
|
||||
"cookie" not in json.loads((target / ".hd" / "config.json").read_text()))
|
||||
check("cookie present in cookies.json",
|
||||
json.loads((target / ".hd" / "cookies.json").read_text())["cookie"] == "session=abc123")
|
||||
check("state.json created", (target / ".hd" / "state.json").exists())
|
||||
check("radio/ created with symlink", (target / "radio" / "Fox Hunt Notes").is_symlink())
|
||||
check("symlinked content matches", (target / "radio" / "Fox Hunt Notes").read_text()
|
||||
== "# Fox Hunt\nfrequencies here")
|
||||
|
||||
# --- --dir auto-detection: standing anywhere inside the hd-managed
|
||||
# tree, 'hdc sync' with no --dir at all should still find it ---
|
||||
r_auto1 = run_hd("sync", cwd=target) # at the root itself
|
||||
check("sync with no --dir, standing AT the hd root, auto-detects it",
|
||||
r_auto1.returncode == 0, r_auto1.stdout + r_auto1.stderr)
|
||||
|
||||
r_auto2 = run_hd("sync", cwd=target / "radio") # a subdirectory
|
||||
check("sync with no --dir, standing in a SUBDIRECTORY, still auto-detects the root above it",
|
||||
r_auto2.returncode == 0, r_auto2.stdout + r_auto2.stderr)
|
||||
|
||||
# From somewhere with no .hd/ above it at all, and a controlled,
|
||||
# guaranteed-empty $HOME so the ~/notes fallback can't accidentally
|
||||
# succeed against whatever the real test machine happens to have --
|
||||
# this must fail cleanly, not silently do nothing or pick up an
|
||||
# unrelated real folder.
|
||||
fake_home = tmpdir / "fake-home-no-notes-here"
|
||||
fake_home.mkdir()
|
||||
r_nowhere = subprocess.run(
|
||||
[sys.executable, str(Path(__file__).parent / "hdc"), "sync"],
|
||||
cwd=tmpdir, capture_output=True, text=True, timeout=15,
|
||||
env={**os.environ, "HOME": str(fake_home)},
|
||||
)
|
||||
check("sync with no --dir and nothing discoverable anywhere fails cleanly, not silently",
|
||||
r_nowhere.returncode != 0, r_nowhere.stdout + r_nowhere.stderr)
|
||||
|
||||
# --- re-init refuses to clobber ---
|
||||
r2 = run_hd("init", f"http://127.0.0.1:{port}", "--cookie", "session=abc123",
|
||||
"--dir", str(target), cwd=tmpdir)
|
||||
check("re-init refuses (nonzero exit)", r2.returncode != 0)
|
||||
check("re-init leaves existing cookie untouched",
|
||||
json.loads((target / ".hd" / "cookies.json").read_text())["cookie"] == "session=abc123")
|
||||
|
||||
# --- sync after a server-side change ---
|
||||
notes["n1"]["tags"] = ["radio", "reference"]
|
||||
r3 = run_hd("sync", "--dir", str(target), cwd=tmpdir)
|
||||
check("sync exits 0", r3.returncode == 0, r3.stderr)
|
||||
check("sync picked up new tag", (target / "reference" / "Fox Hunt Notes").is_symlink())
|
||||
|
||||
# --- sync with no changes reports up to date ---
|
||||
r4 = run_hd("sync", "--dir", str(target), cwd=tmpdir)
|
||||
check("second sync exits 0", r4.returncode == 0)
|
||||
check("second sync says up to date", "Up to date" in r4.stdout, r4.stdout)
|
||||
|
||||
# --- sync against a nonexistent dir fails cleanly ---
|
||||
r5 = run_hd("sync", "--dir", str(tmpdir / "nope"), cwd=tmpdir)
|
||||
check("sync on uninitialized dir fails", r5.returncode != 0)
|
||||
|
||||
shutil.rmtree(target)
|
||||
|
||||
# --- login dialog: email prompted via --email, password via stdin ---
|
||||
r6 = run_hd("init", f"http://127.0.0.1:{port}", "--email", FakeServer.VALID_EMAIL,
|
||||
"--dir", str(target), cwd=tmpdir, input_text=FakeServer.VALID_PASSWORD + "\n")
|
||||
check("login-flow init exits 0", r6.returncode == 0, r6.stderr)
|
||||
check("login-flow saved email in config.json (no password)",
|
||||
json.loads((target / ".hd" / "config.json").read_text()).get("email") == FakeServer.VALID_EMAIL)
|
||||
check("login-flow config.json has no password field",
|
||||
"password" not in json.loads((target / ".hd" / "config.json").read_text()))
|
||||
check("login-flow captured the session cookie HedgeDoc actually set",
|
||||
"connect.sid=loggedinsession" in json.loads((target / ".hd" / "cookies.json").read_text())["cookie"])
|
||||
check("login-flow ran first sync successfully",
|
||||
(target / "radio" / "Fox Hunt Notes").is_symlink())
|
||||
|
||||
shutil.rmtree(target)
|
||||
|
||||
# --- login dialog with wrong password: clean failure, nothing written ---
|
||||
r7 = run_hd("init", f"http://127.0.0.1:{port}", "--email", FakeServer.VALID_EMAIL,
|
||||
"--dir", str(target), cwd=tmpdir, input_text="wrong password\n")
|
||||
check("wrong-password init exits nonzero", r7.returncode != 0)
|
||||
check("wrong-password init did not create .hd", not (target / ".hd").exists())
|
||||
check("wrong-password init explains the failure", "Login failed" in r7.stderr, r7.stderr)
|
||||
|
||||
finally:
|
||||
server.stop()
|
||||
shutil.rmtree(tmpdir, ignore_errors=True)
|
||||
|
||||
print(f"\n{len(PASS)} passed, {len(FAIL)} failed")
|
||||
return 0 if not FAIL else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
245
hd-cli/test_hd_core.py
Normal file
245
hd-cli/test_hd_core.py
Normal file
@@ -0,0 +1,245 @@
|
||||
#!/usr/bin/env python3
|
||||
import json
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(__import__("pathlib").Path(__file__).resolve().parent.parent / "hd_common"))
|
||||
from werkzeug.serving import make_server
|
||||
from werkzeug.wrappers import Request, Response
|
||||
|
||||
from hd_core import HedgeDocSource, State, reconcile
|
||||
|
||||
PASS = []
|
||||
FAIL = []
|
||||
|
||||
|
||||
def check(name, cond, detail=""):
|
||||
if cond:
|
||||
PASS.append(name)
|
||||
else:
|
||||
FAIL.append((name, detail))
|
||||
print(f"FAIL: {name} {detail}")
|
||||
|
||||
|
||||
class FakeHistoryServer:
|
||||
"""Serves /history and /<id>/download from an in-memory dict this test
|
||||
mutates directly between reconcile() calls, so each call sees the state
|
||||
as it stood at that moment -- like a real server changing between syncs.
|
||||
Each note dict may include "time" (default 0) -- tests bump it whenever
|
||||
they simulate a real edit, mirroring how /history's own `time` field
|
||||
actually moves on the real server; download_count tracks /download hits
|
||||
so tests can assert the skip-fetch-when-unchanged optimization fires."""
|
||||
|
||||
def __init__(self, port):
|
||||
self.notes = {} # id -> {"title":..., "tags":[...], "content":..., "time": int}
|
||||
self.port = port
|
||||
self.download_count = {} # id -> number of /download requests served
|
||||
|
||||
def app(environ, start_response):
|
||||
request = Request(environ)
|
||||
if request.path == "/history":
|
||||
history = [
|
||||
{"id": nid, "text": n["title"], "tags": n["tags"], "time": n.get("time", 0)}
|
||||
for nid, n in self.notes.items()
|
||||
]
|
||||
resp = Response(json.dumps({"history": history}), mimetype="application/json")
|
||||
elif request.path.endswith("/download"):
|
||||
nid = request.path.split("/")[1]
|
||||
n = self.notes.get(nid)
|
||||
self.download_count[nid] = self.download_count.get(nid, 0) + 1
|
||||
if n is None:
|
||||
resp = Response("not found", status=404)
|
||||
else:
|
||||
resp = Response(n["content"], mimetype="text/markdown")
|
||||
else:
|
||||
resp = Response("not found", status=404)
|
||||
return resp(environ, start_response)
|
||||
|
||||
self.srv = make_server("127.0.0.1", port, app, threaded=True)
|
||||
self.thread = threading.Thread(target=self.srv.serve_forever, daemon=True)
|
||||
|
||||
def start(self):
|
||||
self.thread.start()
|
||||
|
||||
def stop(self):
|
||||
self.srv.shutdown()
|
||||
|
||||
|
||||
def free_port():
|
||||
import socket
|
||||
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
s.bind(("127.0.0.1", 0))
|
||||
p = s.getsockname()[1]
|
||||
s.close()
|
||||
return p
|
||||
|
||||
|
||||
def listing(root: Path, tag: str):
|
||||
d = root / tag
|
||||
if not d.exists():
|
||||
return {}
|
||||
return {p.name: p.resolve() for p in d.iterdir() if p.is_symlink()}
|
||||
|
||||
|
||||
def main():
|
||||
port = free_port()
|
||||
server = FakeHistoryServer(port)
|
||||
server.start()
|
||||
|
||||
tmpdir = Path(tempfile.mkdtemp(prefix="hd-test-"))
|
||||
root = tmpdir / "notes"
|
||||
hd_dir = root / ".hd"
|
||||
(hd_dir / "notes").mkdir(parents=True)
|
||||
source = HedgeDocSource(f"http://127.0.0.1:{port}", cookie="test=1")
|
||||
state = State()
|
||||
|
||||
try:
|
||||
# --- 1. Two notes, one shared tag, one exclusive tag each ---
|
||||
server.notes["id1"] = {"title": "Radio Log", "tags": ["radio", "work"], "content": "# Radio Log\ncontent A", "time": 1}
|
||||
server.notes["id2"] = {"title": "Grocery List", "tags": ["personal"], "content": "# Grocery List\nmilk", "time": 1}
|
||||
server.notes["id3"] = {"title": "Scratch", "tags": [], "content": "just some notes", "time": 1}
|
||||
|
||||
r1 = reconcile(root, source, state)
|
||||
check("initial: 3 notes updated", len(r1.notes_updated) == 3, r1.notes_updated)
|
||||
check("radio/ has Radio Log", "Radio Log" in listing(root, "radio"))
|
||||
check("work/ has Radio Log", "Radio Log" in listing(root, "work"))
|
||||
check("personal/ has Grocery List", "Grocery List" in listing(root, "personal"))
|
||||
check("untagged/ has Scratch", "Scratch" in listing(root, "untagged"))
|
||||
check("cache file id1 has right content",
|
||||
(hd_dir / "notes" / "id1.md").read_text() == "# Radio Log\ncontent A")
|
||||
check("radio/Radio Log resolves to id1.md",
|
||||
listing(root, "radio")["Radio Log"] == (hd_dir / "notes" / "id1.md").resolve())
|
||||
check("initial: each note fetched exactly once",
|
||||
server.download_count == {"id1": 1, "id2": 1, "id3": 1}, server.download_count)
|
||||
|
||||
# --- 2. Idempotent re-run: nothing changed, and /download is never
|
||||
# called again since /history's `time` field didn't move ---
|
||||
r2 = reconcile(root, source, state)
|
||||
check("idempotent: no notes updated", r2.notes_updated == [], r2.notes_updated)
|
||||
check("idempotent: no symlinks created", r2.symlinks_created == [], r2.symlinks_created)
|
||||
check("idempotent: no symlinks removed", r2.symlinks_removed == [], r2.symlinks_removed)
|
||||
check("idempotent: no re-fetch when time is unchanged",
|
||||
server.download_count == {"id1": 1, "id2": 1, "id3": 1}, server.download_count)
|
||||
|
||||
# --- 3. Retag: id1 loses 'work', gains 'reference' (a real retag
|
||||
# edits the note's frontmatter, so /history's time moves too) ---
|
||||
server.notes["id1"]["tags"] = ["radio", "reference"]
|
||||
server.notes["id1"]["time"] = 2
|
||||
r3 = reconcile(root, source, state)
|
||||
check("retag: id1 marked updated", "id1" in r3.notes_updated)
|
||||
check("retag: work/ no longer has Radio Log", "Radio Log" not in listing(root, "work"))
|
||||
check("retag: reference/ has Radio Log", "Radio Log" in listing(root, "reference"))
|
||||
check("retag: radio/ still has Radio Log", "Radio Log" in listing(root, "radio"))
|
||||
|
||||
# --- 4. Note becomes fully untagged ---
|
||||
server.notes["id2"]["tags"] = []
|
||||
server.notes["id2"]["time"] = 2
|
||||
r4 = reconcile(root, source, state)
|
||||
check("untag: personal/ no longer has Grocery List", "Grocery List" not in listing(root, "personal"))
|
||||
check("untag: untagged/ has Grocery List", "Grocery List" in listing(root, "untagged"))
|
||||
|
||||
# --- 5. Title change: symlink renamed, id mapping preserved ---
|
||||
server.notes["id1"]["title"] = "Ham Radio Log"
|
||||
server.notes["id1"]["time"] = 3
|
||||
r5 = reconcile(root, source, state)
|
||||
check("rename: old name gone from radio/", "Radio Log" not in listing(root, "radio"))
|
||||
check("rename: new name present in radio/", "Ham Radio Log" in listing(root, "radio"))
|
||||
check("rename: still resolves to id1.md",
|
||||
listing(root, "radio")["Ham Radio Log"] == (hd_dir / "notes" / "id1.md").resolve())
|
||||
check("rename: reference/ also renamed", "Ham Radio Log" in listing(root, "reference"))
|
||||
|
||||
# --- 6. Filename collision: two notes, same title, same tag ---
|
||||
server.notes["id4"] = {"title": "Ham Radio Log", "tags": ["radio"], "content": "different note, same title", "time": 1}
|
||||
r6 = reconcile(root, source, state)
|
||||
radio_files = listing(root, "radio")
|
||||
check("collision: both variants present", len(radio_files) == 2, radio_files)
|
||||
check("collision: deduped name uses id suffix",
|
||||
any(name.startswith("Ham Radio Log-") for name in radio_files))
|
||||
|
||||
# --- 7. Content update without title/tag change: cache refreshes, symlink name stable ---
|
||||
old_name = state.notes["id1"].symlinks["radio"]
|
||||
server.notes["id1"]["content"] = "# Ham Radio Log\nupdated content"
|
||||
server.notes["id1"]["time"] = 4
|
||||
r7 = reconcile(root, source, state)
|
||||
check("content update: id1 flagged updated", "id1" in r7.notes_updated)
|
||||
check("content update: symlink name unchanged", state.notes["id1"].symlinks["radio"] == old_name)
|
||||
check("content update: cache file reflects new content",
|
||||
(hd_dir / "notes" / "id1.md").read_text() == "# Ham Radio Log\nupdated content")
|
||||
check("content update: id1 was actually re-fetched (time moved)",
|
||||
server.download_count["id1"] == 4, server.download_count)
|
||||
|
||||
# --- 8. Note deleted server-side: pruned locally ---
|
||||
del server.notes["id3"]
|
||||
r8 = reconcile(root, source, state)
|
||||
check("deletion: id3 in notes_removed", "id3" in r8.notes_removed)
|
||||
check("deletion: untagged/Scratch gone", "Scratch" not in listing(root, "untagged"))
|
||||
check("deletion: cache file gone", not (hd_dir / "notes" / "id3.md").exists())
|
||||
check("deletion: state no longer tracks id3", "id3" not in state.notes)
|
||||
|
||||
# --- 9. Re-persist state through JSON round-trip and re-sync: still idempotent ---
|
||||
state.save(hd_dir)
|
||||
state2 = State.load(hd_dir)
|
||||
r9 = reconcile(root, source, state2)
|
||||
check("post-reload idempotent: no updates", r9.notes_updated == [], r9.notes_updated)
|
||||
check("post-reload idempotent: no symlink churn",
|
||||
not r9.symlinks_created and not r9.symlinks_removed,
|
||||
(r9.symlinks_created, r9.symlinks_removed))
|
||||
|
||||
finally:
|
||||
server.stop()
|
||||
shutil.rmtree(tmpdir, ignore_errors=True)
|
||||
|
||||
test_update_note_cache()
|
||||
|
||||
print(f"\n{len(PASS)} passed, {len(FAIL)} failed")
|
||||
return 0 if not FAIL else 1
|
||||
|
||||
|
||||
def test_update_note_cache():
|
||||
"""hd_core.update_note_cache: refreshes the local cache + hash after an
|
||||
hd-joe edit session, without touching title/tags/symlinks, and is a
|
||||
safe no-op for a note state.json doesn't know about yet."""
|
||||
import shutil, tempfile
|
||||
from hd_core import NoteState, State, content_hash, update_note_cache
|
||||
|
||||
tmpdir = Path(tempfile.mkdtemp(prefix="hd-cache-test-"))
|
||||
root = tmpdir / "notes"
|
||||
hd_dir = root / ".hd"
|
||||
(hd_dir / "notes").mkdir(parents=True)
|
||||
try:
|
||||
old_text = "---\ntitle: Masten\ntags: sl6cv\n---\n\nold content"
|
||||
(hd_dir / "notes" / "n1.md").write_text(old_text)
|
||||
state = State()
|
||||
state.notes["n1"] = NoteState(
|
||||
title="Masten", tags=["sl6cv"], symlinks={"sl6cv": "Masten"},
|
||||
content_hash=content_hash(old_text),
|
||||
)
|
||||
state.save(hd_dir)
|
||||
|
||||
new_text = "---\ntitle: Masten\ntags: sl6cv\n---\n\nAllt är korrekt!\nedited at EOF"
|
||||
updated = update_note_cache(root, "n1", new_text)
|
||||
check("update_note_cache returns True for a known note", updated is True)
|
||||
check("cache file reflects the new content",
|
||||
(hd_dir / "notes" / "n1.md").read_text() == new_text)
|
||||
|
||||
reloaded = State.load(hd_dir)
|
||||
check("content_hash updated in state.json",
|
||||
reloaded.notes["n1"].content_hash == content_hash(new_text))
|
||||
check("title untouched", reloaded.notes["n1"].title == "Masten")
|
||||
check("tags untouched", reloaded.notes["n1"].tags == ["sl6cv"])
|
||||
check("symlinks untouched", reloaded.notes["n1"].symlinks == {"sl6cv": "Masten"})
|
||||
|
||||
# Unknown note id (opened via explicit url+note-id, never synced) -- safe no-op
|
||||
result = update_note_cache(root, "never-seen-before", "whatever")
|
||||
check("update_note_cache returns False for an unknown note", result is False)
|
||||
check("no stray cache file created for the unknown note",
|
||||
not (hd_dir / "notes" / "never-seen-before.md").exists())
|
||||
finally:
|
||||
shutil.rmtree(tmpdir, ignore_errors=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
156
hd-cli/test_hd_problems.py
Normal file
156
hd-cli/test_hd_problems.py
Normal file
@@ -0,0 +1,156 @@
|
||||
#!/usr/bin/env python3
|
||||
import fcntl
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(__import__("pathlib").Path(__file__).resolve().parent.parent / "hd_common"))
|
||||
from hd_core import (
|
||||
NoteState, ReconcileLock, State, content_hash, detect_problems,
|
||||
load_problems, save_problems, Problem,
|
||||
)
|
||||
|
||||
PASS = []
|
||||
FAIL = []
|
||||
|
||||
|
||||
def check(name, cond, detail=""):
|
||||
if cond:
|
||||
PASS.append(name)
|
||||
else:
|
||||
FAIL.append((name, detail))
|
||||
print(f"FAIL: {name} {detail}")
|
||||
|
||||
|
||||
def main():
|
||||
tmpdir = Path(tempfile.mkdtemp(prefix="hd-problems-test-"))
|
||||
root = tmpdir / "notes"
|
||||
hd_dir = root / ".hd"
|
||||
notes_dir = hd_dir / "notes"
|
||||
notes_dir.mkdir(parents=True)
|
||||
|
||||
try:
|
||||
# --- set up a healthy note with a real cached copy + symlink ---
|
||||
note_text = "# Fox Hunt\nfrequencies here"
|
||||
(notes_dir / "id1.md").write_text(note_text)
|
||||
state = State()
|
||||
state.notes["id1"] = NoteState(
|
||||
title="Fox Hunt", tags=["radio"], symlinks={"radio": "Fox Hunt.md"},
|
||||
content_hash=content_hash(note_text),
|
||||
)
|
||||
radio_dir = root / "radio"
|
||||
radio_dir.mkdir(parents=True)
|
||||
(radio_dir / "Fox Hunt.md").symlink_to(Path("..") / ".hd" / "notes" / "id1.md")
|
||||
|
||||
problems = detect_problems(root, state)
|
||||
check("healthy symlink: no problems", problems == [], problems)
|
||||
|
||||
# --- nested_dir: a real directory where a tag symlink is expected ---
|
||||
(radio_dir / "subproject").mkdir()
|
||||
problems = detect_problems(root, state)
|
||||
kinds = {p.kind for p in problems}
|
||||
check("nested directory flagged", "nested_dir" in kinds, problems)
|
||||
nested = next(p for p in problems if p.kind == "nested_dir")
|
||||
check("nested_dir path is correct", nested.path == "radio/subproject", nested.path)
|
||||
shutil.rmtree(radio_dir / "subproject")
|
||||
|
||||
# --- stray_file: cp without -P, content matches a known note ---
|
||||
(radio_dir / "Accidental Copy.md").write_text(note_text) # same content as id1
|
||||
problems = detect_problems(root, state)
|
||||
stray = next((p for p in problems if p.kind == "stray_file"), None)
|
||||
check("stray file detected", stray is not None, problems)
|
||||
check("stray file identified via checksum match", "id1" in (stray.detail if stray else ""),
|
||||
stray.detail if stray else None)
|
||||
check("stray file suggests a fix command", "hdc tag" in (stray.detail if stray else ""),
|
||||
stray.detail if stray else None)
|
||||
|
||||
# --- stray file with NO checksum match: says so plainly, no guess ---
|
||||
(radio_dir / "Accidental Copy.md").unlink()
|
||||
(radio_dir / "Unknown Content.md").write_text("this matches no cached note at all")
|
||||
problems = detect_problems(root, state)
|
||||
unknown_stray = next(p for p in problems if p.kind == "stray_file" and p.path.endswith("Unknown Content.md"))
|
||||
check("unmatched stray file has no fabricated suggestion", unknown_stray.detail == "", unknown_stray.detail)
|
||||
(radio_dir / "Unknown Content.md").unlink()
|
||||
|
||||
# --- broken_symlink: target no longer exists ---
|
||||
(radio_dir / "Ghost.md").symlink_to(Path("..") / ".hd" / "notes" / "does-not-exist.md")
|
||||
problems = detect_problems(root, state)
|
||||
check("broken symlink flagged", any(p.kind == "broken_symlink" for p in problems), problems)
|
||||
(radio_dir / "Ghost.md").unlink()
|
||||
|
||||
# --- foreign_symlink: points somewhere outside .hd/notes/ entirely ---
|
||||
outside_target = tmpdir / "outside.md"
|
||||
outside_target.write_text("not managed by hd")
|
||||
(radio_dir / "Manual Link.md").symlink_to(outside_target)
|
||||
problems = detect_problems(root, state)
|
||||
check("foreign symlink flagged", any(p.kind == "foreign_symlink" for p in problems), problems)
|
||||
(radio_dir / "Manual Link.md").unlink()
|
||||
|
||||
# --- back to healthy: zero problems again ---
|
||||
problems = detect_problems(root, state)
|
||||
check("clean again after removing all the injected problems", problems == [], problems)
|
||||
|
||||
# --- save_problems / load_problems round-trip ---
|
||||
fake_problems = [Problem("stray_file", "radio/x.md", "content matches note 'id7'")]
|
||||
save_problems(hd_dir, fake_problems)
|
||||
check(".hd/problems.json was created", (hd_dir / "problems.json").exists())
|
||||
loaded = load_problems(hd_dir)
|
||||
check("round-tripped problem matches", loaded == fake_problems, loaded)
|
||||
check("Problem.__str__ produces a readable message",
|
||||
"content matches note 'id7'" in str(fake_problems[0]), str(fake_problems[0]))
|
||||
|
||||
# --- ReconcileLock actually provides mutual exclusion (real flock) ---
|
||||
lock_path = hd_dir / ".lock"
|
||||
held = threading.Event()
|
||||
release = threading.Event()
|
||||
|
||||
def holder():
|
||||
with ReconcileLock(hd_dir):
|
||||
held.set()
|
||||
release.wait(timeout=5)
|
||||
|
||||
t = threading.Thread(target=holder, daemon=True)
|
||||
t.start()
|
||||
held.wait(timeout=5)
|
||||
|
||||
# A second, independent file descriptor to the same lock file must
|
||||
# NOT be acquirable non-blocking while the thread above holds it.
|
||||
fd2 = os.open(lock_path, os.O_CREAT | os.O_RDWR, 0o600)
|
||||
try:
|
||||
fcntl.flock(fd2, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
check("flock actually blocks a concurrent holder", False, "acquired when it should have blocked")
|
||||
fcntl.flock(fd2, fcntl.LOCK_UN)
|
||||
except BlockingIOError:
|
||||
check("flock actually blocks a concurrent holder", True)
|
||||
finally:
|
||||
os.close(fd2)
|
||||
|
||||
release.set()
|
||||
t.join(timeout=5)
|
||||
|
||||
# Now that the thread released it, a fresh acquire must succeed.
|
||||
fd3 = os.open(lock_path, os.O_CREAT | os.O_RDWR, 0o600)
|
||||
try:
|
||||
fcntl.flock(fd3, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
check("lock is acquirable again after release", True)
|
||||
fcntl.flock(fd3, fcntl.LOCK_UN)
|
||||
except BlockingIOError:
|
||||
check("lock is acquirable again after release", False, "still blocked")
|
||||
finally:
|
||||
os.close(fd3)
|
||||
|
||||
check("marker file is gone after the lock is released", not (hd_dir / ".reconciling.lock").exists())
|
||||
|
||||
finally:
|
||||
shutil.rmtree(tmpdir, ignore_errors=True)
|
||||
|
||||
print(f"\n{len(PASS)} passed, {len(FAIL)} failed")
|
||||
return 0 if not FAIL else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
188
hd-cli/test_hd_tag_cli.py
Normal file
188
hd-cli/test_hd_tag_cli.py
Normal file
@@ -0,0 +1,188 @@
|
||||
#!/usr/bin/env python3
|
||||
import json
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(__import__("pathlib").Path(__file__).resolve().parent.parent / "hd_common"))
|
||||
import socketio
|
||||
from werkzeug.serving import make_server
|
||||
from werkzeug.wrappers import Request, Response
|
||||
|
||||
from hd_client import apply_operation
|
||||
from hd_core import parse_current_tags, parse_frontmatter
|
||||
|
||||
PASS = []
|
||||
FAIL = []
|
||||
|
||||
|
||||
def check(name, cond, detail=""):
|
||||
if cond:
|
||||
PASS.append(name)
|
||||
else:
|
||||
FAIL.append((name, detail))
|
||||
print(f"FAIL: {name} {detail}")
|
||||
|
||||
|
||||
def apply_operation_strict(text, op):
|
||||
for c in op:
|
||||
if isinstance(c, bool):
|
||||
raise ValueError(f"unknown operation: {c!r}")
|
||||
if isinstance(c, int) and c == 0:
|
||||
raise ValueError(f"unknown operation: {c!r}")
|
||||
return apply_operation(text, op)
|
||||
|
||||
|
||||
class CombinedFakeServer:
|
||||
"""Serves /history, /<id>/download, AND the realtime Socket.IO channel
|
||||
from one shared note store -- close enough to real HedgeDoc that `hd
|
||||
sync` and `hd tag`/`hd untag` can both run against it in the same test,
|
||||
the way they'd run against a real server."""
|
||||
|
||||
def __init__(self, port):
|
||||
self.notes = {} # id -> {"title", "tags", "content", "time", "revision"}
|
||||
self.port = port
|
||||
self.lock = threading.Lock()
|
||||
|
||||
self.sio = socketio.Server(async_mode="threading", cors_allowed_origins="*")
|
||||
|
||||
@self.sio.event
|
||||
def connect(sid, environ, auth):
|
||||
from urllib.parse import parse_qs
|
||||
qs = parse_qs(environ.get("QUERY_STRING", ""))
|
||||
note_id = (qs.get("noteId") or [None])[0]
|
||||
with self.lock:
|
||||
n = self.notes.get(note_id)
|
||||
if n is None:
|
||||
return
|
||||
self.sio.save_session(sid, {"note_id": note_id})
|
||||
self.sio.emit("doc", {"str": n["content"], "revision": n["revision"], "clients": []}, to=sid)
|
||||
|
||||
@self.sio.on("operation")
|
||||
def on_operation(sid, base_revision, operation, selection):
|
||||
with self.lock:
|
||||
session = self.sio.get_session(sid)
|
||||
note_id = session["note_id"]
|
||||
n = self.notes[note_id]
|
||||
if base_revision != n["revision"]:
|
||||
return
|
||||
try:
|
||||
n["content"] = apply_operation_strict(n["content"], operation)
|
||||
except Exception as exc:
|
||||
print("[fake server] rejected:", exc, operation)
|
||||
return
|
||||
n["revision"] += 1
|
||||
n["time"] += 1 # a real edit always moves /history's time
|
||||
self.sio.emit("ack", n["revision"], to=sid)
|
||||
|
||||
self._socketio_app = socketio.WSGIApp(self.sio)
|
||||
|
||||
def wsgi(environ, start_response):
|
||||
request = Request(environ)
|
||||
if request.path == "/history":
|
||||
with self.lock:
|
||||
history = []
|
||||
for nid, n in self.notes.items():
|
||||
# Tags are derived from the note's own content, exactly
|
||||
# like real HedgeDoc's Note.parseNoteInfo does -- not
|
||||
# from a separate field this test tracks by hand.
|
||||
fm = parse_frontmatter(n["content"])
|
||||
tags = parse_current_tags(__import__("yaml").safe_load(fm["yaml_str"]) or {}) if fm else []
|
||||
history.append({"id": nid, "text": n["title"], "tags": tags, "time": n["time"]})
|
||||
resp = Response(json.dumps({"history": history}), mimetype="application/json")
|
||||
return resp(environ, start_response)
|
||||
if request.path.endswith("/download"):
|
||||
nid = request.path.split("/")[1]
|
||||
with self.lock:
|
||||
n = self.notes.get(nid)
|
||||
resp = Response(n["content"] if n else "", mimetype="text/markdown",
|
||||
status=200 if n else 404)
|
||||
return resp(environ, start_response)
|
||||
return socketio.WSGIApp(self.sio)(environ, start_response)
|
||||
|
||||
self.srv = make_server("127.0.0.1", port, wsgi, threaded=True)
|
||||
self.thread = threading.Thread(target=self.srv.serve_forever, daemon=True)
|
||||
|
||||
def start(self):
|
||||
self.thread.start()
|
||||
|
||||
def stop(self):
|
||||
self.srv.shutdown()
|
||||
|
||||
|
||||
def free_port():
|
||||
import socket
|
||||
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
s.bind(("127.0.0.1", 0))
|
||||
p = s.getsockname()[1]
|
||||
s.close()
|
||||
return p
|
||||
|
||||
|
||||
def run_hd(*args, cwd):
|
||||
return subprocess.run(
|
||||
[sys.executable, str(Path(__file__).parent / "hdc"), *args],
|
||||
cwd=cwd, capture_output=True, text=True, timeout=15,
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
port = free_port()
|
||||
server = CombinedFakeServer(port)
|
||||
server.notes["n1"] = {
|
||||
"title": "Fox Hunt Notes",
|
||||
"content": "---\ntitle: Fox Hunt Notes\ntags: radio\n---\n\nfrequencies here",
|
||||
"time": 1, "revision": 0,
|
||||
}
|
||||
server.start()
|
||||
time.sleep(0.2)
|
||||
|
||||
tmpdir = Path(tempfile.mkdtemp(prefix="hd-tag-cli-test-"))
|
||||
target = tmpdir / "notes"
|
||||
|
||||
try:
|
||||
r = run_hd("init", f"http://127.0.0.1:{port}", "--cookie", "session=abc",
|
||||
"--dir", str(target), cwd=tmpdir)
|
||||
check("init ok", r.returncode == 0, r.stderr)
|
||||
check("initial symlink present", (target / "radio" / "Fox Hunt Notes").is_symlink())
|
||||
|
||||
# --- hd tag by title: adds a new tag, writes to server, resyncs locally ---
|
||||
r2 = run_hd("tag", "Fox Hunt Notes", "reference", "--dir", str(target), cwd=tmpdir)
|
||||
check("hd tag exits 0", r2.returncode == 0, r2.stderr)
|
||||
check("hd tag reports the new tag list", "reference" in r2.stdout, r2.stdout)
|
||||
fm = parse_frontmatter(server.notes["n1"]["content"])
|
||||
server_tags = parse_current_tags(__import__("yaml").safe_load(fm["yaml_str"])) if fm else []
|
||||
check("server-side frontmatter actually updated",
|
||||
server_tags == ["radio", "reference"], server_tags)
|
||||
check("new symlink appeared locally", (target / "reference" / "Fox Hunt Notes").is_symlink())
|
||||
check("old symlink still present too", (target / "radio" / "Fox Hunt Notes").is_symlink())
|
||||
|
||||
# --- hd tag by id ---
|
||||
r3 = run_hd("tag", "n1", "urgent", "--dir", str(target), cwd=tmpdir)
|
||||
check("hd tag by id exits 0", r3.returncode == 0, r3.stderr)
|
||||
check("tag-by-id symlink appeared", (target / "urgent" / "Fox Hunt Notes").is_symlink())
|
||||
|
||||
# --- hd untag removes it again ---
|
||||
r4 = run_hd("untag", "n1", "urgent", "--dir", str(target), cwd=tmpdir)
|
||||
check("hd untag exits 0", r4.returncode == 0, r4.stderr)
|
||||
check("untagged symlink removed", not (target / "urgent" / "Fox Hunt Notes").exists())
|
||||
|
||||
# --- resolving an unknown note fails cleanly, no crash ---
|
||||
r5 = run_hd("tag", "does-not-exist", "x", "--dir", str(target), cwd=tmpdir)
|
||||
check("unknown note ref fails cleanly", r5.returncode != 0)
|
||||
check("unknown note ref explains why", "No known note" in r5.stderr, r5.stderr)
|
||||
|
||||
finally:
|
||||
server.stop()
|
||||
shutil.rmtree(tmpdir, ignore_errors=True)
|
||||
|
||||
print(f"\n{len(PASS)} passed, {len(FAIL)} failed")
|
||||
return 0 if not FAIL else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
227
hd-cli/test_hd_tag_stale_history.py
Normal file
227
hd-cli/test_hd_tag_stale_history.py
Normal file
@@ -0,0 +1,227 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Reproduces the bug Joakim hit for real: after 'hdc untag', the removed
|
||||
tag's symlink stayed in place for several seconds. Every existing fake
|
||||
server in this test suite derives /history's tags live from the note's
|
||||
current content on every request -- perfectly, instantly consistent,
|
||||
which is exactly the kind of too-forgiving fake server that already hid
|
||||
more than one bug in this project (see CHANGES-0.7.14, -0.7.15). Real
|
||||
HedgeDoc's /history reflects a DB view that's flushed on a delay, same as
|
||||
content -- this test's StaleHistoryFakeServer deliberately reproduces
|
||||
that: /history keeps reporting the OLD tags for a configurable delay
|
||||
after a write actually lands.
|
||||
"""
|
||||
import json
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "hd_common"))
|
||||
import socketio
|
||||
from werkzeug.serving import make_server
|
||||
from werkzeug.wrappers import Request, Response
|
||||
|
||||
from hd_client import apply_operation
|
||||
from hd_core import parse_current_tags, parse_frontmatter
|
||||
|
||||
PASS = []
|
||||
FAIL = []
|
||||
|
||||
|
||||
def check(name, cond, detail=""):
|
||||
if cond:
|
||||
PASS.append(name)
|
||||
else:
|
||||
FAIL.append((name, detail))
|
||||
print(f"FAIL: {name} {detail}")
|
||||
|
||||
|
||||
def apply_operation_strict(text, op):
|
||||
for c in op:
|
||||
if isinstance(c, bool):
|
||||
raise ValueError(f"unknown operation: {c!r}")
|
||||
if isinstance(c, int) and c == 0:
|
||||
raise ValueError(f"unknown operation: {c!r}")
|
||||
return apply_operation(text, op)
|
||||
|
||||
|
||||
class StaleHistoryFakeServer:
|
||||
"""Like test_hd_tag_cli.py's CombinedFakeServer, but /history's view of
|
||||
a note's tags/time is deliberately DELAYED by `history_delay` seconds
|
||||
after a write actually completes -- reproducing HedgeDoc's own
|
||||
DB-flush lag instead of the instant consistency every other fake
|
||||
server in this suite gives for free."""
|
||||
|
||||
def __init__(self, port, history_delay=1.5):
|
||||
self.notes = {} # id -> {"title", "content", "time", "revision"}
|
||||
self.history_delay = history_delay
|
||||
self.port = port
|
||||
self.lock = threading.Lock()
|
||||
|
||||
self.sio = socketio.Server(async_mode="threading", cors_allowed_origins="*")
|
||||
|
||||
@self.sio.event
|
||||
def connect(sid, environ, auth):
|
||||
from urllib.parse import parse_qs
|
||||
qs = parse_qs(environ.get("QUERY_STRING", ""))
|
||||
note_id = (qs.get("noteId") or [None])[0]
|
||||
with self.lock:
|
||||
n = self.notes.get(note_id)
|
||||
if n is None:
|
||||
return
|
||||
self.sio.save_session(sid, {"note_id": note_id})
|
||||
self.sio.emit("doc", {"str": n["content"], "revision": n["revision"], "clients": []}, to=sid)
|
||||
|
||||
@self.sio.on("operation")
|
||||
def on_operation(sid, base_revision, operation, selection):
|
||||
with self.lock:
|
||||
session = self.sio.get_session(sid)
|
||||
note_id = session["note_id"]
|
||||
n = self.notes[note_id]
|
||||
if base_revision != n["revision"]:
|
||||
return
|
||||
try:
|
||||
n["content"] = apply_operation_strict(n["content"], operation)
|
||||
except Exception as exc:
|
||||
print("[fake server] rejected:", exc, operation)
|
||||
return
|
||||
n["revision"] += 1
|
||||
n["time"] += 1
|
||||
self.sio.emit("ack", n["revision"], to=sid)
|
||||
# The write is confirmed to the client (and to write_tags()'s
|
||||
# caller) immediately, same as the real thing. /history's view
|
||||
# of it, deliberately, is not -- scheduled to "flush" later.
|
||||
threading.Timer(self.history_delay, self._flush_history, args=(note_id,)).start()
|
||||
|
||||
self._socketio_app = socketio.WSGIApp(self.sio)
|
||||
|
||||
def wsgi(environ, start_response):
|
||||
request = Request(environ)
|
||||
if request.path == "/history":
|
||||
with self.lock:
|
||||
history = []
|
||||
for nid, n in self.notes.items():
|
||||
fm = parse_frontmatter(n["committed_content"])
|
||||
tags = parse_current_tags(__import__("yaml").safe_load(fm["yaml_str"]) or {}) if fm else []
|
||||
history.append({"id": nid, "text": n["title"], "tags": tags, "time": n["committed_time"]})
|
||||
resp = Response(json.dumps({"history": history}), mimetype="application/json")
|
||||
return resp(environ, start_response)
|
||||
if request.path.endswith("/download"):
|
||||
nid = request.path.split("/")[1]
|
||||
with self.lock:
|
||||
n = self.notes.get(nid)
|
||||
resp = Response(n["content"] if n else "", mimetype="text/markdown",
|
||||
status=200 if n else 404)
|
||||
return resp(environ, start_response)
|
||||
return self._socketio_app(environ, start_response)
|
||||
|
||||
self.srv = make_server("127.0.0.1", port, wsgi, threaded=True)
|
||||
self.thread = threading.Thread(target=self.srv.serve_forever, daemon=True)
|
||||
|
||||
def _flush_history(self, note_id):
|
||||
with self.lock:
|
||||
n = self.notes.get(note_id)
|
||||
if n:
|
||||
n["committed_content"] = n["content"]
|
||||
n["committed_time"] = n["time"]
|
||||
|
||||
def add_note(self, note_id, title, content, t=1):
|
||||
self.notes[note_id] = {
|
||||
"title": title, "content": content, "committed_content": content,
|
||||
"time": t, "committed_time": t, "revision": 0,
|
||||
}
|
||||
|
||||
def start(self):
|
||||
self.thread.start()
|
||||
|
||||
def stop(self):
|
||||
self.srv.shutdown()
|
||||
|
||||
|
||||
def free_port():
|
||||
import socket
|
||||
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
s.bind(("127.0.0.1", 0))
|
||||
p = s.getsockname()[1]
|
||||
s.close()
|
||||
return p
|
||||
|
||||
|
||||
def run_hdc(*args, cwd):
|
||||
return subprocess.run(
|
||||
[sys.executable, str(Path(__file__).parent / "hdc"), *args],
|
||||
cwd=cwd, capture_output=True, text=True, timeout=15,
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
port = free_port()
|
||||
# Long enough to reliably still be stale through the ENTIRE 'hdc untag'
|
||||
# command's execution, including its own trailing sync -- 1.5s was
|
||||
# tried first and wasn't long enough: real subprocess + multiple
|
||||
# network round trips (the write's own socket connection, then a
|
||||
# fresh /history HTTP GET) routinely took longer than that in
|
||||
# practice, so the first version of this test passed by accident,
|
||||
# without ever actually exercising the race it was meant to catch.
|
||||
server = StaleHistoryFakeServer(port, history_delay=8.0)
|
||||
server.add_note("n1", "FOI", "---\ntitle: FOI\ntags: TaBort\n---\n\ncontent here")
|
||||
server.start()
|
||||
time.sleep(0.2)
|
||||
|
||||
tmpdir = Path(tempfile.mkdtemp(prefix="hd-stale-history-test-"))
|
||||
target = tmpdir / "notes"
|
||||
|
||||
try:
|
||||
r_init = run_hdc("init", f"http://127.0.0.1:{port}", "--cookie", "session=1",
|
||||
"--dir", str(target), cwd=str(tmpdir))
|
||||
check("init succeeded", r_init.returncode == 0, r_init.stdout + r_init.stderr)
|
||||
check("initial sync created the TaBort symlink", (target / "TaBort" / "FOI").is_symlink(),
|
||||
list((target / "TaBort").iterdir()) if (target / "TaBort").exists() else "no TaBort dir")
|
||||
|
||||
# This is the exact scenario Joakim hit: untag, then check the
|
||||
# symlink IMMEDIATELY -- while /history is still deliberately
|
||||
# reporting the OLD tag list (history_delay hasn't elapsed yet).
|
||||
r_untag = run_hdc("untag", "n1", "TaBort", "--dir", str(target), cwd=str(tmpdir))
|
||||
check("untag command succeeded", r_untag.returncode == 0, r_untag.stdout + r_untag.stderr)
|
||||
check("write confirmed no tags remain", "tags now [(none)]" in r_untag.stdout, r_untag.stdout)
|
||||
|
||||
still_there = (target / "TaBort" / "FOI").exists()
|
||||
check("symlink is gone IMMEDIATELY after untag, not several seconds later "
|
||||
"(the actual bug: update_note_tags_locally applies the write's own "
|
||||
"confirmed result directly, without waiting for /history to catch up)",
|
||||
not still_there, "still present!" if still_there else "correctly removed")
|
||||
|
||||
# And state.json should already reflect it too, not just the filesystem.
|
||||
from hd_core import State
|
||||
state = State.load(target / ".hd")
|
||||
# Matches reconcile()'s own convention: an untagged note is recorded
|
||||
# as ["untagged"], never an empty list -- not [], see hd_core.py's
|
||||
# UNTAGGED substitution in both reconcile() and _sync_note_symlinks().
|
||||
from hd_core import UNTAGGED
|
||||
check("state.json already shows the note as untagged (not still 'TaBort')",
|
||||
state.notes["n1"].tags == [UNTAGGED], state.notes["n1"].tags)
|
||||
check("state.json's symlinks dict no longer has TaBort", "TaBort" not in state.notes["n1"].symlinks,
|
||||
state.notes["n1"].symlinks)
|
||||
|
||||
# Once /history actually catches up, a later sync must still agree
|
||||
# (this direct update should be idempotent with reconcile(), not
|
||||
# just a one-off hack that diverges from it).
|
||||
time.sleep(8.5)
|
||||
r_sync = run_hdc("sync", "--dir", str(target), cwd=str(tmpdir))
|
||||
check("later sync (once /history has caught up) succeeds", r_sync.returncode == 0, r_sync.stdout)
|
||||
check("still no TaBort symlink after /history catches up too",
|
||||
not (target / "TaBort" / "FOI").exists())
|
||||
|
||||
finally:
|
||||
server.stop()
|
||||
shutil.rmtree(tmpdir, ignore_errors=True)
|
||||
|
||||
print(f"\n{len(PASS)} passed, {len(FAIL)} failed")
|
||||
return 0 if not FAIL else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
171
hd-cli/test_hd_tags.py
Normal file
171
hd-cli/test_hd_tags.py
Normal file
@@ -0,0 +1,171 @@
|
||||
#!/usr/bin/env python3
|
||||
import sys
|
||||
from pathlib import Path
|
||||
sys.path.insert(0, str(__import__("pathlib").Path(__file__).resolve().parent.parent / "hd_common"))
|
||||
|
||||
from hd_core import (
|
||||
FrontmatterError, NoteState, State, compute_tag_patch, parse_current_tags,
|
||||
parse_frontmatter, resolve_note_ref,
|
||||
)
|
||||
|
||||
PASS = []
|
||||
FAIL = []
|
||||
|
||||
|
||||
def check(name, cond, detail=""):
|
||||
if cond:
|
||||
PASS.append(name)
|
||||
else:
|
||||
FAIL.append((name, detail))
|
||||
print(f"FAIL: {name} {detail}")
|
||||
|
||||
|
||||
def apply_patch(text, patch):
|
||||
start, end, repl = patch
|
||||
return text[:start] + repl + text[end:]
|
||||
|
||||
|
||||
def main():
|
||||
# --- parse_frontmatter ---
|
||||
check("no frontmatter -> None", parse_frontmatter("# just a heading\nbody") is None)
|
||||
fm = parse_frontmatter("---\ntitle: X\ntags: a, b\n---\nbody")
|
||||
check("frontmatter detected", fm is not None)
|
||||
check("yaml_str excludes closing delimiter",
|
||||
fm["yaml_str"] == "---\ntitle: X\ntags: a, b", repr(fm["yaml_str"]))
|
||||
fm_dots = parse_frontmatter("---\ntitle: X\n...\nbody")
|
||||
check("'...' closing delimiter also works", fm_dots is not None)
|
||||
check("unterminated frontmatter -> None", parse_frontmatter("---\ntitle: X\nno closing") is None)
|
||||
|
||||
# --- parse_current_tags: mirrors extractNoteTags exactly ---
|
||||
check("comma string parsed and deduped",
|
||||
parse_current_tags({"tags": "work, radio, work"}) == ["work", "radio"])
|
||||
check("bare number accepted (matches JS typeof check)",
|
||||
parse_current_tags({"tags": 42}) == ["42"])
|
||||
check("YAML list silently ignored (matches server behavior)",
|
||||
parse_current_tags({"tags": ["work", "radio"]}) == [])
|
||||
check("missing tags key -> empty", parse_current_tags({"title": "X"}) == [])
|
||||
check("bool tags value ignored (bool is technically an int subclass in Python)",
|
||||
parse_current_tags({"tags": True}) == [])
|
||||
|
||||
# --- compute_tag_patch: round-trip correctness ---
|
||||
text = "---\ntitle: My Note\ntags: work\n---\n\n# Body\ncontent here"
|
||||
patch = compute_tag_patch(text, ["work", "radio"])
|
||||
result = apply_patch(text, patch)
|
||||
check("add tag: title preserved", "title: My Note" in result, result)
|
||||
check("add tag: new tag present", parse_current_tags(
|
||||
__import__("yaml").safe_load(parse_frontmatter(result)["yaml_str"])) == ["work", "radio"])
|
||||
check("add tag: body untouched", result.endswith("# Body\ncontent here"), result)
|
||||
check("add tag: patch doesn't touch the whole document",
|
||||
patch[1] < len(text), f"patch end={patch[1]} doc len={len(text)}")
|
||||
|
||||
# untag down to zero -> tags key removed entirely, not left as ""
|
||||
text2 = "---\ntitle: Solo\ntags: onlyone\n---\nbody"
|
||||
patch2 = compute_tag_patch(text2, [])
|
||||
result2 = apply_patch(text2, patch2)
|
||||
meta2 = __import__("yaml").safe_load(parse_frontmatter(result2)["yaml_str"])
|
||||
check("untag to zero: tags key removed, not empty string", "tags" not in meta2, meta2)
|
||||
check("untag to zero: title still preserved", meta2.get("title") == "Solo", meta2)
|
||||
|
||||
# no frontmatter at all -> a fresh block gets inserted at position 0
|
||||
text3 = "# No frontmatter here\njust markdown"
|
||||
patch3 = compute_tag_patch(text3, ["new"])
|
||||
check("no frontmatter: patch is a pure insert at 0", patch3[0] == 0 and patch3[1] == 0, patch3)
|
||||
result3 = apply_patch(text3, patch3)
|
||||
check("no frontmatter: original body still present verbatim",
|
||||
result3.endswith(text3), result3)
|
||||
fm3 = parse_frontmatter(result3)
|
||||
check("no frontmatter: new block is now valid, parseable frontmatter", fm3 is not None)
|
||||
check("no frontmatter: new tag present after insert",
|
||||
parse_current_tags(__import__("yaml").safe_load(fm3["yaml_str"])) == ["new"])
|
||||
|
||||
# invalid YAML frontmatter -> refuse rather than clobber
|
||||
bad = "---\ntitle: [unterminated\n---\nbody"
|
||||
try:
|
||||
compute_tag_patch(bad, ["x"])
|
||||
check("invalid YAML raises FrontmatterError", False, "did not raise")
|
||||
except FrontmatterError:
|
||||
check("invalid YAML raises FrontmatterError", True)
|
||||
|
||||
# frontmatter that parses to a non-mapping (e.g. a bare scalar) -> refuse
|
||||
scalar = "---\njust a string, not a mapping\n---\nbody"
|
||||
try:
|
||||
compute_tag_patch(scalar, ["x"])
|
||||
check("non-mapping frontmatter raises FrontmatterError", False, "did not raise")
|
||||
except FrontmatterError:
|
||||
check("non-mapping frontmatter raises FrontmatterError", True)
|
||||
|
||||
# --- resolve_note_ref ---
|
||||
state = State()
|
||||
state.notes["id1"] = NoteState(title="Fox Hunt", tags=["radio"], symlinks={"radio": "Fox Hunt.md"})
|
||||
state.notes["id2"] = NoteState(title="Fox Hunt", tags=["work"], symlinks={"work": "Fox Hunt.md"})
|
||||
state.notes["id3"] = NoteState(title="Grocery List", tags=["personal"], symlinks={"personal": "Grocery List.md"})
|
||||
|
||||
check("resolve by exact id", resolve_note_ref(Path("/tmp/nonexistent-hd-root-xyz"), state, "id3") == "id3")
|
||||
check("resolve by unique title", resolve_note_ref(Path("/tmp/nonexistent-hd-root-xyz"), state, "Grocery List") == "id3")
|
||||
check("resolve by title is case-insensitive", resolve_note_ref(Path("/tmp/nonexistent-hd-root-xyz"), state, "grocery list") == "id3")
|
||||
try:
|
||||
resolve_note_ref(Path("/tmp/nonexistent-hd-root-xyz"), state, "Fox Hunt")
|
||||
check("ambiguous title raises", False, "did not raise")
|
||||
except ValueError as exc:
|
||||
check("ambiguous title raises", True)
|
||||
check("ambiguous title error names both ids", "id1" in str(exc) and "id2" in str(exc), str(exc))
|
||||
try:
|
||||
resolve_note_ref(Path("/tmp/nonexistent-hd-root-xyz"), state, "nonexistent")
|
||||
check("unknown ref raises", False, "did not raise")
|
||||
except ValueError:
|
||||
check("unknown ref raises", True)
|
||||
|
||||
# --- resolve_note_ref: path resolution is cwd-relative, and wins over
|
||||
# a same-named title elsewhere -- the bug Joakim reported: 'FOI' or
|
||||
# '../work/FOI' used to resolve relative to ROOT, not to wherever the
|
||||
# user actually was, and never took priority over a global title match ---
|
||||
import shutil, tempfile
|
||||
tmpdir = Path(tempfile.mkdtemp(prefix="hd-resolve-path-test-"))
|
||||
try:
|
||||
root2 = tmpdir / "notes"
|
||||
hd_dir2 = root2 / ".hd"
|
||||
(hd_dir2 / "notes").mkdir(parents=True)
|
||||
(hd_dir2 / "notes" / "real-id.md").write_text("---\ntitle: Ambiguous\n---\n\nbody")
|
||||
|
||||
radio_dir = root2 / "radio"
|
||||
work_dir = root2 / "work"
|
||||
radio_dir.mkdir()
|
||||
work_dir.mkdir()
|
||||
# The symlink actually lives in radio/ ...
|
||||
(radio_dir / "FOI").symlink_to(Path("..") / ".hd" / "notes" / "real-id.md")
|
||||
# ... but a note with the SAME TITLE also exists elsewhere, with a
|
||||
# different id -- resolving 'FOI' from radio/ must never land on
|
||||
# this one just because titles happen to collide.
|
||||
state2 = State()
|
||||
state2.notes["real-id"] = NoteState(title="Ambiguous", tags=["radio"], symlinks={"radio": "FOI"})
|
||||
state2.notes["decoy-id"] = NoteState(title="FOI", tags=["work"], symlinks={"work": "SomeOtherName"})
|
||||
|
||||
result = resolve_note_ref(root2, state2, "FOI", cwd=radio_dir)
|
||||
check("bare name resolves to the symlink actually in cwd, not a same-named title elsewhere",
|
||||
result == "real-id", result)
|
||||
|
||||
# From work/, the SAME bare name 'FOI' must NOT resolve to
|
||||
# radio/FOI (that's not the directory the user is standing in) --
|
||||
# no symlink named FOI exists in work/ itself, so this falls
|
||||
# through to the (still-present, unchanged) title search, which
|
||||
# correctly finds the OTHER note titled "FOI" -- a different id
|
||||
# than the one radio/FOI resolves to.
|
||||
result2 = resolve_note_ref(root2, state2, "FOI", cwd=work_dir)
|
||||
check("same bare name from a DIFFERENT directory resolves differently "
|
||||
"(falls through to title search, finds the note titled FOI instead)",
|
||||
result2 == "decoy-id", result2)
|
||||
|
||||
# A relative path with '..' resolves against cwd, not root.
|
||||
result3 = resolve_note_ref(root2, state2, "../radio/FOI", cwd=work_dir)
|
||||
check("'../radio/FOI' from work/ resolves against cwd (finds radio/FOI), "
|
||||
"not against root (which would look for a nonexistent root/../radio/FOI)",
|
||||
result3 == "real-id", result3)
|
||||
finally:
|
||||
shutil.rmtree(tmpdir, ignore_errors=True)
|
||||
|
||||
print(f"\n{len(PASS)} passed, {len(FAIL)} failed")
|
||||
return 0 if not FAIL else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
146
hd-cli/test_hd_write.py
Normal file
146
hd-cli/test_hd_write.py
Normal file
@@ -0,0 +1,146 @@
|
||||
#!/usr/bin/env python3
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(__import__("pathlib").Path(__file__).resolve().parent.parent / "hd_common"))
|
||||
import socketio
|
||||
from werkzeug.serving import make_server
|
||||
|
||||
from hd_client import apply_operation
|
||||
from hd_core import parse_current_tags, parse_frontmatter, write_tags
|
||||
|
||||
PASS = []
|
||||
FAIL = []
|
||||
|
||||
|
||||
def check(name, cond, detail=""):
|
||||
if cond:
|
||||
PASS.append(name)
|
||||
else:
|
||||
FAIL.append((name, detail))
|
||||
print(f"FAIL: {name} {detail}")
|
||||
|
||||
|
||||
def apply_operation_strict(text, op):
|
||||
for c in op:
|
||||
if isinstance(c, bool):
|
||||
raise ValueError(f"unknown operation: {c!r}")
|
||||
if isinstance(c, int) and c == 0:
|
||||
raise ValueError(f"unknown operation: {c!r}")
|
||||
return apply_operation(text, op)
|
||||
|
||||
|
||||
class FakeServer:
|
||||
def __init__(self, initial_text, port):
|
||||
self.sio = socketio.Server(async_mode="threading", cors_allowed_origins="*")
|
||||
self.text = initial_text
|
||||
self.revision = 0
|
||||
self.lock = threading.Lock()
|
||||
self.operations = []
|
||||
|
||||
@self.sio.event
|
||||
def connect(sid, environ, auth):
|
||||
with self.lock:
|
||||
self.sio.emit("doc", {"str": self.text, "revision": self.revision, "clients": []}, to=sid)
|
||||
|
||||
@self.sio.on("operation")
|
||||
def on_operation(sid, base_revision, operation, selection):
|
||||
with self.lock:
|
||||
self.operations.append(operation)
|
||||
if base_revision != self.revision:
|
||||
return
|
||||
try:
|
||||
self.text = apply_operation_strict(self.text, operation)
|
||||
except Exception as exc:
|
||||
print("[fake server] rejected:", exc, operation)
|
||||
return
|
||||
self.revision += 1
|
||||
self.sio.emit("ack", self.revision, to=sid)
|
||||
|
||||
self.app = socketio.WSGIApp(self.sio)
|
||||
self.srv = make_server("127.0.0.1", port, self.app, threaded=True)
|
||||
self.thread = threading.Thread(target=self.srv.serve_forever, daemon=True)
|
||||
|
||||
def start(self):
|
||||
self.thread.start()
|
||||
|
||||
def stop(self):
|
||||
self.srv.shutdown()
|
||||
|
||||
|
||||
def free_port():
|
||||
import socket
|
||||
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
s.bind(("127.0.0.1", 0))
|
||||
p = s.getsockname()[1]
|
||||
s.close()
|
||||
return p
|
||||
|
||||
|
||||
def main():
|
||||
# --- 1. Add a tag to a note that already has frontmatter + one tag ---
|
||||
initial = "---\ntitle: Fox Hunt Notes\ntags: radio\n---\n\n# Frequencies\n144.390 MHz APRS\n"
|
||||
port = free_port()
|
||||
server = FakeServer(initial, port)
|
||||
server.start()
|
||||
time.sleep(0.2)
|
||||
|
||||
new_tags = write_tags(f"http://127.0.0.1:{port}", "test=1", "note1",
|
||||
lambda tags: tags if "reference" in tags else [*tags, "reference"])
|
||||
|
||||
check("write_tags returns the new tag list", new_tags == ["radio", "reference"], new_tags)
|
||||
check("server revision advanced exactly once", server.revision == 1, server.revision)
|
||||
fm = parse_frontmatter(server.text)
|
||||
check("server text still has valid frontmatter", fm is not None)
|
||||
import yaml
|
||||
meta = yaml.safe_load(fm["yaml_str"])
|
||||
check("title untouched by the tag edit", meta.get("title") == "Fox Hunt Notes", meta)
|
||||
check("tags updated on the server", parse_current_tags(meta) == ["radio", "reference"], meta)
|
||||
check("body untouched by the tag edit",
|
||||
server.text.endswith("# Frequencies\n144.390 MHz APRS\n"), repr(server.text))
|
||||
|
||||
check("edit was minimal, not a full-document replace",
|
||||
len(server.operations) == 1 and len(server.operations[0]) <= 4,
|
||||
server.operations)
|
||||
# Minimality is already proven structurally above (body untouched, title
|
||||
# untouched, exactly one operation) -- a byte-count heuristic on top of
|
||||
# that is fragile (YAML re-dump size varies) and adds no real coverage.
|
||||
|
||||
server.stop()
|
||||
|
||||
# --- 2. Untag down to zero on a note with no frontmatter at all ---
|
||||
initial2 = "# Bare note\nno frontmatter here at all"
|
||||
port2 = free_port()
|
||||
server2 = FakeServer(initial2, port2)
|
||||
server2.start()
|
||||
time.sleep(0.2)
|
||||
|
||||
new_tags2 = write_tags(f"http://127.0.0.1:{port2}", "test=1", "note2",
|
||||
lambda tags: [*tags, "urgent"]) # note had zero tags -> gains one
|
||||
check("tag added to a previously bare note", new_tags2 == ["urgent"], new_tags2)
|
||||
fm2 = parse_frontmatter(server2.text)
|
||||
check("frontmatter block was created", fm2 is not None)
|
||||
check("original body preserved verbatim after the frontmatter",
|
||||
server2.text.rstrip("\n").endswith(initial2), repr(server2.text))
|
||||
server2.stop()
|
||||
|
||||
# --- 3. No-op: mutate() returns the same tags -> no network write at all ---
|
||||
initial3 = "---\ntitle: Steady\ntags: keep\n---\nbody"
|
||||
port3 = free_port()
|
||||
server3 = FakeServer(initial3, port3)
|
||||
server3.start()
|
||||
time.sleep(0.2)
|
||||
result3 = write_tags(f"http://127.0.0.1:{port3}", "test=1", "note3", lambda tags: tags)
|
||||
check("no-op mutate returns tags unchanged", result3 == ["keep"], result3)
|
||||
check("no-op mutate sends no operation at all", server3.operations == [], server3.operations)
|
||||
check("no-op mutate leaves server revision at 0", server3.revision == 0, server3.revision)
|
||||
server3.stop()
|
||||
|
||||
print(f"\n{len(PASS)} passed, {len(FAIL)} failed")
|
||||
return 0 if not FAIL else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in New Issue
Block a user