160 lines
5.0 KiB
Python
160 lines
5.0 KiB
Python
#!/usr/bin/env python3
|
|
"""Confirms joe_wrapper.py's os.execv into hd_joe_agent.py actually works
|
|
for an existing hd-managed note (Rule 1) -- not just decide()'s pure
|
|
logic. Opens a note by its bare symlink name from INSIDE the tag dir
|
|
(the common case), edits, and checks the server received it live.
|
|
"""
|
|
import json
|
|
import os
|
|
import shutil
|
|
import socket as socketmod
|
|
import sys
|
|
import tempfile
|
|
import threading
|
|
import time
|
|
from pathlib import Path
|
|
|
|
import pexpect
|
|
import socketio
|
|
from werkzeug.serving import make_server
|
|
|
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "hd_common"))
|
|
from hd_client import apply_operation
|
|
from hd_core import Config, Cookies, State, NoteState, content_hash
|
|
|
|
JOE_BIN = os.environ.get("JOE_BIN", "/home/claude/work/repo/joe-patch/build/joe-4.8/joe/joe")
|
|
WRAPPER = str(Path(__file__).resolve().parent / "joe_wrapper.py")
|
|
|
|
|
|
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, port, initial_text):
|
|
self.text = initial_text
|
|
self.revision = 0
|
|
self.lock = threading.Lock()
|
|
|
|
self.sio = socketio.Server(async_mode="threading", cors_allowed_origins="*")
|
|
|
|
@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:
|
|
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():
|
|
s = socketmod.socket(socketmod.AF_INET, socketmod.SOCK_STREAM)
|
|
s.bind(("127.0.0.1", 0))
|
|
port = s.getsockname()[1]
|
|
s.close()
|
|
return port
|
|
|
|
|
|
def main():
|
|
port = free_port()
|
|
note_id = "n1"
|
|
initial_content = "---\ntitle: Masten\ntags: sl6cv\n---\n\nstarting content"
|
|
server = FakeServer(port, initial_content)
|
|
server.start()
|
|
time.sleep(0.2)
|
|
|
|
tmpdir = Path(tempfile.mkdtemp(prefix="joe-wrapper-hdjoe-exec-test-"))
|
|
root = tmpdir / "notes"
|
|
hd_dir = root / ".hd"
|
|
(hd_dir / "notes").mkdir(parents=True)
|
|
Config(url=f"http://127.0.0.1:{port}", email=None).save(hd_dir)
|
|
Cookies(header="session=1").save(hd_dir)
|
|
|
|
state = State()
|
|
(hd_dir / "notes" / f"{note_id}.md").write_text(initial_content)
|
|
state.notes[note_id] = NoteState(
|
|
title="Masten", tags=["sl6cv"], symlinks={"sl6cv": "Masten"},
|
|
content_hash=content_hash(initial_content), last_seen_time=1,
|
|
)
|
|
state.save(hd_dir)
|
|
tag_dir = root / "sl6cv"
|
|
tag_dir.mkdir(parents=True)
|
|
(tag_dir / "Masten").symlink_to(Path("..") / ".hd" / "notes" / f"{note_id}.md")
|
|
|
|
ok = True
|
|
child = None
|
|
try:
|
|
log_path = "/tmp/joe-wrapper-hdjoe-exec.log"
|
|
try:
|
|
os.remove(log_path)
|
|
except OSError:
|
|
pass
|
|
|
|
# Invoke exactly like real joe would be invoked -- through the
|
|
# wrapper, with just the bare symlink NAME (not a resolved path),
|
|
# from inside the tag directory. This is Rule 1's "existing note"
|
|
# case reached via a relative name, the way someone actually types
|
|
# `joe Masten` day to day, not `joe /full/path/to/Masten`.
|
|
cmd = f"python3 {WRAPPER} Masten"
|
|
child = pexpect.spawn(cmd, cwd=str(tag_dir), env={**os.environ, "TERM": "xterm"},
|
|
dimensions=(24, 80), timeout=10)
|
|
time.sleep(1.0)
|
|
|
|
child.send("\x0bv") # Ctrl-K V: EOF
|
|
time.sleep(0.3)
|
|
child.send(" -- via joe wrapper")
|
|
time.sleep(0.6)
|
|
|
|
child.send("\x0bx")
|
|
time.sleep(0.4)
|
|
child.send("\r")
|
|
try:
|
|
child.wait()
|
|
except pexpect.TIMEOUT:
|
|
pass
|
|
if child.isalive():
|
|
child.terminate(force=True)
|
|
time.sleep(0.3)
|
|
|
|
print("server text:", repr(server.text[-50:]))
|
|
ok &= "via joe wrapper" in server.text
|
|
ok &= server.revision > 0
|
|
|
|
finally:
|
|
if child and child.isalive():
|
|
child.terminate(force=True)
|
|
server.stop()
|
|
shutil.rmtree(tmpdir, ignore_errors=True)
|
|
|
|
print("\nPASS" if ok else "\nFAIL")
|
|
return 0 if ok else 1
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|