Skip to content

tests,fix(cli): Fix loading of multiple workspace files #838

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Oct 29, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

from libtmux.test import namer
from tests.fixtures import utils as test_utils
from tmuxp.cli.utils import get_config_dir

if t.TYPE_CHECKING:
from libtmux.session import Session
Expand All @@ -40,6 +41,24 @@ def home_path_default(monkeypatch: pytest.MonkeyPatch, user_path: pathlib.Path)
monkeypatch.setenv("HOME", str(user_path))


@pytest.fixture
def tmuxp_configdir(user_path: pathlib.Path) -> pathlib.Path:
xdg_config_dir = user_path / ".config"
xdg_config_dir.mkdir(exist_ok=True)

tmuxp_configdir = xdg_config_dir / "tmuxp"
tmuxp_configdir.mkdir(exist_ok=True)
return tmuxp_configdir


@pytest.fixture
def tmuxp_configdir_default(
monkeypatch: pytest.MonkeyPatch, tmuxp_configdir: pathlib.Path
) -> None:
monkeypatch.setenv("TMUXP_CONFIGDIR", str(tmuxp_configdir))
assert get_config_dir() == str(tmuxp_configdir)


@pytest.fixture(scope="function")
def monkeypatch_plugin_test_packages(monkeypatch: pytest.MonkeyPatch) -> None:
paths = [
Expand Down
59 changes: 34 additions & 25 deletions src/tmuxp/cli/load.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
from libtmux.common import has_gte_version
from libtmux.server import Server
from libtmux.session import Session
from tmuxp.types import StrPath

from .. import config, config_reader, exc, log, util
from ..workspacebuilder import WorkspaceBuilder
Expand All @@ -29,13 +30,17 @@
)

if t.TYPE_CHECKING:
from typing_extensions import Literal, TypeAlias
from typing_extensions import Literal, NotRequired, TypeAlias, TypedDict

CLIColorsLiteral: TypeAlias = Literal[56, 88]

class OptionOverrides(TypedDict):
detached: NotRequired[bool]
new_session_name: NotRequired[t.Optional[str]]


class CLILoadNamespace(argparse.Namespace):
config_file: str
config_files: t.List[str]
socket_name: t.Optional[str]
socket_path: t.Optional[str]
tmux_config_file: t.Optional[str]
Expand Down Expand Up @@ -251,7 +256,7 @@ def _setup_plugins(builder: WorkspaceBuilder) -> Session:


