Skip to content

Commit

Permalink
build!(libtmux): 0.17 with API changes (#850)
Browse files Browse the repository at this point in the history
This includes libtmux 0.17's API overhaul from 
tmux-python/libtmux#426
  • Loading branch information
tony authored Dec 27, 2022
2 parents cf784c0 + 36e99bc commit 2d371ac
Show file tree
Hide file tree
Showing 13 changed files with 158 additions and 160 deletions.
7 changes: 7 additions & 0 deletions CHANGES
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,13 @@ $ pipx install --suffix=@next 'tmuxp' --pip-args '\--pre' --force

<!-- Maintainers, insert changes / features for the next release here -->

### Breaking change

- libtmux 0.16 -> 0.17 (#850)

This includes the API overhaul from
[libtmux#426](https://github.com/tmux-python/libtmux/pull/426).

### Developmental

- Tests: Stabilization fix for automatic rename test (#853)
Expand Down
4 changes: 0 additions & 4 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,6 @@ If you need an internal API stabilized please [file an issue](https://github.com
.. automethod:: tmuxp.util.oh_my_zsh_auto_title
```

```{eval-rst}
.. automethod:: tmuxp.util.raise_if_tmux_not_running
```

```{eval-rst}
.. automethod:: tmuxp.util.get_current_pane
```
Expand Down
6 changes: 3 additions & 3 deletions docs/quickstart.md
Original file line number Diff line number Diff line change
Expand Up @@ -145,10 +145,10 @@ AL - [Abstraction Layer][abstraction layer]
| {ref}`tmuxp python api <libtmux:api>` | {term}`tmux(1)` equivalent |
| ------------------------------------- | -------------------------- |
| {meth}`libtmux.Server.new_session` | `$ tmux new-session` |
| {meth}`libtmux.Server.list_sessions` | `$ tmux list-sessions` |
| {meth}`libtmux.Session.list_windows` | `$ tmux list-windows` |
| {meth}`libtmux.Server.sessions` | `$ tmux list-sessions` |
| {meth}`libtmux.Session.windows` | `$ tmux list-windows` |
| {meth}`libtmux.Session.new_window` | `$ tmux new-window` |
| {meth}`libtmux.Window.list_panes` | `$ tmux list-panes` |
| {meth}`libtmux.Window.panes` | `$ tmux list-panes` |
| {meth}`libtmux.Window.split_window` | `$ tmux split-window` |
| {meth}`libtmux.Pane.send_keys` | `$ tmux send-keys` |

Expand Down
8 changes: 4 additions & 4 deletions poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ tmuxp = 'tmuxp:cli.cli'

[tool.poetry.dependencies]
python = "^3.7"
libtmux = "~0.16.1"
libtmux = "0.17.0a1"
colorama = ">=0.3.9"
PyYAML = "^6.0"

Expand Down
4 changes: 2 additions & 2 deletions src/tmuxp/cli/freeze.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ class CLIFreezeNamespace(argparse.Namespace):

def session_completion(ctx, params, incomplete):
server = Server()
choices = [session.name for session in server.list_sessions()]
choices = [session.name for session in server.sessions]
return sorted(str(c) for c in choices if str(c).startswith(incomplete))


Expand Down Expand Up @@ -100,7 +100,7 @@ def command_freeze(

try:
if args.session_name:
session = server.find_where({"session_name": args.session_name})
session = server.sessions.get(session_name=args.session_name, default=None)
else:
session = util.get_session(server)

Expand Down
2 changes: 1 addition & 1 deletion src/tmuxp/cli/shell.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ def command_shell(
"""
server = Server(socket_name=args.socket_name, socket_path=args.socket_path)

util.raise_if_tmux_not_running(server=server)
server.raise_if_dead()

current_pane = util.get_current_pane(server=server)

Expand Down
80 changes: 38 additions & 42 deletions src/tmuxp/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
import sys

from libtmux._compat import console_to_str
from libtmux.exc import LibTmuxException

from . import exc

Expand Down Expand Up @@ -75,49 +74,31 @@ def oh_my_zsh_auto_title():
)


def raise_if_tmux_not_running(server):
"""Raise exception if not running. More descriptive error if no server found."""
try:
server.sessions
except LibTmuxException as e:
if any(
needle in str(e)
for needle in ["No such file or directory", "no server running on"]
):
raise LibTmuxException(
"no tmux session found. Start a tmux session and try again. \n"
"Original error: " + str(e)
)
else:
raise e


def get_current_pane(server):
"""Return Pane if one found in env"""
if os.getenv("TMUX_PANE") is not None:
try:
return [
p
for p in server._list_panes()
if p.get("pane_id") == os.getenv("TMUX_PANE")
][0]
return [p for p in server.panes if p.pane_id == os.getenv("TMUX_PANE")][0]
except IndexError:
pass


def get_session(server, session_name=None, current_pane=None):
if session_name:
session = server.find_where({"session_name": session_name})
elif current_pane is not None:
session = server.find_where({"session_id": current_pane["session_id"]})
else:
current_pane = get_current_pane(server)
if current_pane:
session = server.find_where({"session_id": current_pane["session_id"]})
try:
if session_name:
session = server.sessions.get(session_name=session_name)
elif current_pane is not None:
session = server.sessions.get(session_id=current_pane.session_id)
else:
session = server.list_sessions()[0]

if not session:
current_pane = get_current_pane(server)
if current_pane:
session = server.sessions.get(session_id=current_pane.session_id)
else:
session = server.sessions[0]
except Exception:
session = None

if session is None:
if session_name:
raise exc.TmuxpException("Session not found: %s" % session_name)
else:
Expand All @@ -127,26 +108,41 @@ def get_session(server, session_name=None, current_pane=None):


def get_window(session, window_name=None, current_pane=None):
if window_name:
window = session.find_where({"window_name": window_name})
if not window:
try:
if window_name:
window = session.windows.get(window_name=window_name)
elif current_pane is not None:
window = session.windows.get(window_id=current_pane.window_id)
else:
window = session.windows[0]
except Exception:
window = None

if window is None:
if window_name:
raise exc.TmuxpException("Window not found: %s" % window_name)
elif current_pane is not None:
window = session.find_where({"window_id": current_pane["window_id"]})
else:
window = session.list_windows()[0]
if current_pane:
raise exc.TmuxpException("Window not found: %s" % current_pane)
else:
raise exc.TmuxpException("Window not found")

return window


def get_pane(window, current_pane=None):
try:
if current_pane is not None:
pane = window.find_where({"pane_id": current_pane["pane_id"]}) # NOQA: F841
pane = window.panes.get(pane_id=current_pane.pane_id) # NOQA: F841
else:
pane = window.attached_pane # NOQA: F841
except exc.TmuxpException as e:
print(e)
return

if pane is None:
if current_pane:
raise exc.TmuxpException("Pane not found: %s" % current_pane)
else:
raise exc.TmuxpException("Pane not found")

return pane
42 changes: 23 additions & 19 deletions src/tmuxp/workspace/builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,15 +71,15 @@ class WorkspaceBuilder:
>>> new_session.name == 'sample workspace'
True
>>> len(new_session._windows)
>>> len(new_session.windows)
3
>>> sorted([window.name for window in new_session.windows])
['editor', 'logging', 'test']
**Existing session:**
>>> len(session._windows)
>>> len(session.windows)
1
>>> builder.build(session=session)
Expand All @@ -89,7 +89,7 @@ class WorkspaceBuilder:
>>> session.name == 'sample workspace'
False
>>> len(session._windows)
>>> len(session.windows)
3
>>> sorted([window.name for window in session.windows])
Expand Down Expand Up @@ -174,7 +174,10 @@ def session_exists(self, session_name=None):
if not exists:
return exists

self.session = self.server.find_where({"session_name": session_name})
try:
self.session = self.server.sessions.filter(session_name=session_name)[0]
except IndexError:
return False
return True

def build(self, session=None, append=False):
Expand Down Expand Up @@ -203,12 +206,17 @@ def build(self, session=None, append=False):
)

if self.server.has_session(self.sconf["session_name"]):
self.session = self.server.find_where(
{"session_name": self.sconf["session_name"]}
)
raise TmuxSessionExists(
"Session name %s is already running." % self.sconf["session_name"]
)
try:
self.session = self.server.sessions.filter(
session_name=self.sconf["session_name"]
)[0]

raise TmuxSessionExists(
"Session name %s is already running."
% self.sconf["session_name"]
)
except IndexError:
pass
else:
new_session_kwargs = {}
if "start_directory" in self.sconf:
Expand All @@ -226,7 +234,7 @@ def build(self, session=None, append=False):
self.session = session
self.server = session.server

self.server._list_sessions()
self.server.sessions
assert self.server.has_session(session.name)
assert session.id

Expand Down Expand Up @@ -378,16 +386,13 @@ def iter_create_windows(self, session, append=False):
session.attached_window.kill_window()

assert isinstance(w, Window)
session.server._update_windows()
if "options" in wconf and isinstance(wconf["options"], dict):
for key, val in wconf["options"].items():
w.set_window_option(key, val)

if "focus" in wconf and wconf["focus"]:
w.select_window()

session.server._update_windows()

yield w, wconf

def iter_create_panes(self, w, wconf):
Expand Down Expand Up @@ -421,7 +426,6 @@ def iter_create_panes(self, w, wconf):
else:

def get_pane_start_directory():

if "start_directory" in pconf:
return pconf["start_directory"]
elif "start_directory" in wconf:
Expand All @@ -430,7 +434,6 @@ def get_pane_start_directory():
return None

def get_pane_shell():

if "shell" in pconf:
return pconf["shell"]
elif "window_shell" in wconf:
Expand Down Expand Up @@ -486,7 +489,8 @@ def get_pane_shell():
time.sleep(sleep_after)

if "focus" in pconf and pconf["focus"]:
w.select_pane(p["pane_id"])
assert p.pane_id is not None
w.select_pane(p.pane_id)

w.server._update_panes()

Expand Down Expand Up @@ -519,8 +523,8 @@ def find_current_attached_session(self):
return next(
(
s
for s in self.server.list_sessions()
if s["session_id"] == current_active_pane["session_id"]
for s in self.server.sessions
if s.session_id == current_active_pane.session_id
),
None,
)
Expand Down
16 changes: 8 additions & 8 deletions src/tmuxp/workspace/freezer.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,36 +53,36 @@ def freeze(session):
dict
tmuxp compatible workspace
"""
sconf = {"session_name": session["session_name"], "windows": []}
sconf = {"session_name": session.session_name, "windows": []}

for w in session.windows:
wconf = {
"options": w.show_window_options(),
"window_name": w.name,
"layout": w.layout,
"layout": w.window_layout,
"panes": [],
}
if w.get("window_active", "0") == "1":
if getattr(w, "window_active", "0") == "1":
wconf["focus"] = "true"

# If all panes have same path, set 'start_directory' instead
# of using 'cd' shell commands.
def pane_has_same_path(p):
return w.panes[0].current_path == p.current_path
return w.panes[0].pane_current_path == p.pane_current_path

if all(pane_has_same_path(p) for p in w.panes):
wconf["start_directory"] = w.panes[0].current_path
wconf["start_directory"] = w.panes[0].pane_current_path

for p in w.panes:
pconf = {"shell_command": []}

if "start_directory" not in wconf:
pconf["shell_command"].append("cd " + p.current_path)
pconf["shell_command"].append("cd " + p.pane_current_path)

if p.get("pane_active", "0") == "1":
if getattr(p, "pane_active", "0") == "1":
pconf["focus"] = "true"

current_cmd = p.current_command
current_cmd = p.pane_current_command

def filter_interpretters_and_shells():
return current_cmd.startswith("-") or any(
Expand Down
Loading

0 comments on commit 2d371ac

Please sign in to comment.