-
Notifications
You must be signed in to change notification settings - Fork 126
Expand file tree
/
Copy pathenv.py
More file actions
288 lines (221 loc) · 9.23 KB
/
Copy pathenv.py
File metadata and controls
288 lines (221 loc) · 9.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
"""Readers for the tmux variables libtmux takes its bearings from.
libtmux._internal.env
~~~~~~~~~~~~~~~~~~~~~
tmux exports two variables into the child environment of every pane it spawns:
``TMUX``
``"<socket_path>,<server_pid>,<session_id>"``. The session id is spelled
*bare* -- ``47``, where libtmux spells the same session ``$47``.
``TMUX_PANE``
``"%N"`` -- the pane's id.
tmux also exports ``TMUX`` to the job children it spawns for ``run-shell`` and
``#()``, and those never get ``TMUX_PANE``. A ``#()`` job carries no session at
all, and its ``TMUX`` says so with a session id of ``-1``. So a process holding
a pane id always has a real session id beside it.
Both are frozen at spawn time and tmux never revises them. The moment a pane's
window is moved or linked into another session, the session id baked into
``TMUX`` is stale, while ``TMUX_PANE`` stays valid for the life of the pane.
libtmux therefore reads *only* the socket path out of ``TMUX`` and asks tmux
itself -- targeting ``TMUX_PANE`` -- for the pane's window and session. See
:meth:`libtmux.Pane.from_env`.
A third variable, ``TMUX_TMPDIR``, is read *by* tmux rather than exported by
it: it picks the directory tmux keeps its sockets in. See
:func:`resolve_socket_path`.
"""
from __future__ import annotations
import os
import pathlib
import typing as t
from libtmux import exc
TMUX: t.Final = "TMUX"
"""Environment variable tmux exports with ``socket_path,server_pid,session_id``."""
TMUX_PANE: t.Final = "TMUX_PANE"
"""Environment variable tmux exports with the pane's id, e.g. ``%3``."""
TMUX_TMPDIR: t.Final = "TMUX_TMPDIR"
"""Environment variable naming the directory tmux keeps its sockets in."""
DEFAULT_SOCKET_DIR: t.Final = "/tmp"
"""Socket directory tmux falls back to when ``$TMUX_TMPDIR`` is unset."""
DEFAULT_SOCKET_NAME: t.Final = "default"
"""Socket name tmux uses when neither ``-L`` nor ``-S`` was given."""
def resolve_env(env: t.Mapping[str, str] | None = None) -> t.Mapping[str, str]:
"""Return *env*, defaulting to the live process environment.
Parameters
----------
env : :class:`typing.Mapping`, optional
Environment to read. Defaults to :data:`os.environ`.
Returns
-------
:class:`typing.Mapping`
The mapping to read tmux variables from.
Examples
--------
>>> from libtmux._internal.env import resolve_env
>>> resolve_env({"TMUX_PANE": "%1"})
{'TMUX_PANE': '%1'}
>>> resolve_env() is os.environ
True
"""
return os.environ if env is None else env
def resolve_socket_path(
socket_name: str | None = None,
env: t.Mapping[str, str] | None = None,
) -> pathlib.Path:
"""Resolve the socket path tmux uses for *socket_name*.
tmux keeps its sockets in ``tmux-<euid>`` under ``$TMUX_TMPDIR``, falling
back to ``/tmp`` when that is unset or empty. ``$TMPDIR`` is deliberately
not consulted -- tmux does not consult it either. The socket directory is
resolved through symlinks, as tmux resolves it before binding, so a
symlinked ``$TMUX_TMPDIR`` yields the path tmux itself reports.
The path is *computed*, not observed: it says where tmux would put the
socket, not that a daemon is listening there. Code holding a live
:class:`~libtmux.Server` should ask tmux instead, with the
``#{socket_path}`` format.
Parameters
----------
socket_name : str, optional
Socket name, as passed to tmux's ``-L``. Defaults to tmux's own
default, ``"default"``.
env : :class:`typing.Mapping`, optional
Environment to read. Defaults to :data:`os.environ`.
Returns
-------
:class:`pathlib.Path`
Path tmux resolves the socket to.
Examples
--------
>>> from libtmux._internal.env import resolve_socket_path
>>> resolve_socket_path(env={})
PosixPath('/tmp/tmux-.../default')
>>> resolve_socket_path("mysocket", env={"TMUX_TMPDIR": "/run/user/1000"})
PosixPath('/run/user/1000/tmux-.../mysocket')
``$TMPDIR`` is not a socket directory, so it changes nothing:
>>> resolve_socket_path(env={"TMPDIR": "/var/folders/xy"})
PosixPath('/tmp/tmux-.../default')
"""
tmpdir = resolve_env(env).get(TMUX_TMPDIR) or DEFAULT_SOCKET_DIR
return (
pathlib.Path(tmpdir).resolve()
/ f"tmux-{os.geteuid()}"
/ (socket_name or DEFAULT_SOCKET_NAME)
)
def socket_path_from_env(env: t.Mapping[str, str] | None = None) -> str:
"""Return the tmux socket path recorded in ``$TMUX``.
``$TMUX`` is ``"<socket_path>,<server_pid>,<session_id>"``. The pid and
session id are integers, so any comma in the value belongs to the socket
path -- split from the *right*.
The pid and session id are deliberately discarded: both are frozen at pane
spawn, and the session id goes stale as soon as the pane's window is moved
between sessions.
Parameters
----------
env : :class:`typing.Mapping`, optional
Environment to read. Defaults to :data:`os.environ`.
Returns
-------
str
Path of the tmux server's socket.
Raises
------
:exc:`~libtmux.exc.NotInsideTmux`
When ``$TMUX`` is unset, empty, or not shaped like tmux's triple.
Examples
--------
>>> from libtmux._internal.env import socket_path_from_env
>>> socket_path_from_env({"TMUX": "/tmp/tmux-1000/default,84215,0"})
'/tmp/tmux-1000/default'
A comma in the socket path is safe, because the split runs from the right:
>>> socket_path_from_env({"TMUX": "/tmp/od,d/sock,84215,3"})
'/tmp/od,d/sock'
Outside tmux there is nothing to read:
>>> socket_path_from_env({})
Traceback (most recent call last):
...
libtmux.exc.NotInsideTmux: Not inside a tmux pane: $TMUX is unset or empty
"""
raw = resolve_env(env).get(TMUX, "")
if not raw:
raise exc.NotInsideTmux(TMUX)
parts = raw.rsplit(",", 2)
if len(parts) != 3 or not parts[0]:
raise exc.NotInsideTmux(
TMUX,
reason="not '<socket_path>,<server_pid>,<session_id>'",
)
return parts[0]
def resolve_ambient_socket_path(env: t.Mapping[str, str] | None = None) -> pathlib.Path:
"""Resolve the socket a *bare* tmux invocation talks to, in tmux's own order.
A tmux client given no ``-L`` or ``-S`` prefers ``$TMUX`` -- the socket of
the pane it is running inside -- and only falls back to computing a path
under ``$TMUX_TMPDIR`` when there is no pane. Measured against tmux 3.7b: a
bare client with ``$TMUX`` set connects even when ``$TMUX_TMPDIR`` names a
directory far too deep to bind, because it never looks there.
That order only holds for the bare client. Passing ``-L`` sends tmux to
``$TMUX_TMPDIR`` regardless of ``$TMUX``, so a named socket resolves through
:func:`resolve_socket_path` instead.
Parameters
----------
env : :class:`typing.Mapping`, optional
Environment to read. Defaults to :data:`os.environ`.
Returns
-------
:class:`pathlib.Path`
Socket path a bare tmux client would use.
Examples
--------
>>> from libtmux._internal.env import resolve_ambient_socket_path
Inside a pane, ``$TMUX`` names the socket outright:
>>> resolve_ambient_socket_path({"TMUX": "/tmp/tmux-1000/default,8421,0"})
PosixPath('/tmp/tmux-1000/default')
``$TMUX_TMPDIR`` is not consulted when there is a pane to inherit from:
>>> resolve_ambient_socket_path(
... {"TMUX": "/tmp/sock,8421,0", "TMUX_TMPDIR": "/nowhere"}
... )
PosixPath('/tmp/sock')
Outside tmux it falls back to the computed path:
>>> resolve_ambient_socket_path({})
PosixPath('/tmp/tmux-.../default')
"""
try:
return pathlib.Path(socket_path_from_env(env))
except exc.NotInsideTmux:
return resolve_socket_path(env=env)
def pane_id_from_env(env: t.Mapping[str, str] | None = None) -> str:
"""Return the pane id recorded in ``$TMUX_PANE``.
The ``%`` sigil is load-bearing: libtmux passes this id straight to tmux as
a ``-t`` target, and tmux's ``cmd_find`` routes a target to its pane slot
*by sigil*. A sigil-less value would be matched against session names
instead, silently resolving to the wrong object.
Parameters
----------
env : :class:`typing.Mapping`, optional
Environment to read. Defaults to :data:`os.environ`.
Returns
-------
str
The pane id, e.g. ``"%3"``.
Raises
------
:exc:`~libtmux.exc.NotInsideTmux`
When ``$TMUX_PANE`` is unset, empty, or is not a ``%``-prefixed id.
Examples
--------
>>> from libtmux._internal.env import pane_id_from_env
>>> pane_id_from_env({"TMUX_PANE": "%3"})
'%3'
>>> pane_id_from_env({})
Traceback (most recent call last):
...
libtmux.exc.NotInsideTmux: Not inside a tmux pane: $TMUX_PANE is unset or empty
>>> pane_id_from_env({"TMUX_PANE": "3"})
Traceback (most recent call last):
...
libtmux.exc.NotInsideTmux: Not inside a tmux pane: $TMUX_PANE is not a pane id...
"""
pane_id = resolve_env(env).get(TMUX_PANE, "")
if not pane_id:
raise exc.NotInsideTmux(TMUX_PANE)
if not pane_id.startswith("%"):
raise exc.NotInsideTmux(
TMUX_PANE,
reason=f"not a pane id (expected '%N', got {pane_id!r})",
)
return pane_id