Debian Codegraph @

src/libtmux/neo.py

raw symbols SCIP
1 """Tools for reading tmux data into Python objects."""
2
3 from __future__ import annotations
4
5 import dataclasses
6 import functools
7 import logging
8 import shlex
9 import typing as t
10 from collections.abc import Iterable
11
12 from libtmux import exc
13 from libtmux._compat import LooseVersion
14 from libtmux.common import get_version, raise_if_stderr, tmux_cmd
15 from libtmux.formats import FORMAT_SEPARATOR
16
17 if t.TYPE_CHECKING:
18 ListCmd = t.Literal["list-sessions", "list-windows", "list-panes", "list-clients"]
19 ListExtraArgs = Iterable[str] | None
20
21 from libtmux.server import Server
22
23 logger = logging.getLogger(__name__)
24
25
26 OutputRaw = dict[str, t.Any]
27 OutputsRaw = list[OutputRaw]
28
29
30 SCOPES_BY_LIST_CMD: dict[str, frozenset[str]] = {
31 "list-sessions": frozenset({"universal", "session", "window", "pane"}),
32 "list-windows": frozenset({"universal", "session", "window", "pane"}),
33 "list-panes": frozenset({"universal", "session", "window", "pane"}),
34 "list-clients": frozenset({"universal", "session", "window", "pane", "client"}),
35 }
36 """Format-token scopes a given tmux ``list-*`` subcommand can resolve.
37
38 A token whose scope is in the set is safe to include in that subcommand's
39 ``-F`` template. A token whose scope is *outside* the set may be unavailable
40 for that command, so libtmux leaves it out.
41
42 The relationship is asymmetric: when tmux lists a parent object, it can also
43 report fields for that parent's active child. A session row can include its
44 current window and active pane fields, and a client row can include the
45 attached session, current window, and active pane. ``client`` scope is the
46 exception in the other direction: it appears only in ``list-clients`` because
47 session/window/pane listings do not have a client attachment to report.
48 """
49
50
51 FIELD_VERSION: dict[str, str] = {
52 # Post-3.2a additions (verified against tmux's format.c at each gated
53 # release tag, e.g. https://github.com/tmux/tmux/blob/3.6a/format.c).
54 "pane_dead_signal": "3.3",
55 "pane_dead_time": "3.3",
56 # tmux 3.7 additions (verified against format.c / tmux.1 at the 3.7 tag).
57 "bracket_paste_flag": "3.7",
58 "pane_flags": "3.7",
59 "pane_floating_flag": "3.7",
60 "pane_pb_progress": "3.7",
61 "pane_pb_state": "3.7",
62 "pane_pipe_pid": "3.7",
63 "pane_x": "3.7",
64 "pane_y": "3.7",
65 "pane_z": "3.7",
66 "pane_zoomed_flag": "3.7",
67 "synchronized_output_flag": "3.7",
68 }
69 """Minimum tmux version that registers each format token.
70
71 Field names absent from this dict default to ``"3.2a"`` (always-safe within
72 the supported tmux range). Entries here represent tokens added after 3.2a
73 that need explicit gating to keep the ``-F`` template compatible with older
74 tmux versions.
75 """
76
77
78 # Field-name prefixes that map to a single format-token scope. Resolved by
79 # :func:`_token_scope`. Order matters: longer prefixes win (e.g.
80 # ``copy_cursor_`` is a runtime token, not a generic ``copy_`` one).
81 _SCOPE_PREFIXES: tuple[tuple[str, str], ...] = (
82 ("copy_cursor_", "event"),
83 ("pane_", "pane"),
84 ("window_", "window"),
85 ("session_", "session"),
86 ("client_", "client"),
87 ("buffer_", "buffer"),
88 ("mouse_", "event"),
89 ("cursor_", "event"),
90 ("selection_", "event"),
91 ("scroll_", "event"),
92 ("popup_", "event"),
93 )
94
95 # Per-token scope overrides for fields whose name doesn't follow the prefix
96 # convention. Verified against the corresponding ``format_cb_*`` in tmux's
97 # ``format.c`` (which context the callback dereferences — wp, wl, s, or c).
98 # Entries are added by the scope-gate fix commits as misclassifications are
99 # discovered.
100 _SCOPE_OVERRIDES: dict[str, str] = {
101 "cursor_x": "pane", # ft->wp->base.cx
102 "cursor_y": "pane", # ft->wp->base.cy
103 "cursor_flag": "pane", # ft->wp->base.mode
104 "cursor_character": "pane", # ft->wp
105 "mouse_all_flag": "pane", # ft->wp->base.mode MODE_MOUSE_ALL
106 "mouse_any_flag": "pane", # ft->wp->base.mode ALL_MOUSE_MODES
107 "mouse_button_flag": "pane", # ft->wp->base.mode MODE_MOUSE_BUTTON
108 "mouse_sgr_flag": "pane", # ft->wp->base.mode MODE_MOUSE_SGR
109 "mouse_standard_flag": "pane", # ft->wp->base.mode MODE_MOUSE_STANDARD
110 "scroll_region_lower": "pane", # ft->wp->base.rlower
111 "scroll_region_upper": "pane", # ft->wp->base.rupper
112 "alternate_saved_x": "pane", # ft->wp->base.saved_cx
113 "alternate_saved_y": "pane", # ft->wp->base.saved_cy
114 "history_bytes": "pane", # ft->wp
115 "history_limit": "pane", # ft->wp->base.grid->hlimit
116 "history_size": "pane", # ft->wp->base.grid->hsize
117 "insert_flag": "pane", # ft->wp->base.mode MODE_INSERT
118 "keypad_cursor_flag": "pane", # ft->wp->base.mode MODE_KCURSOR
119 "keypad_flag": "pane", # ft->wp->base.mode MODE_KKEYPAD
120 "origin_flag": "pane", # ft->wp->base.mode MODE_ORIGIN
121 "wrap_flag": "pane", # ft->wp->base.mode MODE_WRAP
122 "active_window_index": "session", # ft->s->curw->idx
123 "last_window_index": "session", # ft->s
124 # tmux 3.7 pane-scope tokens that don't carry the pane_ prefix.
125 "bracket_paste_flag": "pane", # ft->wp->screen->mode MODE_BRACKETPASTE
126 "synchronized_output_flag": "pane", # ft->wp->base.mode MODE_SYNC
127 }
128
129
130 # Standalone tokens registered in tmux's ``format.c`` static table (the
131 # default tree of ``format_cb_*`` callbacks). They resolve in every
132 # ``list-*`` subcommand because their callbacks read process- or server-
133 # global state rather than dereferencing ``ft->c``, ``ft->s``, ``ft->wl``,
134 # or ``ft->wp``. Pane- and session-scoped standalones are routed via
135 # :data:`_SCOPE_OVERRIDES`; context-only tokens (registered outside
136 # ``format.c`` for a specific subcommand or mode) are routed via
137 # :data:`_CONTEXT_ONLY_TOKENS`.
138 _UNIVERSAL_TOKENS: frozenset[str] = frozenset(
139 {
140 "config_files",
141 "host",
142 "host_short",
143 "line",
144 "next_session_id",
145 "pid",
146 "socket_path",
147 "start_time",
148 "uid",
149 "user",
150 "version",
151 }
152 )
153
154 # Tokens declared on :class:`Obj` whose callbacks are registered *outside*
155 # ``format.c``'s static table — i.e. they only resolve in a specific
156 # command context, not via ``format_defaults`` for any ``list-*``
157 # subcommand:
158 #
159 # - ``command_list_alias`` / ``command_list_name`` / ``command_list_usage``
160 # → ``cmd-list-commands.c`` (the ``list-commands`` subcommand only).
161 # - ``search_match`` → ``window-copy.c`` (copy-mode pane formats only).
162 # - ``current_file`` → ``cfg.c`` (config parse context only).
163 #
164 # Emitting these in a ``list-sessions/windows/panes/clients/buffers`` ``-F``
165 # template is harmless (tmux renders unknown tokens to empty), but it
166 # misleads readers of the ``-F`` string about what the format engine will
167 # resolve in that scope. Routed to the ``"context"`` scope, which is
168 # explicitly excluded from every :data:`SCOPES_BY_LIST_CMD` entry.
169 _CONTEXT_ONLY_TOKENS: frozenset[str] = frozenset(
170 {
171 "command_list_alias",
172 "command_list_name",
173 "command_list_usage",
174 "current_file",
175 "search_match",
176 }
177 )
178
179
180 def _token_scope(field_name: str) -> str:
181 """Resolve a format token's scope from its name.
182
183 Returns ``"universal"`` for cross-scope tokens (e.g. ``version``,
184 ``socket_path``, ``host``). Returns ``"event"`` for runtime-only tokens
185 that never appear in a ``list-*`` output (mouse, cursor, selection,
186 popup). Returns ``"context"`` for tokens registered outside
187 ``format.c``'s static table (only resolve in a specific command or
188 mode context). Returns ``"pane"`` / ``"window"`` / ``"session"`` /
189 ``"client"`` / ``"buffer"`` for scope-prefixed tokens.
190
191 Fields that don't match any prefix, override, or known-token table
192 fall back to ``"unknown"``. ``"unknown"`` is intentionally absent from
193 every :data:`SCOPES_BY_LIST_CMD` entry, so an unclassified field is
194 excluded from every ``list-*`` ``-F`` template — preventing a future
195 untracked field from being silently emitted under a list command
196 where it might crash older tmux. Add such a field to
197 :data:`_SCOPE_OVERRIDES` (or the appropriate prefix / known-token
198 table) to admit it.
199
200 Examples
201 --------
202 >>> from libtmux.neo import _token_scope
203 >>> _token_scope("pane_id")
204 'pane'
205 >>> _token_scope("window_zoomed_flag")
206 'window'
207 >>> _token_scope("client_name")
208 'client'
209 >>> _token_scope("version")
210 'universal'
211 >>> _token_scope("mouse_x")
212 'event'
213
214 Tokens whose name doesn't carry a scope prefix can still be scope-gated
215 via :data:`_SCOPE_OVERRIDES` (verified against tmux's ``format_cb_*``).
216 The override also corrects prefix-misclassified tokens — e.g.
217 ``mouse_all_flag`` is a per-pane mode bit, not a runtime mouse event:
218
219 >>> _token_scope("mouse_all_flag")
220 'pane'
221 >>> _token_scope("active_window_index")
222 'session'
223
224 Context-only tokens (registered outside ``format.c``'s static table)
225 route to the ``"context"`` scope and are excluded from every
226 ``list-*`` ``-F`` template:
227
228 >>> _token_scope("command_list_alias")
229 'context'
230 >>> _token_scope("search_match")
231 'context'
232
233 Unclassified tokens fall back to ``"unknown"``, also excluded from
234 every list command:
235
236 >>> _token_scope("libtmux_test_nonexistent_token")
237 'unknown'
238
239 Notes
240 -----
241 Fields whose name doesn't carry one of the scope prefixes in
242 :data:`_SCOPE_PREFIXES` (for example, ``bracket_paste_flag`` and
243 ``synchronized_output_flag``, which are pane-scope but don't start
244 with ``pane_``) MUST be classified via :data:`_SCOPE_OVERRIDES` —
245 otherwise the fail-closed default returns ``"unknown"`` and
246 excludes them from every ``list-*`` ``-F`` template. The drift
247 catcher ``test_every_obj_field_classifies_to_known_scope`` enforces
248 this on the base :class:`Obj`; subclasses that add custom fields
249 must classify them via the same tables.
250 """
251 override = _SCOPE_OVERRIDES.get(field_name)
252 if override is not None:
253 return override
254 for prefix, scope in _SCOPE_PREFIXES:
255 if field_name.startswith(prefix):
256 return scope
257 if field_name in _CONTEXT_ONLY_TOKENS:
258 return "context"
259 if field_name in _UNIVERSAL_TOKENS:
260 return "universal"
261 return "unknown"
262
263
264 def _normalize_tmux_version(version: str) -> LooseVersion:
265 """Convert a tmux version string into a comparable :class:`LooseVersion`.
266
267 tmux master is reported as ``"master"`` (or e.g. ``"3.6a-master"``);
268 treat it as larger than any tagged release.
269
270 Examples
271 --------
272 >>> from libtmux.neo import _normalize_tmux_version
273 >>> _normalize_tmux_version("3.6a") < _normalize_tmux_version("master")
274 True
275 >>> _normalize_tmux_version("3.2a") < _normalize_tmux_version("3.6a")
276 True
277 """
278 if "master" in version.lower():
279 return LooseVersion("99.0")
280 return LooseVersion(version)
281
282
283 @dataclasses.dataclass()
284 class Obj:
285 """Dataclass of generic tmux object.
286
287 Notes
288 -----
289 tmux may return fields from an object's active children along with the
290 object itself. The practical consequence:
291
292 - On a :class:`~libtmux.session.Session` row (``list-sessions``),
293 every ``pane_*`` and ``window_*`` field resolves to the
294 session's current window's **active pane** — *not* "the
295 session's pane" (no such thing). ``session.active_window.window_id``
296 and ``session.active_window.active_pane.pane_id`` are the
297 canonical accessors for the same values.
298 - On a :class:`~libtmux.window.Window` row (``list-windows``),
299 every ``pane_*`` field resolves to that window's active pane.
300 - On a :class:`~libtmux.client.Client` row (``list-clients``),
301 every ``session_*``, ``window_*``, and ``pane_*`` field reflects
302 the client's attached session, current window, and active pane.
303
304 A reader who treats ``session.pane_id`` as the literal session's
305 pane id (rather than "active pane of this session's current
306 window") will be surprised when the active window changes.
307 """
308
309 server: Server
310
311 active_window_index: str | None = None
312 alternate_saved_x: str | None = None
313 alternate_saved_y: str | None = None
314 bracket_paste_flag: str | None = None
315 buffer_name: str | None = None
316 buffer_sample: str | None = None
317 buffer_size: str | None = None
318 client_activity: str | None = None
319 client_cell_height: str | None = None
320 client_cell_width: str | None = None
321 client_control_mode: str | None = None
322 client_created: str | None = None
323 client_discarded: str | None = None
324 client_flags: str | None = None
325 client_height: str | None = None
326 client_key_table: str | None = None
327 client_last_session: str | None = None
328 client_mode_format: str | None = None
329 client_name: str | None = None
330 client_pid: str | None = None
331 client_prefix: str | None = None
332 client_readonly: str | None = None
333 client_session: str | None = None
334 client_termfeatures: str | None = None
335 client_termname: str | None = None
336 client_termtype: str | None = None
337 client_tty: str | None = None
338 client_uid: str | None = None
339 client_user: str | None = None
340 client_utf8: str | None = None
341 client_width: str | None = None
342 client_written: str | None = None
343 command_list_alias: str | None = None
344 command_list_name: str | None = None
345 command_list_usage: str | None = None
346 config_files: str | None = None
347 copy_cursor_line: str | None = None
348 copy_cursor_word: str | None = None
349 copy_cursor_x: str | None = None
350 copy_cursor_y: str | None = None
351 current_file: str | None = None
352 cursor_character: str | None = None
353 cursor_flag: str | None = None
354 cursor_x: str | None = None
355 cursor_y: str | None = None
356 history_bytes: str | None = None
357 history_limit: str | None = None
358 history_size: str | None = None
359 insert_flag: str | None = None
360 keypad_cursor_flag: str | None = None
361 keypad_flag: str | None = None
362 last_window_index: str | None = None
363 line: str | None = None
364 mouse_all_flag: str | None = None
365 mouse_any_flag: str | None = None
366 mouse_button_flag: str | None = None
367 mouse_sgr_flag: str | None = None
368 mouse_standard_flag: str | None = None
369 next_session_id: str | None = None
370 origin_flag: str | None = None
371 pane_active: str | None = None # Not detected by script
372 pane_at_bottom: str | None = None
373 pane_at_left: str | None = None
374 pane_at_right: str | None = None
375 pane_at_top: str | None = None
376 pane_bg: str | None = None
377 pane_bottom: str | None = None
378 pane_current_command: str | None = None
379 pane_current_path: str | None = None
380 pane_dead: str | None = None
381 pane_dead_signal: str | None = None
382 pane_dead_status: str | None = None
383 pane_dead_time: str | None = None
384 pane_fg: str | None = None
385 pane_flags: str | None = None
386 pane_floating_flag: str | None = None
387 pane_format: str | None = None
388 pane_height: str | None = None
389 pane_id: str | None = None
390 pane_in_mode: str | None = None
391 pane_index: str | None = None
392 pane_input_off: str | None = None
393 pane_last: str | None = None
394 pane_left: str | None = None
395 pane_marked: str | None = None
396 pane_marked_set: str | None = None
397 pane_mode: str | None = None
398 pane_path: str | None = None
399 pane_pb_progress: str | None = None
400 pane_pb_state: str | None = None
401 pane_pid: str | None = None
402 pane_pipe: str | None = None
403 pane_pipe_pid: str | None = None
404 pane_right: str | None = None
405 pane_search_string: str | None = None
406 pane_start_command: str | None = None
407 pane_start_path: str | None = None
408 pane_synchronized: str | None = None
409 pane_tabs: str | None = None
410 pane_title: str | None = None
411 pane_top: str | None = None
412 pane_tty: str | None = None
413 pane_width: str | None = None
414 pane_x: str | None = None
415 pane_y: str | None = None
416 pane_z: str | None = None
417 pane_zoomed_flag: str | None = None
418 pid: str | None = None
419 scroll_position: str | None = None
420 scroll_region_lower: str | None = None
421 scroll_region_upper: str | None = None
422 search_match: str | None = None
423 selection_end_x: str | None = None
424 selection_end_y: str | None = None
425 selection_start_x: str | None = None
426 selection_start_y: str | None = None
427 session_activity: str | None = None
428 session_alerts: str | None = None
429 session_attached: str | None = None
430 session_attached_list: str | None = None
431 session_created: str | None = None
432 session_format: str | None = None
433 session_group: str | None = None
434 session_group_attached: str | None = None
435 session_group_attached_list: str | None = None
436 session_group_list: str | None = None
437 session_group_many_attached: str | None = None
438 session_group_size: str | None = None
439 session_grouped: str | None = None
440 session_id: str | None = None
441 session_last_attached: str | None = None
442 session_many_attached: str | None = None
443 session_marked: str | None = None
444 session_name: str | None = None
445 session_path: str | None = None
446 session_stack: str | None = None
447 session_windows: str | None = None
448 socket_path: str | None = None
449 start_time: str | None = None
450 synchronized_output_flag: str | None = None
451 uid: str | None = None
452 user: str | None = None
453 version: str | None = None
454 window_active: str | None = None # Not detected by script
455 window_active_clients: str | None = None
456 window_active_clients_list: str | None = None
457 window_active_sessions: str | None = None
458 window_active_sessions_list: str | None = None
459 window_activity: str | None = None
460 window_activity_flag: str | None = None
461 window_bell_flag: str | None = None
462 window_bigger: str | None = None
463 window_cell_height: str | None = None
464 window_cell_width: str | None = None
465 window_end_flag: str | None = None
466 window_flags: str | None = None
467 window_format: str | None = None
468 window_height: str | None = None
469 window_id: str | None = None
470 window_index: str | None = None
471 window_last_flag: str | None = None
472 window_layout: str | None = None
473 window_linked: str | None = None
474 window_linked_sessions: str | None = None
475 window_linked_sessions_list: str | None = None
476 window_marked_flag: str | None = None
477 window_name: str | None = None
478 window_offset_x: str | None = None
479 window_offset_y: str | None = None
480 window_panes: str | None = None
481 window_raw_flags: str | None = None
482 window_silence_flag: str | None = None
483 window_stack_index: str | None = None
484 window_start_flag: str | None = None
485 window_visible_layout: str | None = None
486 window_width: str | None = None
487 window_zoomed_flag: str | None = None
488 wrap_flag: str | None = None
489
490 def _refresh(
491 self,
492 obj_key: str,
493 obj_id: str,
494 list_cmd: ListCmd = "list-panes",
495 list_extra_args: ListExtraArgs = None,
496 ) -> None:
497 """Refresh dataclass fields from a single ``list-*`` row.
498
499 Used by the public ``refresh()`` methods on :class:`~libtmux.Pane`,
500 :class:`~libtmux.Window`, :class:`~libtmux.Session`, and
501 :class:`~libtmux.Client`. Each subclass guards its identity field
502 (``pane_id``, ``window_id``, ``session_id``, ``client_name``)
503 against ``None`` before delegating here; this base method enforces
504 the same precondition explicitly so the guarantee survives
505 ``python -O``, where an ``assert`` would be stripped.
506
507 Raises
508 ------
509 ValueError
510 When ``obj_id`` is ``None``. Surfaces a clear error under
511 ``python -O``, matching the contract of the public ``refresh()``
512 methods.
513 """
514 if obj_id is None:
515 msg = "Obj._refresh requires a non-None obj_id"
516 raise ValueError(msg)
517 obj = fetch_obj(
518 obj_key=obj_key,
519 obj_id=obj_id,
520 list_cmd=list_cmd,
521 list_extra_args=list_extra_args,
522 server=self.server,
523 )
524 assert obj is not None
525 if obj is not None:
526 for k, v in obj.items():
527 setattr(self, k, v)
528
529
530 @functools.cache
531 def get_output_format(
532 list_cmd: str = "list-panes",
533 tmux_version: str = "3.2a",
534 ) -> tuple[tuple[str, ...], str]:
535 """Return field names and tmux format string filtered by scope and version.
536
537 Only emits tokens whose scope is reachable from *list_cmd* (per
538 :data:`SCOPES_BY_LIST_CMD`) and whose minimum tmux version (per
539 :data:`FIELD_VERSION`) is at or below *tmux_version*. Runtime-only
540 tokens (``mouse_*``, ``cursor_*``, popups) are excluded from every
541 ``list-*`` template — they only resolve in event-time format contexts.
542
543 Parameters
544 ----------
545 list_cmd : str
546 The tmux list subcommand the format string is being built for.
547 Determines which token scopes are reachable.
548 tmux_version : str
549 The live tmux version. Used to gate post-3.2a tokens. Defaults to
550 ``"3.2a"`` (the project's minimum) for safe fallback when the
551 caller can't yet detect the version.
552
553 Returns
554 -------
555 tuple[tuple[str, ...], str]
556 A tuple of (field_names, tmux_format_string) restricted to tokens
557 the given *list_cmd* and *tmux_version* can resolve.
558
559 Examples
560 --------
561 >>> from libtmux.neo import get_output_format
562 >>> fields, fmt = get_output_format("list-sessions", "3.6a")
563 >>> 'session_id' in fields
564 True
565 >>> 'pane_id' in fields # active pane for the listed session
566 True
567 >>> 'client_name' in fields # upward not allowed
568 False
569 >>> 'server' in fields
570 False
571
572 Pane scope picks up window and session tokens too:
573
574 >>> fields, _ = get_output_format("list-panes", "3.6a")
575 >>> all(t in fields for t in ('pane_id', 'window_id', 'session_id'))
576 True
577
578 ``list-clients`` adds fields for the attached client:
579
580 >>> fields, _ = get_output_format("list-clients", "3.6a")
581 >>> 'client_name' in fields
582 True
583 >>> 'pane_id' in fields
584 True
585 """
586 allowed_scopes = SCOPES_BY_LIST_CMD.get(
587 list_cmd,
588 frozenset({"universal", "session", "window", "pane"}),
589 )
590 live_ver = _normalize_tmux_version(tmux_version)
591
592 formats: list[str] = []
593 for f in Obj.__dataclass_fields__:
594 if f == "server":
595 continue
596 if _token_scope(f) not in allowed_scopes:
597 continue
598 min_v = FIELD_VERSION.get(f)
599 if min_v is not None and _normalize_tmux_version(min_v) > live_ver:
600 continue
601 formats.append(f)
602
603 tmux_format = "".join(f"#{{{n}}}{FORMAT_SEPARATOR}" for n in formats)
604 return tuple(formats), tmux_format
605
606
607 def parse_output(
608 output: str,
609 list_cmd: str = "list-panes",
610 tmux_version: str = "3.2a",
611 ) -> OutputRaw:
612 """Parse a tmux ``-F`` line into a dict keyed by Obj field name.
613
614 The (*list_cmd*, *tmux_version*) pair must match what was passed to
615 :func:`get_output_format` when the ``-F`` template was built —
616 otherwise the field order won't line up with the split values.
617
618 Parameters
619 ----------
620 output : str
621 Raw tmux output line produced with a template from
622 :func:`get_output_format`.
623 list_cmd : str
624 Same value passed to :func:`get_output_format`.
625 tmux_version : str
626 Same value passed to :func:`get_output_format`.
627
628 Returns
629 -------
630 OutputRaw
631 A dict mapping field names to non-empty string values.
632
633 Examples
634 --------
635 >>> from libtmux.neo import get_output_format, parse_output
636 >>> from libtmux.formats import FORMAT_SEPARATOR
637 >>> fields, fmt = get_output_format("list-sessions", "3.6a")
638 >>> values = [''] * len(fields)
639 >>> values[fields.index('session_id')] = '$1'
640 >>> result = parse_output(
641 ... FORMAT_SEPARATOR.join(values) + FORMAT_SEPARATOR,
642 ... list_cmd="list-sessions",
643 ... tmux_version="3.6a",
644 ... )
645 >>> result['session_id']
646 '$1'
647 >>> 'pane_id' in result
648 False
649 """
650 formats, _ = get_output_format(list_cmd, tmux_version)
651 values = output.split(FORMAT_SEPARATOR)
652
653 # Remove the trailing empty string from the split
654 if values and values[-1] == "":
655 values = values[:-1]
656
657 formatter = dict(zip(formats, values, strict=True))
658 return {k: v for k, v in formatter.items() if v}
659
660
661 def fetch_objs(
662 server: Server,
663 list_cmd: ListCmd,
664 list_extra_args: ListExtraArgs = None,
665 filter: str | None = None, # noqa: A002
666 ) -> OutputsRaw:
667 """Fetch a listing of raw data from a tmux command.
668
669 Runs a tmux list command (e.g. ``list-sessions``) with the format string
670 from :func:`get_output_format` and parses each line of output into a dict.
671
672 Parameters
673 ----------
674 server : :class:`~libtmux.server.Server`
675 The tmux server to query.
676 list_cmd : ListCmd
677 The tmux list command to run, e.g. ``"list-sessions"``,
678 ``"list-windows"``, or ``"list-panes"``.
679 list_extra_args : ListExtraArgs, optional
680 Extra arguments appended to the tmux command (e.g. ``("-a",)``
681 for all windows/panes, or ``["-t", session_id]`` to filter).
682 filter : str, optional
683 Filter expression evaluated by tmux (``-f`` flag). tmux omits rows
684 whose expanded expression is false before libtmux parses the result.
685
686 .. warning::
687
688 tmux silently expands a malformed filter (unclosed ``#{...}``,
689 unknown format token) to empty, which is treated as false —
690 every row is suppressed and no stderr is emitted. A bad filter
691 is indistinguishable from "filter matched nothing"; verify the
692 expression against the FORMATS section of ``tmux(1)``. See
693 :ref:`native-filtering` for the typed wrappers that share this
694 caveat.
695
696 .. versionadded:: 0.57
697
698 Returns
699 -------
700 OutputsRaw
701 A list of dicts, each mapping tmux format field names to their
702 non-empty string values.
703
704 Raises
705 ------
706 :exc:`~libtmux.exc.LibTmuxException`
707 If the tmux command writes to stderr.
708
709 Examples
710 --------
711 >>> from libtmux.neo import fetch_objs
712 >>> objs = fetch_objs(server=server, list_cmd="list-sessions")
713 >>> isinstance(objs, list)
714 True
715 >>> isinstance(objs[0], dict)
716 True
717 >>> 'session_id' in objs[0]
718 True
719 """
720 tmux_version = str(get_version(tmux_bin=server.tmux_bin))
721 _fields, format_string = get_output_format(list_cmd, tmux_version)
722
723 cmd_args: list[str | int] = []
724
725 if server.socket_name:
726 cmd_args.insert(0, f"-L{server.socket_name}")
727 if server.socket_path:
728 cmd_args.insert(0, f"-S{server.socket_path}")
729
730 tmux_cmds = [
731 *cmd_args,
732 list_cmd,
733 ]
734
735 if list_extra_args is not None and isinstance(list_extra_args, Iterable):
736 tmux_cmds.extend(list(list_extra_args))
737
738 if filter is not None:
739 tmux_cmds.extend(["-f", filter])
740
741 tmux_cmds.append(f"-F{format_string}")
742
743 cmd_str: str | None = None
744
745 if logger.isEnabledFor(logging.DEBUG):
746 cmd_str = shlex.join([str(x) for x in tmux_cmds])
747 logger.debug(
748 "tmux list queried",
749 extra={
750 "tmux_subcommand": list_cmd,
751 "tmux_cmd": cmd_str,
752 },
753 )
754
755 proc = tmux_cmd(
756 *tmux_cmds,
757 tmux_bin=server.tmux_bin,
758 )
759
760 raise_if_stderr(proc, list_cmd)
761
762 outputs = [parse_output(line, list_cmd, tmux_version) for line in proc.stdout]
763
764 if logger.isEnabledFor(logging.DEBUG):
765 if cmd_str is None:
766 cmd_str = shlex.join([str(x) for x in tmux_cmds])
767 logger.debug(
768 "tmux list parsed",
769 extra={
770 "tmux_subcommand": list_cmd,
771 "tmux_cmd": cmd_str,
772 "tmux_stdout_len": len(proc.stdout),
773 },
774 )
775
776 return outputs
777
778
779 def fetch_obj(
780 server: Server,
781 obj_key: str,
782 obj_id: str,
783 list_cmd: ListCmd = "list-panes",
784 list_extra_args: ListExtraArgs = None,
785 ) -> OutputRaw:
786 """Fetch raw data from tmux command."""
787 obj_formatters_filtered = fetch_objs(
788 server=server,
789 list_cmd=list_cmd,
790 list_extra_args=list_extra_args,
791 )
792
793 obj = None
794 for _obj in obj_formatters_filtered:
795 if _obj.get(obj_key) == obj_id:
796 obj = _obj
797
798 if obj is None:
799 raise exc.TmuxObjectDoesNotExist(
800 obj_key=obj_key,
801 obj_id=obj_id,
802 list_cmd=list_cmd,
803 list_extra_args=list_extra_args,
804 )
805
806 assert obj is not None
807
808 return obj