margin-notes 0.1.0__tar.gz → 0.1.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (21) hide show
  1. {margin_notes-0.1.0 → margin_notes-0.1.1}/CHANGELOG.md +8 -0
  2. {margin_notes-0.1.0 → margin_notes-0.1.1}/PKG-INFO +5 -4
  3. {margin_notes-0.1.0 → margin_notes-0.1.1}/README.md +4 -3
  4. {margin_notes-0.1.0 → margin_notes-0.1.1}/src/margin_notes/__init__.py +1 -1
  5. {margin_notes-0.1.0 → margin_notes-0.1.1}/src/margin_notes/cli.py +48 -1
  6. {margin_notes-0.1.0 → margin_notes-0.1.1}/src/margin_notes/notes.py +19 -11
  7. {margin_notes-0.1.0 → margin_notes-0.1.1}/src/margin_notes/server.py +10 -1
  8. {margin_notes-0.1.0 → margin_notes-0.1.1}/src/margin_notes/static/review.js +38 -0
  9. {margin_notes-0.1.0 → margin_notes-0.1.1}/tests/test_browser.py +29 -0
  10. {margin_notes-0.1.0 → margin_notes-0.1.1}/tests/test_cli.py +70 -0
  11. {margin_notes-0.1.0 → margin_notes-0.1.1}/tests/test_notes.py +9 -0
  12. {margin_notes-0.1.0 → margin_notes-0.1.1}/tests/test_server.py +13 -1
  13. {margin_notes-0.1.0 → margin_notes-0.1.1}/.gitignore +0 -0
  14. {margin_notes-0.1.0 → margin_notes-0.1.1}/LICENSE +0 -0
  15. {margin_notes-0.1.0 → margin_notes-0.1.1}/pyproject.toml +0 -0
  16. {margin_notes-0.1.0 → margin_notes-0.1.1}/src/margin_notes/__main__.py +0 -0
  17. {margin_notes-0.1.0 → margin_notes-0.1.1}/src/margin_notes/py.typed +0 -0
  18. {margin_notes-0.1.0 → margin_notes-0.1.1}/src/margin_notes/render.py +0 -0
  19. {margin_notes-0.1.0 → margin_notes-0.1.1}/src/margin_notes/static/page.css +0 -0
  20. {margin_notes-0.1.0 → margin_notes-0.1.1}/tests/conftest.py +0 -0
  21. {margin_notes-0.1.0 → margin_notes-0.1.1}/tests/test_render.py +0 -0
