diff --git a/src/sshctl/operations/jump.py b/src/sshctl/operations/jump.py index 49868fe..aa5c8d5 100644 --- a/src/sshctl/operations/jump.py +++ b/src/sshctl/operations/jump.py @@ -5,7 +5,7 @@ import re import socket import subprocess from pathlib import Path -from typing import Any, TypedDict +from typing import Any, NotRequired, TypedDict _PROXYJUMP_RE = re.compile(r"^\s+ProxyJump\s+", re.I) _SAVE_FILE = ".proxyjump_save" @@ -26,6 +26,10 @@ class JumpRecord(TypedDict): file: str line: int text: str + # Where the line belongs: its Host block (the full Host argument string) and + # its offset below the Host line. Absent in save files from older versions. + host: NotRequired[str] + offset: NotRequired[int] class JumpNoopResult(TypedDict): @@ -241,15 +245,18 @@ def save_state(ssh_dir: Path) -> list[JumpRecord]: records: list[JumpRecord] = [] for f in _find_conf_files(ssh_dir): lines = f.read_text().splitlines(keepends=False) + host, host_idx = "", -1 for i, line in enumerate(lines): + m = _BLOCK_RE.match(line) + if m: + host, host_idx = m.group(2).strip(), i + continue if _PROXYJUMP_RE.match(line): - records.append( - JumpRecord( - file=str(f.relative_to(ssh_dir)), - line=i, - text=line, - ) - ) + rec = JumpRecord(file=str(f.relative_to(ssh_dir)), line=i, text=line) + if host_idx >= 0: + rec["host"] = host + rec["offset"] = i - host_idx + records.append(rec) (ssh_dir / _SAVE_FILE).write_text(json.dumps(records, indent=2)) return records @@ -302,17 +309,10 @@ def on(ssh_dir: Path) -> dict[str, Any]: fpath = ssh_dir / fname if not fpath.exists(): continue - file_records.sort(key=lambda r: int(r.get("line", 0)), reverse=True) lines = fpath.read_text().splitlines(keepends=False) if any(_PROXYJUMP_RE.match(ln) for ln in lines): continue - for rec in file_records: - lineno = int(rec.get("line", 0)) - text = str(rec.get("text", "")) - if lineno < len(lines): - lines.insert(lineno, text) - else: - lines.append(text) + _restore_lines(lines, file_records) fpath.write_text("\n".join(lines) + "\n") modified.add(fname) @@ -321,6 +321,44 @@ def on(ssh_dir: Path) -> dict[str, Any]: return {"status": "ok", "count": len(records), "files": sorted(modified)} +_BLOCK_RE = re.compile(r"^\s*(Host|Match)\s+(.+?)\s*$", re.I) + + +def _restore_lines(lines: list[str], records: list[JumpRecord]) -> None: + """Re-insert removed lines, in place. + + Anchored records go back under their own Host line at their old offset, + clamped to that block, so edits made between `off` and `on` cannot move a + ProxyJump into another host. Legacy records (absolute line numbers only) are + inserted in ascending order: each saved number is a position in the + original file, which is only reproduced by filling the gaps front to back. + """ + legacy = sorted((r for r in records if "host" not in r), key=lambda r: int(r["line"])) + for rec in legacy: + lines.insert(min(int(rec["line"]), len(lines)), str(rec["text"])) + + anchored = sorted( + (r for r in records if "host" in r), key=lambda r: (r["host"], int(r["offset"])) + ) + for rec in anchored: + start = next( + ( + i + for i, ln in enumerate(lines) + if (m := _BLOCK_RE.match(ln)) and m.group(2).strip() == rec["host"] + ), + None, + ) + if start is None: + continue # the host was deleted while jumps were off + end = next( + (i for i in range(start + 1, len(lines)) if _BLOCK_RE.match(lines[i])), len(lines) + ) + while end > start + 1 and not lines[end - 1].strip(): + end -= 1 # stay above the blank lines that separate blocks + lines.insert(min(start + int(rec["offset"]), end), str(rec["text"])) + + def status(ssh_dir: Path) -> JumpStatusResult: hosts = list_hosts(ssh_dir) saved = load_state(ssh_dir) diff --git a/tests/test_jump.py b/tests/test_jump.py index e110c1e..e29fb81 100644 --- a/tests/test_jump.py +++ b/tests/test_jump.py @@ -269,3 +269,33 @@ def test_jump_gateways_collects_unique(ssh_dir: Path) -> None: _mk_conf(ssh_dir, "10-servers.conf", "Host a\n ProxyJump gw\n") _mk_conf(ssh_dir, "20-servers.conf", "Host b\n ProxyJump gw:2222\n ProxyJump other\n") assert _jump_gateways(ssh_dir) == {"gw", "other"} + + +# Regression: `on` used to re-insert saved lines in descending line order into +# the file `off` had already shortened, so with more than one ProxyJump every +# line after the first landed in the wrong Host block. This scrambled real +# configs (97 of 295 hosts routed through the wrong gateway, or none). +_MULTI = ( + "Host gw\n HostName 1.2.3.4\n\n" + "Host a\n HostName 10.0.0.1\n ProxyJump gw\n\n" + "Host b\n HostName 10.0.0.2\n\n" + "Host c\n HostName 10.0.0.3\n ProxyJump gw\n\n" + "Host d\n ProxyJump gw\n HostName 10.0.0.4\n" +) + + +def test_off_on_roundtrip_is_byte_identical(ssh_dir: Path) -> None: + f = _mk_conf(ssh_dir, "10-servers.conf", _MULTI) + off(ssh_dir) + assert "ProxyJump" not in f.read_text() + on(ssh_dir) + assert f.read_text() == _MULTI + + +def test_on_survives_edits_between_off_and_on(ssh_dir: Path) -> None: + f = _mk_conf(ssh_dir, "10-servers.conf", _MULTI) + off(ssh_dir) + # A host added above the others shifts every line number. + f.write_text("Host new\n HostName 10.0.0.9\n\n" + f.read_text()) + on(ssh_dir) + assert f.read_text() == "Host new\n HostName 10.0.0.9\n\n" + _MULTI