def load_workspace(
config_file: t.Union[pathlib.Path, str],
config_file: StrPath,
socket_name: t.Optional[str] = None,
socket_path: None = None,
tmux_config_file: None = None,
Expand All @@ -266,8 +271,8 @@ def load_workspace(

Parameters
----------
config_file : str
absolute path to config file
config_file : list of str
paths or session names to workspace files
socket_name : str, optional
``tmux -L <socket-name>``
socket_path: str, optional
Expand Down Expand Up @@ -356,7 +361,7 @@ def load_workspace(
Accessed April 8th, 2018.
"""
# get the canonical path, eliminating any symlinks
if isinstance(config_file, str):
if isinstance(config_file, (str, os.PathLike)):
config_file = pathlib.Path(config_file)

tmuxp_echo(
Expand Down Expand Up @@ -486,8 +491,9 @@ def config_file_completion(ctx, params, incomplete):


def create_load_subparser(parser: argparse.ArgumentParser) -> argparse.ArgumentParser:
config_file = parser.add_argument(
"config_file",
config_files = parser.add_argument(
"config_files",
nargs="+",
metavar="config-file",
help="filepath to session or filename of session if in tmuxp config directory",
)
Expand Down Expand Up @@ -568,7 +574,7 @@ def create_load_subparser(parser: argparse.ArgumentParser) -> argparse.ArgumentP
try:
import shtab

config_file.complete = shtab.FILE # type: ignore
config_files.complete = shtab.FILE # type: ignore
tmux_config_file.complete = shtab.FILE # type: ignore
log_file.complete = shtab.FILE # type: ignore
except ImportError:
Expand Down Expand Up @@ -623,27 +629,30 @@ def command_load(
"append": args.append,
}

if args.config_file is None:
if args.config_files is None or len(args.config_files) == 0:
tmuxp_echo("Enter at least one config")
if parser is not None:
parser.print_help()
sys.exit()
return

config_file = scan_config(args.config_file, config_dir=get_config_dir())
last_idx = len(args.config_files) - 1
original_detached_option = tmux_options.pop("detached")
original_new_session_name = tmux_options.pop("new_session_name")

if isinstance(config_file, str):
load_workspace(config_file, **tmux_options)
elif isinstance(config_file, tuple):
config = list(config_file)
# Load each configuration but the last to the background
for cfg in config[:-1]:
opt = tmux_options.copy()
opt.update({"detached": True, "new_session_name": None})
load_workspace(cfg, **opt)
for idx, config_file in enumerate(args.config_files):
config_file = scan_config(config_file, config_dir=get_config_dir())

# todo: obey the -d in the cli args only if user specifies
load_workspace(config_file[-1], **tmux_options)
else:
raise NotImplementedError(
f"config {type(config_file)} with {config_file} not valid"
detached = original_detached_option
new_session_name = original_new_session_name

if last_idx > 0 and idx < last_idx:
detached = True
new_session_name = None

load_workspace(
config_file,
detached=detached,
new_session_name=new_session_name,
**tmux_options,
)
14 changes: 14 additions & 0 deletions src/tmuxp/types.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
"""Internal :term:`type annotations <annotation>`

Notes
-----

:class:`StrPath` and :class:`StrOrBytesPath` is based on `typeshed's`_.

.. _typeshed's: https://github.com/python/typeshed/blob/9687d5/stdlib/_typeshed/__init__.pyi#L98
""" # NOQA E501
from os import PathLike
from typing import Union

StrPath = Union[str, "PathLike[str]"]
""":class:`os.PathLike` or :class:`str`"""
158 changes: 158 additions & 0 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -433,6 +433,164 @@ def test_load_symlinked_workspace(
assert pane.current_path == str(realtemp)


if t.TYPE_CHECKING:
from typing_extensions import TypeAlias

ExpectedOutput: TypeAlias = t.Optional[t.Union[str, t.List[str]]]


class CLILoadFixture(t.NamedTuple):
test_id: str
cli_args: t.List[t.Union[str, t.List[str]]]
config_paths: t.List[str]
session_names: t.List[str]
expected_exit_code: int
expected_in_out: "ExpectedOutput" = None
expected_not_in_out: "ExpectedOutput" = None
expected_in_err: "ExpectedOutput" = None
expected_not_in_err: "ExpectedOutput" = None


TEST_LOAD_FIXTURES = [
CLILoadFixture(
test_id="dir-relative-dot-samedir",
cli_args=["load", "."],
config_paths=["{tmp_path}/.tmuxp.yaml"],
session_names=["my_config"],
expected_exit_code=0,
expected_in_out=None,
expected_not_in_out=None,
),
CLILoadFixture(
test_id="dir-relative-dot-slash-samedir",
cli_args=["load", "./"],
config_paths=["{tmp_path}/.tmuxp.yaml"],
session_names=["my_config"],
expected_exit_code=0,
expected_in_out=None,
expected_not_in_out=None,
),
CLILoadFixture(
test_id="dir-relative-file-samedir",
cli_args=["load", "./.tmuxp.yaml"],
config_paths=["{tmp_path}/.tmuxp.yaml"],
session_names=["my_config"],
expected_exit_code=0,
expected_in_out=None,
expected_not_in_out=None,
),
CLILoadFixture(
test_id="filename-relative-file-samedir",
cli_args=["load", "./my_config.yaml"],
config_paths=["{tmp_path}/my_config.yaml"],
session_names=["my_config"],
expected_exit_code=0,
expected_in_out=None,
expected_not_in_out=None,
),
CLILoadFixture(
test_id="configdir-session-name",
cli_args=["load", "my_config"],
config_paths=["{TMUXP_CONFIGDIR}/my_config.yaml"],
session_names=["my_config"],
expected_exit_code=0,
expected_in_out=None,
expected_not_in_out=None,
),
CLILoadFixture(
test_id="configdir-absolute",
cli_args=["load", "~/.config/tmuxp/my_config.yaml"],
config_paths=["{TMUXP_CONFIGDIR}/my_config.yaml"],
session_names=["my_config"],
expected_exit_code=0,
expected_in_out=None,
expected_not_in_out=None,
),
#
# Multiple configs
#
CLILoadFixture(
test_id="configdir-session-name-double",
cli_args=["load", "my_config", "second_config"],
config_paths=[
"{TMUXP_CONFIGDIR}/my_config.yaml",
"{TMUXP_CONFIGDIR}/second_config.yaml",
],
session_names=["my_config", "second_config"],
expected_exit_code=0,
expected_in_out=None,
expected_not_in_out=None,
),
]


@pytest.mark.parametrize(
list(CLILoadFixture._fields),
TEST_LOAD_FIXTURES,
ids=[test.test_id for test in TEST_LOAD_FIXTURES],
)
@pytest.mark.usefixtures("tmuxp_configdir_default")
def test_load(
tmp_path: pathlib.Path,
tmuxp_configdir: pathlib.Path,
server: "Server",
session: Session,
capsys: pytest.CaptureFixture,
monkeypatch: pytest.MonkeyPatch,
test_id: str,
cli_args: t.List[str],
config_paths: t.List[str],
session_names: t.List[str],
expected_exit_code: int,
expected_in_out: "ExpectedOutput",
expected_not_in_out: "ExpectedOutput",
expected_in_err: "ExpectedOutput",
expected_not_in_err: "ExpectedOutput",
) -> None:
assert server.socket_name is not None

monkeypatch.chdir(tmp_path)
for session_name, config_path in zip(session_names, config_paths):
tmuxp_config = pathlib.Path(
config_path.format(tmp_path=tmp_path, TMUXP_CONFIGDIR=tmuxp_configdir)
)
tmuxp_config.write_text(
"""
session_name: {session_name}
windows:
- window_name: test
panes:
-
""".format(
session_name=session_name
),
encoding="utf-8",
)

try:
cli.cli([*cli_args, "-d", "-L", server.socket_name, "-y"])
except SystemExit:
pass

result = capsys.readouterr()
output = "".join(list(result.out))

if expected_in_out is not None:
if isinstance(expected_in_out, str):
expected_in_out = [expected_in_out]
for needle in expected_in_out:
assert needle in output

if expected_not_in_out is not None:
if isinstance(expected_not_in_out, str):
expected_not_in_out = [expected_not_in_out]
for needle in expected_not_in_out:
assert needle not in output

for session_name in session_names:
assert server.has_session(session_name)


def test_regression_00132_session_name_with_dots(
tmp_path: pathlib.Path,
server: "Server",
Expand Down