# ruff: noqa: E501 """Helpers for tmux options. Option parsing function trade testability and clarity for performance. Tmux options ------------ Options in tmux consist of empty values, strings, integers, arrays, and complex shapes. Marshalling types from text: Integers: ``buffer-limit 50`` to ``{'buffer-limit': 50}`` Booleans: ``exit-unattached on`` to ``{'exit-unattached': True}`` Exploding arrays: ``command-alias[1] split-pane=split-window`` to ``{'command-alias[1]': {'split-pane=split-window'}}`` However, there is no equivalent to the above type of object in Python (a sparse array), so a SparseArray is used. Exploding complex shapes: ``"choose-session=choose-tree -s"`` to ``{'choose-session': 'choose-tree -s'}`` Finally, we need to convert hyphenated keys to underscored attribute names and assign values, as python does not allow hyphens in attribute names. ``command-alias`` is ``command_alias`` in python. Options object -------------- Dataclasses are used to provide typed access to tmux' option shape. Extra data gleaned from the options, such as user options (custom data) and an option being inherited, User options ------------ There are also custom user options, preceded with @, which exist are stored to `Options.context.user_options` as a dictionary. > tmux set-option -w my-custom-variable my-value invalid option: my-custom-option > tmux set-option -w @my-custom-option my-value > tmux show-option -w @my-custom-optione my-value Inherited options ----------------- ``tmux show-options`` -A can include inherited options. The raw output of an inherited option is detected by the key having a ``*``:: visual-activity* on visual-bell* off A list of options that are inherited is kept at ``Options.context._inherited_options`` and ``Options.context.inherited_options``. They are mixed with the normal options, to differentiate them, run ``show_options()`` without ``include_inherited=True``. """ from __future__ import annotations import io import logging import re import shlex import typing as t import warnings from libtmux._internal.sparse_array import SparseArray from libtmux.common import CmdMixin from libtmux.constants import ( DEFAULT_OPTION_SCOPE, OPTION_SCOPE_FLAG_MAP, OptionScope, _DefaultOptionScope, ) from . import exc if t.TYPE_CHECKING: from typing import TypeAlias from typing_extensions import Self from libtmux._internal.constants import TerminalFeatures from libtmux.common import tmux_cmd TerminalOverride = dict[str, str | None] TerminalOverrides = dict[str, TerminalOverride] CommandAliases = dict[str, str] OptionDict: TypeAlias = dict[str, t.Any] UntypedOptionsDict: TypeAlias = dict[str, str | None] ExplodedUntypedOptionsDict: TypeAlias = dict[ str, str | int | list[str] | dict[str, list[str]], ] ExplodedComplexUntypedOptionsDict: TypeAlias = dict[ str, str | int | list[str | int] | dict[str, list[str | int]] | SparseArray[str | int] | None, ] logger = logging.getLogger(__name__) def handle_option_error(error: str) -> type[exc.OptionError]: """Raise exception if error in option command found. In tmux 3.0, show-option and show-window-option return invalid option instead of unknown option. See https://github.com/tmux/tmux/blob/3.0/cmd-show-options.c. In tmux >2.4, there are 3 different types of option errors: - unknown option - invalid option - ambiguous option In tmux <2.4, unknown option was the only option. All errors raised will have the base error of :exc:`exc.OptionError`. So to catch any option error, use ``except exc.OptionError``. Parameters ---------- error : str Error response from subprocess call. Raises ------ :exc:`exc.OptionError`, :exc:`exc.UnknownOption`, :exc:`exc.InvalidOption`, :exc:`exc.AmbiguousOption` Examples -------- >>> result = server.cmd( ... 'set-option', ... 'unknown-option-name', ... ) >>> bool(isinstance(result.stderr, list) and len(result.stderr)) True >>> import pytest >>> from libtmux import exc >>> with pytest.raises(exc.OptionError): ... handle_option_error(result.stderr[0]) """ if "unknown option" in error: raise exc.UnknownOption(error) if "invalid option" in error: raise exc.InvalidOption(error) if "ambiguous option" in error: raise exc.AmbiguousOption(error) raise exc.OptionError(error) # Raise generic option error _V = t.TypeVar("_V") ConvertedValue: TypeAlias = str | int | bool | None ConvertedValues: TypeAlias = ( ConvertedValue | list[ConvertedValue] | dict[str, ConvertedValue] | SparseArray[ConvertedValue] ) def convert_value( value: _V | None, ) -> ConvertedValue | _V | None: """Convert raw option strings to python types. Examples -------- >>> convert_value("on") True >>> convert_value("off") False >>> convert_value("1") 1 >>> convert_value("50") 50 >>> convert_value("%50") '%50' """ if not isinstance(value, str): return value if value.isdigit(): return int(value) if value == "on": return True if value == "off": return False return value def convert_values( value: _V | None, ) -> ConvertedValues | _V | None: """Recursively convert values to python types via :func:`convert_value`. >>> convert_values(None) >>> convert_values("on") True >>> convert_values("off") False >>> convert_values(["on"]) [True] >>> convert_values(["off"]) [False] >>> convert_values({"window_index": "1"}) {'window_index': 1} >>> convert_values({"visual-bell": "on"}) {'visual-bell': True} """ if value is None: return None if isinstance(value, dict): # Note: SparseArray inherits from dict, so this branch handles both for k, v in value.items(): value[k] = convert_value(v) return value if isinstance(value, list): for idx, v in enumerate(value): value[idx] = convert_value(v) return value return convert_value(value) def parse_options_to_dict( stdout: t.IO[str], ) -> UntypedOptionsDict: r"""Process subprocess.stdout options or hook output to flat, naive, untyped dict. Does not explode arrays or deep values. Examples -------- >>> import io >>> raw_options = io.StringIO("status-keys vi") >>> parse_options_to_dict(raw_options) == {"status-keys": "vi"} True >>> int_options = io.StringIO("message-limit 50") >>> parse_options_to_dict(int_options) == {"message-limit": "50"} True >>> empty_option = io.StringIO("user-keys") >>> parse_options_to_dict(empty_option) == {"user-keys": None} True >>> array_option = io.StringIO("command-alias[0] split-pane=split-window") >>> parse_options_to_dict(array_option) == { ... "command-alias[0]": "split-pane=split-window"} True >>> array_option = io.StringIO("command-alias[40] split-pane=split-window") >>> parse_options_to_dict(array_option) == { ... "command-alias[40]": "split-pane=split-window"} True >>> many_options = io.StringIO(r'''status-keys ... command-alias[0] split-pane=split-window ... ''') >>> parse_options_to_dict(many_options) == { ... "command-alias[0]": "split-pane=split-window", ... "status-keys": None,} True >>> many_more_options = io.StringIO(r''' ... terminal-features[0] xterm*:clipboard:ccolour:cstyle:focus ... terminal-features[1] screen*:title ... ''') >>> parse_options_to_dict(many_more_options) == { ... "terminal-features[0]": "xterm*:clipboard:ccolour:cstyle:focus", ... "terminal-features[1]": "screen*:title",} True >>> quoted_option = io.StringIO(r''' ... command-alias[0] "choose-session=choose-tree -s" ... ''') >>> parse_options_to_dict(quoted_option) == { ... "command-alias[0]": "choose-session=choose-tree -s", ... } True """ output: UntypedOptionsDict = {} val: ConvertedValue | None = None for item in stdout.readlines(): if " " in item: try: key, val = shlex.split(item) except ValueError: key, val = item.split(" ", maxsplit=1) else: key, val = item, None key = key.strip() if key: if isinstance(val, str) and val.endswith("\n"): val = val.rstrip("\n") output[key] = val return output def explode_arrays( _dict: UntypedOptionsDict, force_array: bool = False, ) -> ExplodedUntypedOptionsDict: """Explode flat, naive options dict's option arrays. Examples -------- >>> import io >>> many_more_options = io.StringIO(r''' ... terminal-features[0] xterm*:clipboard:ccolour:cstyle:focus ... terminal-features[1] screen*:title ... ''') >>> many_more_flat_dict = parse_options_to_dict(many_more_options) >>> many_more_flat_dict == { ... "terminal-features[0]": "xterm*:clipboard:ccolour:cstyle:focus", ... "terminal-features[1]": "screen*:title",} True >>> explode_arrays(many_more_flat_dict) == { ... "terminal-features": {0: "xterm*:clipboard:ccolour:cstyle:focus", ... 1: "screen*:title"}} True tmux arrays allow non-sequential indexes, so we need to support that: >>> explode_arrays(parse_options_to_dict(io.StringIO(r''' ... terminal-features[0] xterm*:clipboard:ccolour:cstyle:focus ... terminal-features[5] screen*:title ... '''))) == { ... "terminal-features": {0: "xterm*:clipboard:ccolour:cstyle:focus", ... 5: "screen*:title"}} True Use ``force_array=True`` for hooks, which always use array format: >>> from libtmux._internal.sparse_array import SparseArray >>> hooks_output = io.StringIO(r''' ... session-renamed[0] display-message 'renamed' ... session-renamed[5] refresh-client ... pane-focus-in[0] run-shell 'echo focus' ... ''') >>> hooks_exploded = explode_arrays( ... parse_options_to_dict(hooks_output), ... force_array=True, ... ) Each hook becomes a SparseArray preserving indices: >>> isinstance(hooks_exploded["session-renamed"], SparseArray) True >>> hooks_exploded["session-renamed"][0] "display-message 'renamed'" >>> hooks_exploded["session-renamed"][5] 'refresh-client' >>> sorted(hooks_exploded["session-renamed"].keys()) [0, 5] """ options: dict[str, t.Any] = {} for key, val in _dict.items(): Default: type[dict[t.Any, t.Any] | SparseArray[str | int | bool | None]] = ( dict if isinstance(key, str) and key == "terminal-features" else SparseArray ) if "[" not in key: if force_array: options[key] = Default() if val is not None: options[key][0] = val else: options[key] = val continue try: matchgroup = re.match( r"(?P