@@ -1,5 +1,13 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.1 (2026-11-20)
4
+
5
+ - The notes panel shows the notes file's full path, with **Copy path** and **Copy JSON**
6
+ buttons. Copying also works over plain http on a LAN address (`--host 0.0.0.0`).
7
+ - On a machine running Tailscale, startup also prints its tailnet names. With `--host 0.0.0.0`
8
+ they're printed as URLs; otherwise as a hint. This uses the `tailscale` CLI, no new dependency.
9
+ - The notes API now also returns `notes_path` (absolute) and `notes_json` (the file's contents).
10
+
3
11
  ## 0.1.0 (2026-11-18)
4
12
 
5
13
  First release.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: margin-notes
3
- Version: 0.1.0
3
+ Version: 0.1.1
4
4
  Summary: Review HTML and Markdown in your browser: highlight passages, comment, and save the notes as JSON beside each document.
5
5
  Project-URL: Homepage, https://github.com/jbn/margin-notes
6
6
  Project-URL: Repository, https://github.com/jbn/margin-notes
@@ -70,8 +70,9 @@ uvx margin-notes ~/reports --host 0.0.0.0 --port 9000
70
70
  - **Diagrams** in ```` ```mermaid ```` fences.
71
71
  - Add `?raw=1` to any document URL to get the source.
72
72
  - **Reviewing:** select text and click **💬 Comment**. ⌘↵ saves and Esc cancels. Click a highlight to
73
- edit or delete it. **Notes** (bottom right) lists every note in document order and has
74
- **+ General note** for comments about the whole document. Every change saves immediately.
73
+ edit or delete it. **Notes** (bottom right) lists every note in document order, has **Copy path** and
74
+ **Copy JSON** for the notes file, and has **+ General note** for comments about the whole document.
75
+ Every change saves immediately.
75
76
 
76
77
  MathJax and mermaid load from jsDelivr, so math and diagrams need internet access. Everything
77
78
  else works offline.
@@ -123,7 +124,7 @@ margin-notes [PATH] [--host HOST] [-p PORT] [--no-open] [--version]
123
124
  | Option | Default | |
124
125
  |---|---|---|
125
126
  | `PATH` | `.` | A folder to browse, or a document to open |
126
- | `--host` | `127.0.0.1` | `0.0.0.0` makes it reachable from your network |
127
+ | `--host` | `127.0.0.1` | `0.0.0.0` makes it reachable from your network, and prints the machine's [Tailscale](https://tailscale.com) URLs if it's on a tailnet |
127
128
  | `-p`, `--port` | `8765` | The first port to try; it moves up if that one is busy |
128
129
  | `--no-open` | | Don't open a browser |
129
130
 
@@ -32,8 +32,9 @@ uvx margin-notes ~/reports --host 0.0.0.0 --port 9000
32
32
  - **Diagrams** in ```` ```mermaid ```` fences.
33
33
  - Add `?raw=1` to any document URL to get the source.
34
34
  - **Reviewing:** select text and click **💬 Comment**. ⌘↵ saves and Esc cancels. Click a highlight to
35
- edit or delete it. **Notes** (bottom right) lists every note in document order and has
36
- **+ General note** for comments about the whole document. Every change saves immediately.
35
+ edit or delete it. **Notes** (bottom right) lists every note in document order, has **Copy path** and
36
+ **Copy JSON** for the notes file, and has **+ General note** for comments about the whole document.
37
+ Every change saves immediately.
37
38
 
38
39
  MathJax and mermaid load from jsDelivr, so math and diagrams need internet access. Everything
39
40
  else works offline.
@@ -85,7 +86,7 @@ margin-notes [PATH] [--host HOST] [-p PORT] [--no-open] [--version]
85
86
  | Option | Default | |
86
87
  |---|---|---|
87
88
  | `PATH` | `.` | A folder to browse, or a document to open |
88
- | `--host` | `127.0.0.1` | `0.0.0.0` makes it reachable from your network |
89
+ | `--host` | `127.0.0.1` | `0.0.0.0` makes it reachable from your network, and prints the machine's [Tailscale](https://tailscale.com) URLs if it's on a tailnet |
89
90
  | `-p`, `--port` | `8765` | The first port to try; it moves up if that one is busy |
90
91
  | `--no-open` | | Don't open a browser |
91
92
 
@@ -1,3 +1,3 @@
1
1
  """Highlight and comment on HTML and Markdown documents; notes save beside each one as JSON."""
2
2
 
3
- __version__ = "0.1.0"
3
+ __version__ = "0.1.1"
@@ -5,7 +5,10 @@ from __future__ import annotations
5
5
  import argparse
6
6
  import contextlib
7
7
  import ipaddress
8
+ import json
9
+ import shutil
8
10
  import socket
11
+ import subprocess
9
12
  import sys
10
13
  import threading
11
14
  import webbrowser
@@ -38,6 +41,42 @@ def lan_address() -> str | None:
38
41
  return None
39
42
 
40
43
 
44
+ # The Mac App Store build of Tailscale keeps its CLI inside the app bundle, off PATH.
45
+ TAILSCALE_APP = Path("/Applications/Tailscale.app/Contents/MacOS/Tailscale")
46
+
47
+
48
+ def tailscale_status(timeout: float = 2.0) -> dict | None:
49
+ """`tailscale status --json` from the Tailscale CLI, or None if it's absent, stopped or slow."""
50
+ exe = shutil.which("tailscale") or (str(TAILSCALE_APP) if TAILSCALE_APP.is_file() else None)
51
+ if not exe:
52
+ return None
53
+ try:
54
+ out = subprocess.run(
55
+ [exe, "status", "--json"], capture_output=True, text=True, timeout=timeout, check=False
56
+ ).stdout
57
+ status = json.loads(out)
58
+ except (OSError, subprocess.SubprocessError, ValueError):
59
+ return None
60
+ if not isinstance(status, dict) or status.get("BackendState") != "Running":
61
+ return None
62
+ return status
63
+
64
+
65
+ def tailscale_names(status: dict | None) -> list[str]:
66
+ """This machine's names on the tailnet: the MagicDNS short and full names, else its IPv4 address."""
67
+ me = (status or {}).get("Self") or {}
68
+ full = str(me.get("DNSName") or "").rstrip(".")
69
+ magic_dns = ((status or {}).get("CurrentTailnet") or {}).get("MagicDNSEnabled")
70
+ names = [full.split(".")[0], full] if full and magic_dns else [full] if full else []
71
+ if not names:
72
+ names = [ip for ip in me.get("TailscaleIPs") or [] if ":" not in ip][:1]
73
+ return list(dict.fromkeys(names))
74
+
75
+
76
+ def tailscale_ips(status: dict | None) -> set[str]:
77
+ return set(((status or {}).get("Self") or {}).get("TailscaleIPs") or [])
78
+
79
+
41
80
  def is_loopback(host: str) -> bool:
42
81
  if host == "localhost":
43
82
  return True
@@ -85,10 +124,18 @@ def main(argv: list[str] | None = None) -> None:
85
124
  print(f"margin-notes {__version__}")
86
125
  print(f" serving {root}")
87
126
  print(f" open {url}")
88
- if args.host in ("0.0.0.0", "::"):
127
+ every_interface = args.host in ("0.0.0.0", "::")
128
+ if every_interface:
89
129
  lan = lan_address()
90
130
  if lan:
91
131
  print(f" network http://{lan}:{port}{start_path}")
132
+ ts = tailscale_status()
133
+ ts_names = tailscale_names(ts)
134
+ if every_interface or args.host in tailscale_ips(ts) or args.host in ts_names:
135
+ for name in ts_names:
136
+ print(f" tailnet http://{name}:{port}{start_path}")
137
+ elif ts_names:
138
+ print(f" tailnet {', '.join(ts_names)} (add --host 0.0.0.0 to serve there)")
92
139
  if not is_loopback(args.host):
93
140
  print(
94
141
  " warning anyone who can reach this address can read every file under the folder "
@@ -47,6 +47,18 @@ def _order(note: dict[str, Any]) -> tuple:
47
47
  return (0, 0, str(note.get("created_at", "")))
48
48
 
49
49
 
50
+ def notes_document(doc: Path, notes: list[dict[str, Any]]) -> dict[str, Any]:
51
+ """The object a notes file holds."""
52
+ return {
53
+ "about": ABOUT.format(doc=doc.name),
54
+ "document": doc.name,
55
+ "document_path": str(doc),
56
+ "document_sha256": hashlib.sha256(doc.read_bytes()).hexdigest(),
57
+ "updated_at": now(),
58
+ "notes": notes,
59
+ }
60
+
61
+
50
62
  def validate(note: Any) -> dict[str, Any]:
51
63
  if not isinstance(note, dict) or not isinstance(note.get("id"), str) or not NOTE_ID.match(note["id"]):
52
64
  raise ValueError("a note is an object with an `id` of letters, digits, _ or -")
@@ -60,11 +72,14 @@ class NoteStore:
60
72
  self._lock = threading.Lock()
61
73
 
62
74
  def read(self, doc: Path) -> list[dict[str, Any]]:
75
+ return list(self.read_file(doc).get("notes", []))
76
+
77
+ def read_file(self, doc: Path) -> dict[str, Any]:
78
+ """The notes file's contents, or what it would hold with no notes yet."""
63
79
  path = notes_path(doc)
64
80
  if not path.exists():
65
- return []
66
- data = json.loads(path.read_text(encoding="utf-8"))
67
- return list(data.get("notes", []))
81
+ return notes_document(doc, [])
82
+ return json.loads(path.read_text(encoding="utf-8"))
68
83
 
69
84
  def count(self, doc: Path) -> int:
70
85
  try:
@@ -91,14 +106,7 @@ class NoteStore:
91
106
  if not notes and path.exists():
92
107
  path.unlink()
93
108
  return notes
94
- data = {
95
- "about": ABOUT.format(doc=doc.name),
96
- "document": doc.name,
97
- "document_path": str(doc),
98
- "document_sha256": hashlib.sha256(doc.read_bytes()).hexdigest(),
99
- "updated_at": now(),
100
- "notes": notes,
101
- }
109
+ data = notes_document(doc, notes)
102
110
  fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=".notes-", suffix=".tmp")
103
111
  try:
104
112
  with os.fdopen(fd, "w", encoding="utf-8") as f:
@@ -53,7 +53,16 @@ def create_app(root: Path) -> FastAPI:
53
53
  return target
54
54
 
55
55
  def notes_payload(doc: Path, notes: list) -> dict:
56
- return {"notes": notes, "notes_file": notes_path(doc).name}
56
+ try:
57
+ content = store.read_file(doc)
58
+ except ValueError:
59
+ content = None
60
+ return {
61
+ "notes": notes,
62
+ "notes_file": notes_path(doc).name,
63
+ "notes_path": str(notes_path(doc)),
64
+ "notes_json": content,
65
+ }
57
66
 
58
67
  @app.get("/__review/static/{name}")
59
68
  def static(name: str) -> Response:
@@ -63,6 +63,10 @@
63
63
  .meta { padding: 8px 14px; color: var(--muted); font-size: 12px; border-bottom: 1px solid var(--line); display: flex; gap: 8px; }
64
64
  .meta .status { flex: 1; }
65
65
  .meta .err { color: var(--danger); }
66
+ .copy { padding: 8px 14px; border-bottom: 1px solid var(--line); display: flex; gap: 6px; align-items: center; }
67
+ .copy code { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; direction: rtl;
68
+ text-align: left; color: var(--muted); font-size: 11px; }
69
+ .copy button { font-size: 12px; padding: 3px 8px; white-space: nowrap; }
66
70
  ol { list-style: none; margin: 0; padding: 6px; overflow: auto; flex: 1; }
67
71
  li { padding: 8px 10px; border-radius: 8px; cursor: pointer; border: 1px solid transparent; }
68
72
  li:hover { border-color: var(--line); }
@@ -89,6 +93,7 @@
89
93
  <aside id="panel" hidden>
90
94
  <header><b>Review notes</b><button class="general">+ General note</button><button class="close" title="Close">✕</button></header>
91
95
  <div class="meta"><span class="status"></span><a class="folder" href="./">Folder</a></div>
96
+ <div class="copy"><code class="path"></code><button class="copy-path" title="Copy the notes file's full path">Copy path</button><button class="copy-json" title="Copy the notes file's JSON">Copy JSON</button></div>
92
97
  <ol></ol>
93
98
  </aside>`;
94
99
 
@@ -267,6 +272,7 @@
267
272
  if (!r.ok) throw new Error(`HTTP ${r.status}`);
268
273
  const data = await r.json();
269
274
  setStatus(`Saved to ${data.notes_file} at ${new Date().toLocaleTimeString()}`);
275
+ setFile(data);
270
276
  // Pick up notes other reviewers added, unless we're mid-edit.
271
277
  if (!editing && Array.isArray(data.notes)) { notes = data.notes; sortNotes(); render(); }
272
278
  })
@@ -403,6 +409,37 @@
403
409
  });
404
410
 
405
411
  // ---------- panel ----------
412
+ // The server sends the file's path and contents with every response, so copying is synchronous:
413
+ // Safari refuses clipboard writes that happen after an await.
414
+ let filePath = "", fileJson = null;
415
+ function setFile(data) {
416
+ if (typeof data.notes_path === "string") { filePath = data.notes_path; $(".copy .path").textContent = "\u200e" + filePath; $(".copy .path").title = filePath; }
417
+ if ("notes_json" in data) fileJson = data.notes_json;
418
+ }
419
+ function copyText(text) {
420
+ if (navigator.clipboard && window.isSecureContext) return navigator.clipboard.writeText(text);
421
+ // Plain http on a LAN address (--host 0.0.0.0) has no clipboard API; fall back to execCommand.
422
+ const t = document.createElement("textarea");
423
+ t.value = text;
424
+ t.style.cssText = "position:fixed;top:0;left:0;opacity:0";
425
+ root.appendChild(t);
426
+ t.select();
427
+ const ok = document.execCommand("copy");
428
+ t.remove();
429
+ return ok ? Promise.resolve() : Promise.reject(new Error("copy blocked"));
430
+ }
431
+ function copyButton(sel, label, get) {
432
+ const b = $(sel);
433
+ b.addEventListener("click", () => {
434
+ const text = get();
435
+ if (text == null) { setStatus("Nothing to copy yet", true); return; }
436
+ copyText(text).then(
437
+ () => { b.textContent = "Copied ✓"; setTimeout(() => { b.textContent = label; }, 1200); },
438
+ (e) => setStatus(`Copy failed (${e.message})`, true));
439
+ });
440
+ }
441
+ copyButton(".copy-path", "Copy path", () => filePath || null);
442
+ copyButton(".copy-json", "Copy JSON", () => (fileJson ? JSON.stringify(fileJson, null, 2) : null));
406
443
  $("#toggle").addEventListener("click", () => { panel.hidden = !panel.hidden; });
407
444
  $("#panel .close").addEventListener("click", () => { panel.hidden = true; });
408
445
  $("#panel .general").addEventListener("click", () => {
@@ -424,6 +461,7 @@
424
461
  if (!r.ok) throw new Error(data.detail || `HTTP ${r.status}`);
425
462
  notes = Array.isArray(data.notes) ? data.notes : [];
426
463
  notesFile = data.notes_file;
464
+ setFile(data);
427
465
  setStatus(notes.length ? `Loaded ${notes.length} note(s) from ${notesFile}` : `Notes save to ${notesFile}`);
428
466
  } catch (e) {
429
467
  setStatus(`Couldn't load notes (${e.message})`, true);
@@ -199,6 +199,35 @@ def test_general_note(site, page):
199
199
  assert n["comment"] == "Overall: needs a summary up top."
200
200
 
201
201
 
202
+ @pytest.mark.parametrize("secure", [True, False], ids=["clipboard-api", "execcommand-fallback"])
203
+ def test_copy_path_and_json(site, browser, secure):
204
+ url, root = site
205
+ ctx = browser.new_context(permissions=["clipboard-read", "clipboard-write"])
206
+ page = ctx.new_page()
207
+ if not secure: # what plain http on a LAN address looks like
208
+ page.add_init_script("Object.defineProperty(window, 'isSecureContext', { get: () => false })")
209
+ try:
210
+ open_doc(page, url + "article.html")
211
+ page.evaluate(SELECT, ["p3", "held-out", 0])
212
+ ui(page, "#add").click()
213
+ ui(page, "textarea").fill("source?")
214
+ ui(page, ".save").click()
215
+ page.wait_for_timeout(300)
216
+ ui(page, "#toggle").click()
217
+ clip = "() => navigator.clipboard.readText()"
218
+
219
+ ui(page, ".copy-path").click()
220
+ page.wait_for_timeout(100)
221
+ assert page.evaluate(clip) == str(root / "article.html.notes.json")
222
+ assert ui(page, ".copy-path").text_content() == "Copied ✓"
223
+
224
+ ui(page, ".copy-json").click()
225
+ page.wait_for_timeout(100)
226
+ assert json.loads(page.evaluate(clip)) == json.loads((root / "article.html.notes.json").read_text("utf-8"))
227
+ finally:
228
+ ctx.close()
229
+
230
+
202
231
  def test_typing_does_not_trigger_page_shortcuts(site, page):
203
232
  url, _ = site
204
233
  open_doc(page, url + "article.html")
@@ -1,5 +1,6 @@
1
1
  from __future__ import annotations
2
2
 
3
+ import json
3
4
  import socket
4
5
  import subprocess
5
6
  import sys
@@ -20,6 +21,7 @@ def run(monkeypatch):
20
21
  calls.update(app=app, host=host, port=port)
21
22
 
22
23
  monkeypatch.setattr(uvicorn, "run", fake_run)
24
+ monkeypatch.setattr(cli, "tailscale_status", lambda: None) # tests never see this machine's tailnet
23
25
  monkeypatch.setattr(cli.webbrowser, "open", opened.append)
24
26
 
25
27
  class Timer: # run the browser-open callback immediately
@@ -109,3 +111,71 @@ def test_module_entry_point():
109
111
  cmd = [sys.executable, "-m", "margin_notes", "--version"]
110
112
  out = subprocess.run(cmd, capture_output=True, text=True, check=True)
111
113
  assert out.stdout.strip() == f"margin-notes {__version__}"
114
+
115
+
116
+ TS_STATUS = {
117
+ "BackendState": "Running",
118
+ "Self": {"DNSName": "box.example.ts.net.", "TailscaleIPs": ["100.64.0.7", "fd7a:115c:a1e0::7"]},
119
+ "CurrentTailnet": {"MagicDNSEnabled": True},
120
+ }
121
+
122
+
123
+ class TestTailscale:
124
+ def test_names_with_magic_dns(self):
125
+ assert cli.tailscale_names(TS_STATUS) == ["box", "box.example.ts.net"]
126
+
127
+ def test_names_without_magic_dns(self):
128
+ status = {**TS_STATUS, "CurrentTailnet": {"MagicDNSEnabled": False}}
129
+ assert cli.tailscale_names(status) == ["box.example.ts.net"]
130
+
131
+ def test_names_fall_back_to_ipv4(self):
132
+ status = {"BackendState": "Running", "Self": {"TailscaleIPs": ["fd7a::1", "100.64.0.7"]}}
133
+ assert cli.tailscale_names(status) == ["100.64.0.7"]
134
+
135
+ def test_no_tailscale(self):
136
+ assert cli.tailscale_names(None) == []
137
+
138
+ def test_status_without_the_cli(self, monkeypatch, tmp_path):
139
+ monkeypatch.setattr(cli.shutil, "which", lambda _: None)
140
+ monkeypatch.setattr(cli, "TAILSCALE_APP", tmp_path / "missing")
141
+ assert cli.tailscale_status() is None
142
+
143
+ @pytest.mark.parametrize(
144
+ "stdout, expected",
145
+ [
146
+ (json.dumps(TS_STATUS), TS_STATUS),
147
+ (json.dumps({**TS_STATUS, "BackendState": "Stopped"}), None),
148
+ ("not json", None),
149
+ ("", None),
150
+ ],
151
+ )
152
+ def test_status_parsing(self, monkeypatch, stdout, expected):
153
+ monkeypatch.setattr(cli.shutil, "which", lambda _: "/usr/bin/tailscale")
154
+ monkeypatch.setattr(cli.subprocess, "run", lambda *a, **kw: subprocess.CompletedProcess(a, 0, stdout=stdout))
155
+ assert cli.tailscale_status() == expected
156
+
157
+ def test_status_times_out_quietly(self, monkeypatch):
158
+ def hang(*a, **kw):
159
+ raise subprocess.TimeoutExpired("tailscale", 2)
160
+
161
+ monkeypatch.setattr(cli.shutil, "which", lambda _: "/usr/bin/tailscale")
162
+ monkeypatch.setattr(cli.subprocess, "run", hang)
163
+ assert cli.tailscale_status() is None
164
+
165
+ def test_urls_when_serving_every_interface(self, run, tree, monkeypatch, capsys):
166
+ monkeypatch.setattr(cli, "tailscale_status", lambda: TS_STATUS)
167
+ calls, _ = run(str(tree), "--host", "0.0.0.0", "--no-open", "--port", "0")
168
+ out = capsys.readouterr().out
169
+ assert f"tailnet http://box:{calls['port']}/" in out
170
+ assert f"tailnet http://box.example.ts.net:{calls['port']}/" in out
171
+
172
+ def test_hint_when_serving_localhost(self, run, tree, monkeypatch, capsys):
173
+ monkeypatch.setattr(cli, "tailscale_status", lambda: TS_STATUS)
174
+ run(str(tree), "--no-open", "--port", "0")
175
+ out = capsys.readouterr().out
176
+ assert "tailnet box, box.example.ts.net (add --host 0.0.0.0 to serve there)" in out
177
+ assert "http://box" not in out
178
+
179
+ def test_silent_without_tailscale(self, run, tree, capsys):
180
+ run(str(tree), "--host", "0.0.0.0", "--no-open", "--port", "0")
181
+ assert "tailnet" not in capsys.readouterr().out
@@ -50,6 +50,15 @@ class TestStore:
50
50
  assert store.read(doc) == []
51
51
  assert store.count(doc) == 0
52
52
 
53
+ def test_read_file_matches_disk(self, store, doc):
54
+ store.upsert(doc, note("a"))
55
+ assert store.read_file(doc) == saved(doc)
56
+
57
+ def test_read_file_before_any_notes(self, store, doc):
58
+ data = store.read_file(doc)
59
+ assert data["notes"] == [] and data["document"] == "report.md"
60
+ assert not notes_path(doc).exists()
61
+
53
62
  def test_file_contents(self, store, doc):
54
63
  store.upsert(doc, note("a"))
55
64
  data = saved(doc)
@@ -154,7 +154,11 @@ class TestNotesApi:
154
154
  def test_roundtrip(self, client, tree):
155
155
  doc = {"doc": "/docs/guide.md"}
156
156
  r = client.get(API, params=doc)
157
- assert r.json() == {"notes": [], "notes_file": "guide.md.notes.json"}
157
+ body = r.json()
158
+ assert body["notes"] == []
159
+ assert body["notes_file"] == "guide.md.notes.json"
160
+ assert body["notes_path"] == str(tree / "docs" / "guide.md.notes.json")
161
+ assert body["notes_json"]["notes"] == [] and body["notes_json"]["document"] == "guide.md"
158
162
 
159
163
  r = client.put(API, params=doc, json=note("a", comment="why?", _orphan=True))
160
164
  assert r.status_code == 200
@@ -167,6 +171,14 @@ class TestNotesApi:
167
171
  assert r.json()["notes"] == []
168
172
  assert not (tree / "docs" / "guide.md.notes.json").exists()
169
173
 
174
+ def test_responses_carry_the_file_for_copying(self, client, tree):
175
+ doc = {"doc": "/docs/guide.md"}
176
+ body = client.put(API, params=doc, json=note("a", comment="why?")).json()
177
+ path = tree / "docs" / "guide.md.notes.json"
178
+ assert body["notes_path"] == str(path)
179
+ assert body["notes_json"] == json.loads(path.read_text(encoding="utf-8"))
180
+ assert client.get(API, params=doc).json()["notes_json"] == body["notes_json"]
181
+
170
182
  def test_doc_param_is_percent_encoded_path(self, client, tree):
171
183
  (tree / "my doc.md").write_text("# x\n", encoding="utf-8", newline="\n")
172
184
  assert client.put(API, params={"doc": "/my%20doc.md"}, json=note("a")).status_code == 200
File without changes
File without changes