|
| 1 | +"""Control mode protocol parser.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +from typing import IO |
| 6 | + |
| 7 | +from .result import ControlModeResult |
| 8 | + |
| 9 | + |
| 10 | +class ProtocolParser: |
| 11 | + r"""Parser for tmux control mode protocol. |
| 12 | +
|
| 13 | + Handles %begin/%end/%error blocks and notifications. |
| 14 | +
|
| 15 | + The tmux control mode protocol format: |
| 16 | + - Commands produce output blocks |
| 17 | + - Blocks start with %begin and end with %end or %error |
| 18 | + - Format: %begin timestamp cmd_num flags |
| 19 | + - Notifications (%session-changed, etc.) can appear between blocks |
| 20 | +
|
| 21 | + Examples |
| 22 | + -------- |
| 23 | + >>> import io |
| 24 | + >>> stdout = io.StringIO( |
| 25 | + ... "%begin 1234 1 0\n" |
| 26 | + ... "session1\n" |
| 27 | + ... "%end 1234 1 0\n" |
| 28 | + ... ) |
| 29 | + >>> parser = ProtocolParser(stdout) |
| 30 | + >>> result = parser.parse_response(["list-sessions"]) |
| 31 | + >>> result.stdout |
| 32 | + ['session1'] |
| 33 | + >>> result.returncode |
| 34 | + 0 |
| 35 | + """ |
| 36 | + |
| 37 | + def __init__(self, stdout: IO[str]) -> None: |
| 38 | + self.stdout = stdout |
| 39 | + self.notifications: list[str] = [] |
| 40 | + |
| 41 | + def parse_response(self, cmd: list[str]) -> ControlModeResult: |
| 42 | + """Parse a single command response. |
| 43 | +
|
| 44 | + Parameters |
| 45 | + ---------- |
| 46 | + cmd : list[str] |
| 47 | + The command that was executed (for result.cmd) |
| 48 | +
|
| 49 | + Returns |
| 50 | + ------- |
| 51 | + ControlModeResult |
| 52 | + Parsed result with stdout, stderr, returncode |
| 53 | +
|
| 54 | + Raises |
| 55 | + ------ |
| 56 | + ConnectionError |
| 57 | + If connection closes unexpectedly |
| 58 | + ProtocolError |
| 59 | + If protocol format is unexpected |
| 60 | + """ |
| 61 | + stdout_lines: list[str] = [] |
| 62 | + stderr_lines: list[str] = [] |
| 63 | + returncode = 0 |
| 64 | + |
| 65 | + # State machine |
| 66 | + in_response = False |
| 67 | + |
| 68 | + while True: |
| 69 | + line = self.stdout.readline() |
| 70 | + if not line: # EOF |
| 71 | + msg = "Control mode connection closed unexpectedly" |
| 72 | + raise ConnectionError(msg) |
| 73 | + |
| 74 | + line = line.rstrip("\n") |
| 75 | + |
| 76 | + # Parse line type |
| 77 | + if line.startswith("%begin"): |
| 78 | + # %begin timestamp cmd_num flags |
| 79 | + in_response = True |
| 80 | + continue |
| 81 | + |
| 82 | + elif line.startswith("%end"): |
| 83 | + # Success - response complete |
| 84 | + return ControlModeResult(stdout_lines, stderr_lines, returncode, cmd) |
| 85 | + |
| 86 | + elif line.startswith("%error"): |
| 87 | + # Error - command failed |
| 88 | + returncode = 1 |
| 89 | + # Note: error details are in stdout_lines already |
| 90 | + return ControlModeResult(stdout_lines, stderr_lines, returncode, cmd) |
| 91 | + |
| 92 | + elif line.startswith("%"): |
| 93 | + # Notification - queue for future processing |
| 94 | + self.notifications.append(line) |
| 95 | + # Don't break - keep reading for our response |
| 96 | + continue |
| 97 | + |
| 98 | + else: |
| 99 | + # Regular output line |
| 100 | + if in_response: |
| 101 | + stdout_lines.append(line) |
| 102 | + # else: orphaned line before %begin (should not happen in practice) |
| 103 | + |
| 104 | + |
| 105 | +class ProtocolError(Exception): |
| 106 | + """Raised when control mode protocol is violated.""" |
| 107 | + |
| 108 | + pass |
0 commit comments