diff --git a/docs/changelog.rst b/docs/changelog.rst index 63b0f4404..436de616f 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -142,6 +142,11 @@ Detailed list of changes and ``on_resize``/``on_focus_change`` calls are no longer dropped when many windows are created at once (:disc:`10828`, :iss:`10853`) +- Allow running the programs in new windows via a wrapper command, such as to + open new windows inside the same container as the window they are opened + from, using a :file:`launch_wrapper.py` file in the kitty config directory, + see :ref:`launch_wrapper` (:iss:`10858`) + - Sessions: Fix tabs and windows moved with :ac:`detach_tab`, :ac:`detach_window` or drag and drop losing their session. :ac:`save_as_session` no longer opens saved sessions in the wrong OS Window or tab and no longer diff --git a/docs/launch.rst b/docs/launch.rst index 9047a088c..b0e4ebdcc 100644 --- a/docs/launch.rst +++ b/docs/launch.rst @@ -256,6 +256,130 @@ Run, ``kitten @ --help`` in a kitty terminal, to see all the remote control commands available to you. +.. _launch_wrapper: + +Wrapping the programs run in new windows +------------------------------------------- + +.. versionadded:: 0.50.1 + +You can have kitty run the program in every new window via a wrapper command of +your choosing, for example, to open new windows inside the same container or +development environment as the window they are opened from. To do so, create +the file :file:`launch_wrapper.py` in the kitty config directory, defining a +function named ``prefix_for_launch()``. kitty calls it just before starting the +program in a new window and runs the program with the list of strings it returns +placed before the command. Return ``None`` or an empty list to run the program +unchanged. For example: + +.. code-block:: python + + # ~/.config/kitty/launch_wrapper.py + from collections.abc import Sequence + + from kitty.launch_wrapper import LaunchContext + + + def in_nix_shell(pid: int) -> bool: + # Whether a process was started inside a nix develop shell, detected + # from the environment variables it was started with + try: + with open(f'/proc/{pid}/environ', 'rb') as f: + return b'IN_NIX_SHELL=' in f.read() + except OSError: + return False + + + def prefix_for_launch(ctx: LaunchContext) -> Sequence[str] | None: + # Open new windows in the nix develop environment of their working + # directory, when opened from a window in a nix develop shell + if ctx.source_pid is not None and in_nix_shell(ctx.source_pid): + return ['nix', 'develop', '--command'] + return None + +The function is passed a ``LaunchContext`` object with the following fields: + +``argv`` + The command that will be run, as a tuple of strings +``cwd`` + The working directory the command will run in +``env`` + A read-only mapping of the environment variables the command will be run + with, including the ones kitty sets for :ref:`shell_integration` and + :doc:`remote control ` +``is_default_shell`` + True if the command is the shell from :opt:`shell` +``window_id`` + The id of the new window +``launch_type`` + The type of the new window, the same as the values of :option:`launch --type`, + such as ``window``, ``tab``, ``os-window`` or ``overlay`` +``source_window_id`` + The id of the window the new one is opened from, or ``None``. This is the + window the working directory is taken from when using :option:`launch --cwd` + and the like, otherwise the active window +``source_pid`` + The process id of the foreground process in the source window, or ``None``. + You can use it to find out the environment the source window is running + in, by reading files such as :file:`/proc/{pid}/environ`, + :file:`/proc/{pid}/cgroup` or :file:`/proc/{pid}/cmdline` on Linux. +``user_vars`` + A read-only mapping of the user variables set via :option:`launch --var`. + Since user variables are saved in :doc:`sessions `, you can use + them to start a restored window via the same wrapper as the original, + for example, by setting a user variable from a :ref:`watcher `. + +The wrapper is used for windows created at your request: by the +:doc:`launch ` command, including via :doc:`remote control +` and in :doc:`sessions `, by actions such as +:ac:`new_window`, :ac:`new_tab` and :ac:`new_os_window`, the new tab button in +the tab bar, the macOS menus and the first window kitty creates on startup. It +is not used for windows kitty creates internally, such as for kittens, the +scrollback pager, error messages, or the editor run by :program:`edit-in-kitty`. +It is also not used for background processes or programs run via the legacy +`pipe` action. + +Keep the following in mind when writing a wrapper: + +* The wrapper must run its arguments as the command, with the working directory + and environment it receives from kitty. In particular, it must pass through + the environment variables kitty sets, otherwise features such as + :ref:`shell_integration` and remote control will not work in the new window. + Use ``ctx.env`` to see what they are. + +* kitty may insert its own helper programs between the wrapper and + ``ctx.argv``, such as :program:`kitten run-shell` to set up shell integration. + These must be able to run wherever the wrapper runs the command. This is the + case for wrappers that share the host filesystem, such as :program:`toolbox`, + :program:`distrobox`, :code:`nix develop -c` and :code:`direnv exec`. + +* On macOS, when the shell is run via :program:`/usr/bin/login`, the wrapper + runs inside it, with the home directory as its working directory. Use + ``ctx.cwd`` if the wrapper needs to know the actual working directory. + +* The function is called synchronously, whenever a window is created, so keep + it fast. If it fails, the error is reported and the program is run without + a wrapper, so that you can still open windows to fix it. + +* The wrapper is not saved in :doc:`sessions `, the function is + called again when a session is restored. + +The file is re-loaded when the kitty config is reloaded, and is ignored when +kitty is run with :option:`kitty --config` = :code:`NONE`. + +Why a prefix, rather than a new command and environment? +____________________________________________________________ + +A prefix can do anything a replacement could, as the wrapper is a program you +control: it can change the environment and working directory before running +the command, or not run it at all. However, kitty needs to know what the +command is, to set up :ref:`shell_integration`, which depends on the shell +being run, to track the processes running in the window, to save the window +in :doc:`sessions ` and to clone it with :program:`clone-in-kitty`. +With a prefix, kitty keeps knowing the actual command and can skip over +the wrapper when needed. A replacement command would silently break these +features. + Finding executables ----------------------- diff --git a/kitty/boss.py b/kitty/boss.py index 14cab3103..154d00f26 100644 --- a/kitty/boss.py +++ b/kitty/boss.py @@ -146,6 +146,7 @@ from .fast_data_types import ( ) from .key_encoding import get_name_to_functional_number_map from .keys import Mappings +from .launch_wrapper import user_launch_request from .layout.base import set_layout_options from .notifications import NotificationManager from .options.types import Options, nullable_colors @@ -762,7 +763,7 @@ class Boss: sw: SpecialWindowInstance | None = args else: args = tuple(args) - sw = self.args_to_special_window(args, cwd_from) if args else None + sw = self.args_to_special_window(args, cwd_from, launch_type='os-window') if args else None startup_session = next(create_sessions(get_options(), special_window=sw, cwd_from=cwd_from)) startup_session.session_name = '' ans = self.add_os_window(startup_session) @@ -801,7 +802,7 @@ class Boss: if isinstance(wd, str): wd = wd.split(os.pathsep) if str_is_multiple_paths else [wd] for path in wd: - special_window = SpecialWindow(None, cwd=path) + special_window = SpecialWindow(None, cwd=path, launch_request=user_launch_request('os-window')) self._new_os_window(special_window) def add_child(self, window: Window) -> None: @@ -3521,7 +3522,7 @@ class Boss: self.run_background_process(cmd, cwd_from=cwd_from, stdin=stdin, env=env) return None - def args_to_special_window(self, args: Iterable[str], cwd_from: CwdRequest | None = None) -> SpecialWindowInstance: + def args_to_special_window(self, args: Iterable[str], cwd_from: CwdRequest | None = None, launch_type: str = 'window') -> SpecialWindowInstance: args = list(args) stdin = None w = self.active_window @@ -3540,7 +3541,7 @@ class Boss: continue arg = q cmd.append(arg) - return SpecialWindow(cmd, stdin, cwd_from=cwd_from) + return SpecialWindow(cmd, stdin, cwd_from=cwd_from, launch_request=user_launch_request(launch_type, cwd_from)) def _new_tab(self, args: SpecialWindowInstance | Iterable[str], cwd_from: CwdRequest | None = None, as_neighbor: bool = False) -> Tab | None: special_window = None @@ -3549,7 +3550,7 @@ class Boss: else: args = tuple(args) if args: - special_window = self.args_to_special_window(args, cwd_from=cwd_from) + special_window = self.args_to_special_window(args, cwd_from=cwd_from, launch_type='tab') if not self.os_window_map: self.add_os_window() tm = self.active_tab_manager @@ -3585,7 +3586,7 @@ class Boss: if isinstance(wd, str): wd = wd.split(os.pathsep) if str_is_multiple_paths else [wd] for path in wd: - special_window = SpecialWindow(None, cwd=path) + special_window = SpecialWindow(None, cwd=path, launch_request=user_launch_request('tab')) self._new_tab(special_window) def _new_window(self, args: list[str], cwd_from: CwdRequest | None = None) -> Window | None: @@ -3608,7 +3609,9 @@ class Boss: if args: w = tab.new_special_window(self.args_to_special_window(args, cwd_from=cwd_from), location=location, allow_remote_control=allow_remote_control) else: - w = tab.new_window(cwd_from=cwd_from, location=location, allow_remote_control=allow_remote_control) + w = tab.new_window( + cwd_from=cwd_from, location=location, allow_remote_control=allow_remote_control, launch_request=user_launch_request('window', cwd_from) + ) if cwd_from is not None and (sw := cwd_from.window): w.created_in_session_name = sw.effective_session_name return w @@ -3780,6 +3783,10 @@ class Boss: clear_caches() + from .launch_wrapper import clear_caches + + clear_caches() + def safe_delete_temp_file(self, path: str) -> None: if is_path_in_temp_dir(path): with suppress(FileNotFoundError): diff --git a/kitty/child.py b/kitty/child.py index da9763129..1c24ab08e 100644 --- a/kitty/child.py +++ b/kitty/child.py @@ -18,6 +18,7 @@ from .types import run_once from .utils import cmdline_for_hold, log_error, resolved_shell, which if TYPE_CHECKING: + from .launch_wrapper import LaunchRequest from .window import CwdRequest @@ -401,8 +402,10 @@ class Child: remote_control_fd: int = -1, hold_after_ssh: bool = False, startup_command_via_shell_integration: Sequence[str] | str = (), + launch_request: Optional['LaunchRequest'] = None, ): self.is_clone_launch = is_clone_launch + self.launch_request = launch_request self.id = next(child_counter) # Used to cache the root pid, see root_pid self.wrapper_children: dict[int, int] = {} @@ -509,6 +512,7 @@ class Child: self.initial_termios_state = termios.tcgetattr(master) argv = list(self.argv) kitty_wrappers: list[KittyWrapper] = [] + login_argv: list[str] = [] cwd = self.cwd pass_fds = self.pass_fds if self.remote_control_fd > -1: @@ -555,6 +559,20 @@ class Child: kitty_wrappers.insert(0, KittyWrapper(tuple(login_argv), False)) self.final_exe = final_exe = which(argv[0]) or argv[0] self.final_argv0 = argv[0] + if self.launch_request is not None: + from .launch_wrapper import prefix_for_launch + + if user_prefix := prefix_for_launch(self.launch_request, self.argv, self.cwd, self.final_env): + # The user's wrapper goes inside /usr/bin/login, if present, + # but outside everything else, so that kitty's own helpers + # such as the run-shell kitten see the actual command. + pos = len(login_argv) if login_argv else 0 + argv[pos:pos] = user_prefix + if pos == 0: + final_exe = which(argv[0]) or argv[0] + # The wrapper either replaces itself with the command or runs + # it as a child, either way it is not the root process + kitty_wrappers.append(KittyWrapper(user_prefix, True)) if self.hold: hold_argv = cmdline_for_hold() argv = hold_argv + argv diff --git a/kitty/launch.py b/kitty/launch.py index c99dbcbe4..33fd22ffc 100644 --- a/kitty/launch.py +++ b/kitty/launch.py @@ -15,6 +15,7 @@ from .cli_stub import LaunchCLIOptions from .clipboard import set_clipboard_string, set_primary_selection from .constants import is_wayland from .fast_data_types import COLOR_LAYER_WINDOW, add_timer, get_boss, get_options, get_os_window_title, patch_color_profiles +from .launch_wrapper import LaunchRequest from .options.utils import env as parse_env from .tabs import Tab, TabManager from .types import DockSpec, LayerShellConfig, OverlayType, dock_edges, parse_dock_spec, run_once @@ -762,6 +763,7 @@ def _launch( child_death_callback: Callable[[int, Exception | None], None] | None = None, startup_command_via_shell_integration: Sequence[str] | str = (), restored_scrollback: bytes = b'', + use_launch_wrapper: bool = True, ) -> Window | None: source_window = boss.active_window_for_cwd if opts.source_window: @@ -981,6 +983,7 @@ def _launch( tm.host_os_window_docks_in(tab) kw['os_window_dock'] = True watchers = load_watch_modules(opts.watcher) + launch_request = LaunchRequest(opts.type, source_window.id if source_window else None, tuple(parse_var(opts.var))) if use_launch_wrapper else None with Window.set_ignore_focus_changes_for_new_windows(opts.keep_focus): new_window: Window = tab.new_window( env=env or None, @@ -990,6 +993,7 @@ def _launch( startup_command_via_shell_integration=startup_command_via_shell_integration, restored_scrollback=restored_scrollback, dock_owner=dock_owner, + launch_request=launch_request, **kw, ) new_window.created_in_session_name = add_to_session @@ -1038,6 +1042,7 @@ def launch( child_death_callback: Callable[[int, Exception | None], None] | None = None, startup_command_via_shell_integration: Sequence[str] | str = (), restored_scrollback: bytes = b'', + use_launch_wrapper: bool = True, ) -> Window | None: active = boss.active_window if opts.keep_focus and active: @@ -1055,6 +1060,7 @@ def launch( child_death_callback, startup_command_via_shell_integration, restored_scrollback, + use_launch_wrapper, ) finally: if opts.keep_focus and active: @@ -1457,7 +1463,9 @@ def remote_edit(msg: str, window: Window) -> None: return cmdline = get_editor(path_to_edit=c.file_localpath, line_number=c.line_number) c.opts.source_window = c.opts.next_to = f'id:{window.id}' - w = launch(get_boss(), c.opts, cmdline) + # The editor edits a temporary file kitty creates locally, so it must not + # be run via the user's launch wrapper, which might run it in a container + w = launch(get_boss(), c.opts, cmdline, use_launch_wrapper=False) if w is not None: c.source_window_id = window.id c.editor_window_id = w.id diff --git a/kitty/launch_wrapper.py b/kitty/launch_wrapper.py new file mode 100644 index 000000000..72619ba1e --- /dev/null +++ b/kitty/launch_wrapper.py @@ -0,0 +1,160 @@ +#!/usr/bin/env python +# License: GPLv3 Copyright: 2026, Kovid Goyal + +# Support for the user supplied launch_wrapper.py module in the kitty config +# directory, which can prefix the commands kitty runs in new windows with a +# wrapper command. See docs/launch-wrapper.rst + +import os +from collections.abc import Callable, Mapping, Sequence +from types import MappingProxyType +from typing import TYPE_CHECKING, NamedTuple + +from .constants import config_dir, config_dir_files_ignored +from .fast_data_types import get_boss, get_options +from .types import run_once +from .utils import log_error, resolved_shell + +if TYPE_CHECKING: + from .window import CwdRequest + +MODULE_NAME = 'launch_wrapper.py' +FUNCTION_NAME = 'prefix_for_launch' + + +class LaunchRequest(NamedTuple): + """ + Marks a window launch as one requested by the user, rather than one + kitty makes internally, such as for kittens or the scrollback pager. Only + such launches are passed to the launch wrapper. + """ + + # The type of the new window, one of the values of launch --type that + # create windows, such as: window, tab, os-window, overlay, overlay-main + launch_type: str + # The id of the window the new one is being opened from, if any + source_window_id: int | None = None + # The user variables from launch --var + user_vars: tuple[tuple[str, str], ...] = () + + +class LaunchContext(NamedTuple): + # The command kitty will run, before kitty adds its own helpers, such as + # the run-shell kitten or /usr/bin/login on macOS. These are inserted + # between the prefix and this command. + argv: tuple[str, ...] + # The working directory the command should run in + cwd: str + # The full environment the command will be run with, including the + # variables kitty sets, such as for shell integration and remote control. + env: Mapping[str, str] + # True if argv is the shell configured via the shell option + is_default_shell: bool + # The id of the new window, the same as KITTY_WINDOW_ID in env + window_id: int + # See LaunchRequest.launch_type + launch_type: str + # The id of the window the new one is opened from, if any + source_window_id: int | None + # The pid of the foreground process in the source window, if any + source_pid: int | None + # User variables from launch --var + user_vars: Mapping[str, str] + + +PrefixFunc = Callable[[LaunchContext], Sequence[str] | None] + + +@run_once +def load_prefix_func() -> PrefixFunc | None: + if config_dir_files_ignored(): + return None + path = os.path.join(config_dir, MODULE_NAME) + import runpy + + try: + m = runpy.run_path(path) + except FileNotFoundError: + return None + except Exception as e: + import traceback + + traceback.print_exc() + log_error(f'Failed to load {path} with error: {e}') + return None + func = m.get(FUNCTION_NAME) + if not callable(func): + log_error(f'{path} does not define a {FUNCTION_NAME}() function, ignoring it') + return None + ans: PrefixFunc = func + return ans + + +def clear_caches() -> None: + load_prefix_func.clear_cached() + + +def source_pid_for(window_id: int | None) -> int | None: + if window_id is None: + return None + w = get_boss().window_id_map.get(window_id) + if w is None: + return None + try: + return w.child.pid_for_cwd + except Exception as e: + log_error(f'Failed to get the foreground process of window {window_id} with error: {e}') + return None + + +def prefix_for_launch(req: LaunchRequest, argv: Sequence[str], cwd: str, env: Mapping[str, str]) -> tuple[str, ...]: + """ + Return the prefix to run argv with, from the user's launch wrapper. Any + failure is reported and results in no prefix, so that a broken wrapper + does not prevent new windows from being opened. + """ + func = load_prefix_func() + if func is None: + return () + try: + window_id = int(env.get('KITTY_WINDOW_ID', '0')) + except ValueError: + window_id = 0 + ctx = LaunchContext( + argv=tuple(argv), + cwd=cwd, + env=MappingProxyType(dict(env)), + is_default_shell=list(argv) == resolved_shell(get_options()), + window_id=window_id, + launch_type=req.launch_type, + source_window_id=req.source_window_id, + source_pid=source_pid_for(req.source_window_id), + user_vars=MappingProxyType(dict(req.user_vars)), + ) + try: + ans = func(ctx) + except Exception as e: + import traceback + + traceback.print_exc() + log_error(f'The {FUNCTION_NAME}() function in {MODULE_NAME} failed with error: {e}, running the command without a wrapper') + return () + if ans is None: + return () + if isinstance(ans, str) or not isinstance(ans, Sequence) or not all(isinstance(x, str) for x in ans): + log_error(f'The {FUNCTION_NAME}() function in {MODULE_NAME} must return a list of strings or None, got: {ans!r}, ignoring it') + return () + return tuple(ans) + + +def user_launch_request(launch_type: str, cwd_from: 'CwdRequest | None' = None) -> LaunchRequest: + """ + A request for a window the user asked for via a kitty action, such as + new_window or new_tab. The window it is opened from is the one the working + directory is taken from, if any, otherwise the active window. + """ + if cwd_from: + return LaunchRequest(launch_type, cwd_from.window_id) + boss = get_boss() + w = None if boss is None else boss.active_window_for_cwd + return LaunchRequest(launch_type, None if w is None else w.id) diff --git a/kitty/options/definition.py b/kitty/options/definition.py index 4c052e40e..ea80c67e1 100644 --- a/kitty/options/definition.py +++ b/kitty/options/definition.py @@ -2926,6 +2926,8 @@ whatever shell is set as the default shell for the current user. Note that on macOS if you change this, you might need to add :code:`--login` and :code:`--interactive` to ensure that the shell starts in interactive mode and reads its startup rc files. Environment variables are expanded in this setting. +To run every program in new windows, not just the shell, via a wrapper, such as +inside a container, see :ref:`launch_wrapper`. """, ) diff --git a/kitty/session.py b/kitty/session.py index 7042a652b..be3b01534 100644 --- a/kitty/session.py +++ b/kitty/session.py @@ -15,6 +15,7 @@ from typing import TYPE_CHECKING, Any, Optional, Union from .cli_stub import CLIOptions, GotoSessionOptions, SaveAsSessionOptions from .constants import config_dir, unserialize_launch_flag from .fast_data_types import get_options +from .launch_wrapper import LaunchRequest, user_launch_request from .layout.interface import all_layouts from .options.types import Options from .options.utils import MapType, resize_window, to_layout_names, window_size @@ -236,7 +237,7 @@ def parse_session( for t in ans.tabs: if not t.windows: - t.windows.append(WindowSpec(SpecialWindow(cmd=resolved_shell(opts)))) + t.windows.append(WindowSpec(SpecialWindow(cmd=resolved_shell(opts), launch_request=LaunchRequest('tab')))) return ans if environ is None: @@ -372,7 +373,14 @@ def create_sessions( from kitty.tabs import SpecialWindow cwd: str | None = args.directory if respect_cwd and args else None - special_window = SpecialWindow(cmd, cwd_from=cwd_from, cwd=cwd, env=env_when_no_session, hold=bool(args and args.hold)) + special_window = SpecialWindow( + cmd, + cwd_from=cwd_from, + cwd=cwd, + env=env_when_no_session, + hold=bool(args and args.hold), + launch_request=user_launch_request('os-window', cwd_from), + ) ans.add_special_window(special_window) yield ans diff --git a/kitty/tabs.py b/kitty/tabs.py index 977fcaf76..714663c23 100644 --- a/kitty/tabs.py +++ b/kitty/tabs.py @@ -60,6 +60,7 @@ from .fast_data_types import ( swap_tabs, sync_os_window_title, ) +from .launch_wrapper import LaunchRequest, user_launch_request from .layout.base import DragOverlayMode, Layout from .layout.interface import all_layouts, create_layout_object_for, evict_cached_layouts from .progress import ProgressState @@ -165,6 +166,8 @@ class SpecialWindowInstance(NamedTuple): watchers: Watchers | None overlay_behind: bool hold: bool + # Set for windows launched at the user's request, see launch_wrapper.py + launch_request: LaunchRequest | None = None def SpecialWindow( @@ -178,8 +181,9 @@ def SpecialWindow( watchers: Watchers | None = None, overlay_behind: bool = False, hold: bool = False, + launch_request: LaunchRequest | None = None, ) -> SpecialWindowInstance: - return SpecialWindowInstance(cmd, stdin, override_title, cwd_from, cwd, overlay_for, env, watchers, overlay_behind, hold) + return SpecialWindowInstance(cmd, stdin, override_title, cwd_from, cwd, overlay_for, env, watchers, overlay_behind, hold, launch_request) def os_window_geometry_as_session(g: 'OSWindowGeometry', include_position: bool = True) -> list[str]: @@ -291,7 +295,7 @@ class Tab: # {{{ sl = self.enabled_layouts[0] self._set_current_layout(sl) if special_window is None: - self.new_window(cwd_from=cwd_from) + self.new_window(cwd_from=cwd_from, launch_request=user_launch_request('tab', cwd_from)) else: self.new_special_window(special_window) else: @@ -914,6 +918,7 @@ class Tab: # {{{ remote_control_fd: int = -1, hold_after_ssh: bool = False, startup_command_via_shell_integration: Sequence[str] | str = (), + launch_request: LaunchRequest | None = None, ) -> Child: check_for_suitability = True if cmd is None: @@ -974,6 +979,7 @@ class Tab: # {{{ remote_control_fd=remote_control_fd, hold_after_ssh=hold_after_ssh, startup_command_via_shell_integration=startup_command_via_shell_integration, + launch_request=launch_request, ) ans.fork() return ans @@ -1040,6 +1046,7 @@ class Tab: # {{{ dock_owner: WindowGroup | None = None, restored_scrollback: bytes = b'', os_window_dock: bool = False, + launch_request: LaunchRequest | None = None, ) -> Window: """ Create a new window. When dock is specified, the window is docked to @@ -1081,6 +1088,7 @@ class Tab: # {{{ remote_control_fd=remote_control_fd, hold_after_ssh=hold_after_ssh, startup_command_via_shell_integration=startup_command_via_shell_integration, + launch_request=launch_request, ) window = Window( self, @@ -1144,6 +1152,7 @@ class Tab: # {{{ remote_control_passwords=remote_control_passwords, pass_fds=pass_fds, remote_control_fd=remote_control_fd, + launch_request=special_window.launch_request, ) @ac('win', 'Close all windows in the tab other than the currently active window') diff --git a/kitty_tests/child.py b/kitty_tests/child.py index 3f29868b2..3e176080d 100644 --- a/kitty_tests/child.py +++ b/kitty_tests/child.py @@ -4,6 +4,8 @@ import os import subprocess import tempfile +from types import SimpleNamespace +from unittest.mock import patch from kitty.child import Child, KittyWrapper, children_of_process, cmdline_of_pid, cwd_of_process, memory_used_by_process_tree_rooted_at from kitty.constants import is_macos, kitty_exe @@ -251,3 +253,102 @@ time.sleep(300) self.ae(c.root_pid, p.pid) finally: self._terminate_tree(p) + + +class LaunchWrapperTest(BaseTest): + def setUp(self): + super().setUp() + self.set_options({'shell_integration': frozenset({'disabled'})}) + self.contexts = [] + + def tearDown(self): + from kitty.launch_wrapper import load_prefix_func + + load_prefix_func.clear_override() + super().tearDown() + + def _fork(self, argv=('/bin/prog', 'arg'), launch_request=None, hold=False, user_func=None): + # Fork a Child with spawning faked, returning the Child and the + # exe and argv that would have been spawned + from kitty import child as child_module + from kitty.launch_wrapper import load_prefix_func + + load_prefix_func.set_override(user_func) + spawned = {} + + def spawn(exe, cwd, argv, *a): + spawned['exe'], spawned['argv'] = exe, argv + return 1234567 + + boss = SimpleNamespace(encryption_public_key='key', listening_on='', window_id_map={}) + c = Child(list(argv), '/', env={'KITTY_WINDOW_ID': '7'}, hold=hold, launch_request=launch_request) + with ( + patch.object(child_module.fast_data_types, 'spawn', spawn), + patch.object(child_module.fast_data_types, 'get_boss', return_value=boss), + patch.object(child_module.fast_data_types, 'systemd_move_pid_into_new_scope', side_effect=NotImplementedError, create=True), + ): + c.fork() + os.close(c.child_fd) + c.child_fd = None + return c, spawned['exe'], spawned['argv'] + + def _recording(self, ans): + def func(ctx): + self.contexts.append(ctx) + if isinstance(ans, Exception): + raise ans + return ans + + return func + + def test_launch_wrapper(self): + from kitty.launch_wrapper import LaunchRequest + + req = LaunchRequest('tab', None, (('a', 'b'),)) + # Not a user launch, the wrapper is not called + c, exe, argv = self._fork(user_func=self._recording(['wrapper', '-x'])) + self.ae(argv, ('/bin/prog', 'arg')) + self.ae(self.contexts, []) + self.ae(c.kitty_wrappers, ()) + # No launch_wrapper.py + c, exe, argv = self._fork(launch_request=req) + self.ae(argv, ('/bin/prog', 'arg')) + # A prefix is applied, with the actual command still known to kitty + c, exe, argv = self._fork(launch_request=req, user_func=self._recording(['/bin/wrapper', '-x'])) + self.ae(argv, ('/bin/wrapper', '-x', '/bin/prog', 'arg')) + self.ae(exe, '/bin/wrapper') + self.ae(c.argv, ['/bin/prog', 'arg']) + self.ae(c.final_exe, '/bin/prog') + self.ae(c.kitty_wrappers, (KittyWrapper(('/bin/wrapper', '-x'), True),)) + ctx = self.contexts[-1] + self.ae(ctx.argv, ('/bin/prog', 'arg')) + self.ae(ctx.cwd, '/') + self.ae(ctx.window_id, 7) + self.ae(ctx.launch_type, 'tab') + self.ae(ctx.source_window_id, None) + self.ae(ctx.source_pid, None) + self.ae(dict(ctx.user_vars), {'a': 'b'}) + self.ae(ctx.env['KITTY_WINDOW_ID'], '7') + self.assertFalse(ctx.is_default_shell) + with self.assertRaises(TypeError): + ctx.env['x'] = 'y' + # The hold wrapper runs outside the user's wrapper + c, exe, argv = self._fork(launch_request=req, hold=True, user_func=self._recording(['/bin/wrapper'])) + self.ae(argv[-2:], ('/bin/prog', 'arg')) + self.ae(argv[-3], '/bin/wrapper') + self.ae(c.kitty_wrappers[-1], KittyWrapper(('/bin/wrapper',), True)) + self.ae(len(c.kitty_wrappers), 2) + self.ae(c.kitty_wrappers[0].argv, argv[: len(c.kitty_wrappers[0].argv)]) + # Failures and invalid return values result in no prefix + from kitty import launch_wrapper + + errors = [] + with patch.object(launch_wrapper, 'log_error', lambda *a: errors.append(a)): + for bad in (ValueError('oops'), 'a string', ['ok', 1], 3): + c, exe, argv = self._fork(launch_request=req, user_func=self._recording(bad)) + self.ae(argv, ('/bin/prog', 'arg')) + self.ae(c.kitty_wrappers, ()) + for empty in (None, [], ()): + c, exe, argv = self._fork(launch_request=req, user_func=self._recording(empty)) + self.ae(argv, ('/bin/prog', 'arg')) + self.ae(len(errors), 4)