libtmux 0.1.1 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -30,79 +30,121 @@ module LibTmux
30
30
  # The methods fall into the groups below. A {Session}, {Window}, or {Pane}
31
31
  # carries the operations on that one thing.
32
32
  #
33
- # **Connecting.** {#initialize Server.new} and {Server.open} bind an endpoint
34
- # that already exists; {Server.open} with a block closes the server when the
35
- # block ends. Given no `endpoint:`, `socket_path:` or `socket_name:`, they
36
- # bind the socket {Endpoint#initialize Endpoint.new} picks from
37
- # `LIBTMUX_SOCKET_PATH`, `LIBTMUX_SOCKET`, `TMUX` and tmux's default socket,
38
- # in that order. {Server.start} starts a private daemon instead, creates no
39
- # session, and owns the daemon's exit. {#endpoint} answers the {Endpoint}
40
- # and {#owned?} says whether this server started its daemon. {#diagnostics}
41
- # reports the request and control slots in use, and the limits. {#close}
42
- # retires the server's clients; on an owned server it also stops the daemon.
43
- # {#open_control} opens a {ControlConnection} to a session.
33
+ # **Connecting.** Binding an endpoint that already exists takes the
34
+ # constructor or the open class method, and open with a block closes the
35
+ # server when the block ends. Given no `endpoint:`, `socket_path:` or
36
+ # `socket_name:`, both bind the socket {Endpoint#initialize Endpoint.new}
37
+ # picks from `LIBTMUX_SOCKET_PATH`, `LIBTMUX_SOCKET`, `TMUX` and tmux's
38
+ # default socket, in that order. Starting a private daemon instead creates no
39
+ # session, and the started server owns the daemon's exit. A server answers its
40
+ # {Endpoint} and whether it started its daemon, and reports the request and
41
+ # control slots in use, and the limits. Closing retires the server's clients;
42
+ # on an owned server it also stops the daemon. Open a {ControlConnection} to a
43
+ # session.
44
44
  #
45
- # **Finding one thing.** {#session}, {#window}, {#pane}, and {#window_link}
46
- # wrap an {EntityRef} in a handle without running a command. Take the ref
47
- # from a handle or a snapshot record. A ref of the wrong kind raises
48
- # {TargetNotFoundError}; one whose entity has gone fails at its first
49
- # command.
45
+ # - Bind an endpoint: {#initialize Server.new}, {Server.open}
46
+ # - Start a private daemon: {Server.start}
47
+ # - Read the endpoint: {#endpoint}
48
+ # - Ask whether it started the daemon: {#owned?}
49
+ # - Slots in use and the limits: {#diagnostics}
50
+ # - Retire the clients: {#close}
51
+ # - Open a control connection: {#open_control}
50
52
  #
51
- # **Listing everything.** {#list_sessions}, {#list_windows}, and
52
- # {#list_panes} answer frozen arrays of handles in numeric ID order, and
53
- # {#list_window_links} answers every {WindowLink}. {#list_clients} answers
54
- # one hash per client. {#snapshot} captures the session, window, and pane
55
- # tree, and clients with `clients: true`, as one validated {Snapshot}.
53
+ # **Finding one thing.** Each lookup wraps an {EntityRef} in a handle without
54
+ # running a command. Take the ref from a handle or a snapshot record. A ref of
55
+ # the wrong kind raises {TargetNotFoundError}; one whose entity has gone fails
56
+ # at its first command.
56
57
  #
57
- # **Querying things and getting around.** {#search_panes} filters the panes
58
- # of a snapshot with `where:`, a hash of criteria or a {FilterExpr}, and
59
- # answers a {Selection}; {#explain_panes} answers the plan for a query
60
- # without running tmux. A {Selection} narrows with {Selection#where},
61
- # {Selection#select}, {Selection#filter}, and {Selection#reject}, tests with
62
- # {Selection#exists?}, and takes a single match with {Selection#one}, which
63
- # raises {NoMatchError} or {MultipleMatchesError} otherwise, or
64
- # {Selection#one_or_nil}. Build and compose criteria with
65
- # {FilterExpr.build}, {FilterExpr#and}, {FilterExpr#or}, {FilterExpr#not},
66
- # and {FilterExpr.from_json}.
58
+ # - Handles: {#session}, {#window}, {#pane}, {#window_link}
67
59
  #
68
- # A {Snapshot} answers relational questions without another command:
69
- # {Snapshot#sessions}, {Snapshot#windows}, {Snapshot#panes}, and
70
- # {Snapshot#clients}. Its records follow relations by name: a
71
- # {SessionSnapshot} reaches `windows`, `panes`, and `current_window`, a
72
- # {WindowSnapshot} reaches `panes` and `active_pane`, and a {PaneSnapshot}
73
- # reaches its `window`. {Entity#snapshot} reads one handle back as a record,
74
- # and {CapturedRecord#ref} with {#session}, {#window}, or {#pane} turns a
75
- # record into a handle. Live handles go down one command at a time with
76
- # {Session#list_windows}, {Session#list_panes}, and {Window#list_panes}, and
77
- # back up with {Entity#server}.
60
+ # **Listing everything.** Listing sessions, windows, or panes answers frozen
61
+ # arrays of handles in numeric ID order, and listing window links answers
62
+ # every {WindowLink}. Listing clients answers one hash per client. Taking a
63
+ # snapshot captures the session, window, and pane tree, and clients with
64
+ # `clients: true`, as one validated {Snapshot}.
78
65
  #
79
- # **Changing things.** {#new_session} starts a detached session running
80
- # `command:`, an argv array rather than a shell string, and answers the
81
- # {Session} or, with `receipt: true`, a {CreationReceipt}. {#kill} stops the
82
- # tmux server, which {#close} does only for an owned server.
83
- # {#switch_client} points the client named by `client:` at a session.
66
+ # - Handles: {#list_sessions}, {#list_windows}, {#list_panes}
67
+ # - Window links: {#list_window_links}
68
+ # - Clients: {#list_clients}
69
+ # - One snapshot: {#snapshot}
84
70
  #
85
- # **Options and hooks.** {#options} answers {Options} at server scope, or at
86
- # the global session or window scope. {#hooks} answers {Hooks} at the global
87
- # session or window scope. {#environment}, {#set_environment}, and
88
- # {#unset_environment} read, set, and unset one variable in the server's
89
- # global environment.
71
+ # **Querying things and getting around.** A pane search filters the panes of a
72
+ # snapshot with `where:`, a hash of criteria or a {FilterExpr}, and answers a
73
+ # {Selection}; explaining a search answers the plan for a query without
74
+ # running tmux. A {Selection} narrows, tests whether anything matches, and
75
+ # takes a single match, raising {NoMatchError} or {MultipleMatchesError}
76
+ # otherwise, or takes one or nil. Build and compose criteria with
77
+ # {FilterExpr}. A {Snapshot} answers relational questions without another
78
+ # command. Its records follow relations by name: a {SessionSnapshot} reaches
79
+ # `windows`, `panes`, and `current_window`, a {WindowSnapshot} reaches `panes`
80
+ # and `active_pane`, and a {PaneSnapshot} reaches its `window`. A handle reads
81
+ # back as a record, and a record turns into a handle through its ref and the
82
+ # server's lookups. Live handles go down one command at a time and back up
83
+ # through the server.
90
84
  #
91
- # **Everything else tmux keeps.** Paste buffers: {#list_buffers},
92
- # {#read_buffer}, {#write_buffer}, and {#delete_buffer}. {#source_file}
93
- # loads a configuration file. {#display} expands a tmux format; the argument
94
- # is a format, not literal text. {#wait_for} waits on, signals, locks, or
95
- # unlocks a channel, as `action:` says.
85
+ # - Search the panes of a snapshot: {#search_panes}
86
+ # - Explain a search without running tmux: {#explain_panes}
87
+ # - Narrow: {Selection#where}, {Selection#select}, {Selection#filter},
88
+ # {Selection#reject}
89
+ # - Test: {Selection#exists?}
90
+ # - Take one: {Selection#one}
91
+ # - Take one or nil: {Selection#one_or_nil}
92
+ # - Build criteria: {FilterExpr.build}, {FilterExpr.from_json}
93
+ # - Compose criteria: {FilterExpr#and}, {FilterExpr#or}, {FilterExpr#not}
94
+ # - Read a snapshot's records: {Snapshot#sessions}, {Snapshot#windows},
95
+ # {Snapshot#panes}, {Snapshot#clients}
96
+ # - Read a handle back as a record: {Entity#snapshot}
97
+ # - Turn a record into a handle: {CapturedRecord#ref}, {#session}, {#window},
98
+ # {#pane}
99
+ # - Down: {Session#list_windows}, {Session#list_panes}, {Window#list_panes}
100
+ # - Up: {Entity#server}
96
101
  #
97
- # **Things that need a terminal.** {#attach} runs an interactive client on a
102
+ # **Changing things.** A new session starts detached. Omit `name:` for a tmux
103
+ # name and `command:` for its default command or shell. Supply an argv
104
+ # array to run a particular program. The call returns the
105
+ # {Session} or, with `receipt: true`, a {CreationReceipt}. Kill stops the tmux
106
+ # server, which closing does only for an owned server. Switching a client
107
+ # points the client named by `client:` at a session.
108
+ #
109
+ # - Create a session: {#new_session}
110
+ # - Stop the tmux server: {#kill}
111
+ # - Point a client at a session: {#switch_client}
112
+ #
113
+ # **Options and hooks.** Ask for {Options} at server scope, or at the global
114
+ # session or window scope, and for {Hooks} at the global session or window
115
+ # scope. Read, set, and unset one variable in the server's global environment.
116
+ #
117
+ # - Options: {#options}
118
+ # - Hooks: {#hooks}
119
+ # - Read a variable: {#environment}
120
+ # - Set a variable: {#set_environment}
121
+ # - Unset a variable: {#unset_environment}
122
+ #
123
+ # **Everything else tmux keeps.** List, read, write, and delete paste buffers.
124
+ # Load a configuration file. Display expands a tmux format; the argument is a
125
+ # format, not literal text. Wait on, signal, lock, or unlock a channel, as
126
+ # `action:` says.
127
+ #
128
+ # - Paste buffers: {#list_buffers}, {#read_buffer}, {#write_buffer},
129
+ # {#delete_buffer}
130
+ # - Load a configuration file: {#source_file}
131
+ # - Expand a format: {#display}
132
+ # - Wait on a channel: {#wait_for}
133
+ #
134
+ # **Things that need a terminal.** Attaching runs an interactive client on a
98
135
  # TTY the caller supplies and keeps, blocks until that client exits, and
99
- # answers a {TerminalResult}. Cancelling detaches the client and does not
100
- # stop pane commands.
136
+ # answers a {TerminalResult}. Cancelling detaches the client and does not stop
137
+ # pane commands.
138
+ #
139
+ # - Attach a client: {#attach}
101
140
  #
102
- # Anything else tmux can do is reachable through {#run}, which runs one
103
- # command from an argv array and keeps tmux's separators and format
104
- # semantics, or {#run_group}, which runs several in one tmux invocation. A
105
- # {GroupResult} cannot attribute the client's final status to a single step.
141
+ # **Running a command.** Anything else tmux can do is reachable by running one
142
+ # command, which takes an argv array and keeps tmux's separators and format
143
+ # semantics, or by running several in one tmux invocation. A {GroupResult}
144
+ # cannot attribute the client's final status to a single step.
145
+ #
146
+ # - Run one command: {#run}
147
+ # - Run several in one invocation: {#run_group}
106
148
  class Server
107
149
  attr_reader :endpoint
108
150
 
@@ -171,10 +213,12 @@ module LibTmux
171
213
  @executor = Internal::ProcessExecutor.new
172
214
  @pin = Internal::SocketIdentity.new(@endpoint)
173
215
  begin
174
- @release = Internal::TmuxVersion.connected(@pin.command_prefix) { |argv| @executor.run(argv, timeout: version_timeout, discard_stdout: true) }
216
+ @release = Internal::TmuxVersion.connected(@pin.command_prefix) do |argv|
217
+ @executor.run(argv, **version_probe_options(version_timeout), discard_stdout: true)
218
+ end
175
219
  @pin.record_release(@release)
176
220
  argv, marker = Internal::TmuxVersion.fence_check_argv
177
- Internal::TmuxVersion.verify_fence(@executor.run(@pin.command_prefix + argv, timeout: version_timeout), marker)
221
+ Internal::TmuxVersion.verify_fence(@executor.run(@pin.command_prefix + argv, **version_probe_options(version_timeout)), marker)
178
222
  rescue Exception
179
223
  @pin.close
180
224
  raise
@@ -191,6 +235,16 @@ module LibTmux
191
235
  Internal::Capabilities.capability("control-mode").available?(@release)
192
236
  end
193
237
 
238
+ # Read immutable feature and workaround decisions from the bound daemon.
239
+ # This bounded request fires no user hook and never refreshes the server's
240
+ # original version fence. Closed or unavailable servers raise instead of
241
+ # reporting cached support. Async facades use their fiber-aware dispatch.
242
+ def capabilities(timeout: 5.0, cancel: nil)
243
+ identity = bound_daemon_identity(timeout: timeout, cancel: cancel)
244
+ Capabilities.__send__(:new, binding_key: @pin.key, pid: identity.fetch(:pid),
245
+ start_time: identity.fetch(:start_time), release: @release)
246
+ end
247
+
194
248
  # Raw tmux arguments retain tmux's separators and format semantics.
195
249
  def run(argv, input: "".b, timeout: 5.0, cancel: nil)
196
250
  dispatch(argv, input: input, timeout: timeout, cancel: cancel)
@@ -249,9 +303,17 @@ module LibTmux
249
303
  execute_typed(["kill-server"], timeout: timeout, cancel: cancel)
250
304
  end
251
305
 
252
- def new_session(name:, command:, width: nil, height: nil, window_name: nil, cwd: nil, environment: {}, receipt: false, timeout: 5.0, cancel: nil)
306
+ # Create a session and return its handle, or its creation receipt.
307
+ # tmux through 3.6b replaces `:` and `.` in session names with `_`, so
308
+ # different requests can collide. Exact 3.7 refuses both characters
309
+ # before dispatch. tmux 3.7a through 3.8 preserve them.
310
+ # Read `session.snapshot.name` for the effective name and retain
311
+ # `session.ref` for subsequent targeting by ID.
312
+ # @raise [UnsupportedFeatureError] if exact tmux 3.7 refuses punctuation
313
+ def new_session(name: nil, command: nil, width: nil, height: nil, window_name: nil, cwd: nil, environment: {}, receipt: false, timeout: 5.0, cancel: nil)
253
314
  budget = operation_budget(timeout, cancel)
254
- arguments = ["new-session", "-d", "-P", "-F", creation_format(:session, receipt), "-s", literal_name(name)]
315
+ arguments = ["new-session", "-d", "-P", "-F", creation_format(:session, receipt)]
316
+ arguments.concat(["-s", literal_name(name)]) unless name.nil?
255
317
  arguments.concat(["-n", literal_name(window_name)]) if window_name
256
318
  {"-x" => width, "-y" => height}.each do |flag, value|
257
319
  next if value.nil?
@@ -260,7 +322,7 @@ module LibTmux
260
322
  arguments.concat([flag, value.to_s])
261
323
  end
262
324
  arguments.concat(creation_options(cwd: cwd, environment: environment))
263
- create_entity(:session, arguments + ["--"] + pane_command(command), receipt: receipt, **budget.options)
325
+ create_entity(:session, arguments + creation_command(command), receipt: receipt, **budget.options)
264
326
  end
265
327
 
266
328
  def list_sessions(timeout: 5.0, cancel: nil)
@@ -302,7 +364,7 @@ module LibTmux
302
364
  if @controls.length >= @max_controls
303
365
  raise CapacityError.new("server control capacity is exhausted", phase: :admission)
304
366
  end
305
- connection = ControlConnection.new(binding: @pin, session_id: session_id, **options)
367
+ connection = ControlConnection.__send__(:new, binding: @pin, session_id: session_id, **options)
306
368
  @controls << connection
307
369
  end
308
370
  if block_given?
@@ -350,6 +412,10 @@ module LibTmux
350
412
 
351
413
  private
352
414
 
415
+ def version_probe_options(timeout)
416
+ {timeout: timeout}
417
+ end
418
+
353
419
  class OperationBudget
354
420
  def initialize(timeout, cancel, clock)
355
421
  raise ArgumentError, "timeout must be finite" unless timeout.is_a?(Numeric) && timeout.finite?
@@ -375,6 +441,11 @@ module LibTmux
375
441
  end
376
442
  private_constant :OperationBudget
377
443
 
444
+ def self.operation_budget(timeout, cancel)
445
+ OperationBudget.new(timeout, cancel, -> { Process.clock_gettime(Process::CLOCK_MONOTONIC) })
446
+ end
447
+ private_class_method :operation_budget
448
+
378
449
  def operation_budget(timeout, cancel)
379
450
  OperationBudget.new(timeout, cancel, method(:monotonic))
380
451
  end
@@ -506,8 +577,19 @@ module LibTmux
506
577
  end
507
578
  end
508
579
 
580
+ def bound_daemon_identity(timeout:, cancel:)
581
+ arguments, marker = Internal::TmuxVersion.daemon_identity_argv
582
+ result = dispatch(arguments, timeout: timeout, cancel: cancel)
583
+ identity = Internal::TmuxVersion.parse_daemon_identity(result, marker)
584
+ unless identity.fetch(:version) == @release.text
585
+ raise ProtocolError.new("tmux did not report the bound daemon identity", delivery: :observed, phase: :decode)
586
+ end
587
+
588
+ identity
589
+ end
590
+
509
591
  # Library operations that repair exact tmux 3.7's break-pane say so here.
510
- def dispatch(argv, input: "".b, timeout: 5.0, cancel: nil, repaired_break: false)
592
+ def dispatch(argv, input: "".b, timeout: 5.0, cancel: nil, repaired_break: false, stdout_tail: nil)
511
593
  ensure_owner
512
594
  started = monotonic
513
595
  validate_argv(argv)
@@ -517,15 +599,25 @@ module LibTmux
517
599
  perform_request(cancel: cancel) do |view|
518
600
  fence, marker = Internal::TmuxVersion.fence(@release)
519
601
  result = @executor.run(@pin.command_prefix + fence + argv, input: input,
520
- timeout: timeout - (monotonic - started), cancel: view)
602
+ timeout: timeout - (monotonic - started), cancel: view, stdout_tail: stdout_tail)
521
603
  Internal::TmuxVersion.check_fence(result, marker, @release)
522
604
  end
523
605
  end
524
606
 
525
- def execute_typed(arguments, repaired_break: false, **options)
607
+ def execute_typed(arguments, repaired_break: false, stdout_tail: nil, **options)
526
608
  arguments = encode_arguments(arguments)
527
- result = repaired_break ? dispatch(arguments, repaired_break: true, **options) : run(arguments, **options)
528
- raise CommandError.new(result: result, phase: :command) unless result.success?
609
+ result = if repaired_break || stdout_tail
610
+ dispatch(arguments, repaired_break: repaired_break, stdout_tail: stdout_tail, **options)
611
+ else
612
+ run(arguments, **options)
613
+ end
614
+ unless result.success?
615
+ message = "tmux #{arguments.first} failed"
616
+ line = result.stderr.byteslice(0, 240).partition(/[\r\n]/).first
617
+ reason = line.force_encoding(Encoding::UTF_8).scrub("?").gsub(/[[:cntrl:]\p{Cf}\p{Zl}\p{Zp}]/, "?")
618
+ message += ": #{reason}" unless reason.empty?
619
+ raise CommandError.new(message, result: result, phase: :command)
620
+ end
529
621
 
530
622
  result
531
623
  end
@@ -549,6 +641,10 @@ module LibTmux
549
641
  name.gsub("#", "##")
550
642
  end
551
643
 
644
+ def creation_command(command)
645
+ command.nil? ? [] : ["--", *pane_command(command)]
646
+ end
647
+
552
648
  def pane_command(command)
553
649
  validate_argv(command)
554
650
  raise ArgumentError, "command executable must not be empty" if command.first.empty?
@@ -606,10 +702,17 @@ module LibTmux
606
702
  end
607
703
 
608
704
  def list_entities(kind, options, global: false, timeout: 5.0, cancel: nil)
609
- result = execute_typed(["list-#{kind}s", *options, "-F", id_format(kind)], timeout: timeout, cancel: cancel)
705
+ budget = operation_budget(timeout, cancel)
706
+ result = execute_typed(["list-#{kind}s", *options, "-F", id_format(kind)], **budget.options)
610
707
  entities = Internal::Metadata.decode(result.stdout, fields: 1).map { |row| build_entity(kind, row.first) }
611
708
  entities = entities.uniq.sort_by { |entity| entity.id[1..].to_i } if global
612
709
  entities.freeze
710
+ rescue CommandError => error
711
+ # Even with -a, tmux requires a current target for windows and panes.
712
+ raise unless global && kind != :session && error.result.stderr == "no current target\n"
713
+ raise unless list_sessions(**budget.options).empty?
714
+
715
+ [].freeze
613
716
  end
614
717
 
615
718
  def creation_options(cwd:, environment:)
@@ -645,9 +748,10 @@ module LibTmux
645
748
 
646
749
  destination = target(ref, :session)
647
750
  destination += ":#{index}" unless index.nil?
648
- arguments = ["new-window", *(focus ? [] : ["-d"]), "-P", "-F", creation_format(:window, receipt), "-t", destination, "-n", literal_name(name)]
751
+ arguments = ["new-window", *(focus ? [] : ["-d"]), "-P", "-F", creation_format(:window, receipt), "-t", destination]
752
+ arguments.concat(["-n", literal_name(name)]) unless name.nil?
649
753
  arguments.concat(creation_options(cwd: cwd, environment: environment))
650
- create_entity(:window, arguments + ["--"] + pane_command(command), receipt: receipt, **budget.options)
754
+ create_entity(:window, arguments + creation_command(command), receipt: receipt, **budget.options)
651
755
  end
652
756
 
653
757
  def split_window(ref, direction:, command:, size: nil, cwd: nil, environment: {}, focus: false, timeout: 5.0, cancel: nil)
@@ -667,7 +771,7 @@ module LibTmux
667
771
  arguments = ["split-window", *(focus ? [] : ["-d"]), flag, "-P", "-F", id_format(:pane), "-t", target(ref, ref.kind)]
668
772
  arguments.concat(["-l", size.to_s]) if size
669
773
  arguments.concat(creation_options(cwd: cwd, environment: environment))
670
- create_entity(:pane, arguments + ["--"] + pane_command(command), **budget.options)
774
+ create_entity(:pane, arguments + creation_command(command), **budget.options)
671
775
  end
672
776
  end
673
777
  end
@@ -30,6 +30,11 @@ module LibTmux
30
30
  end
31
31
 
32
32
  class Server
33
+ # Checks a TERM value before opening a server or attaching a client.
34
+ def self.valid_terminal_type?(value)
35
+ value.is_a?(String) && value.ascii_only? && /\A[A-Za-z0-9][A-Za-z0-9_.+-]{0,127}\z/.match?(value)
36
+ end
37
+
33
38
  # Resolves the literal selector at dispatch; it is not a client reference.
34
39
  def switch_client(client:, session:, timeout: 5.0, cancel: nil)
35
40
  budget = operation_budget(timeout, cancel)
@@ -50,7 +55,7 @@ module LibTmux
50
55
  unless terminal.is_a?(IO) && !terminal.closed? && terminal.tty?
51
56
  raise ArgumentError, "terminal must be an open caller-owned TTY"
52
57
  end
53
- unless term.is_a?(String) && /\A[A-Za-z0-9][A-Za-z0-9_.+-]{0,127}\z/.match?(term)
58
+ unless Server.valid_terminal_type?(term)
54
59
  raise ArgumentError, "term must name a terminal type"
55
60
  end
56
61
  raise ArgumentError, "read_only must be Boolean" unless [true, false].include?(read_only)
@@ -0,0 +1,101 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "io/wait"
4
+ require "libtmux/entity"
5
+ require "libtmux/tmux_version"
6
+
7
+ module LibTmux
8
+ module TextWait
9
+ # The joined screen and whether its first capture matched the needle.
10
+ Result = Data.define(:text, :matched_at_entry) do
11
+ private_class_method :new, :[]
12
+ end
13
+ end
14
+
15
+ class Pane
16
+ # Wait for literal text on the visible screen, including wrapped lines.
17
+ # The first read happens immediately. Each read runs the pane's native
18
+ # after-capture-pane hook. Use a distinct reply to avoid matching input echo.
19
+ # @raise [PaneDied] if the pane or server ends first
20
+ # @raise [DeadlineExceeded] if timeout elapses
21
+ # @raise [Cancelled] if the cancellation token is signaled
22
+ def wait_for_text(text, interval: 0.1, timeout: 5.0, cancel: nil)
23
+ last_text = ""
24
+ unless text.is_a?(String) && !text.empty?
25
+ raise ArgumentError, "text must be a nonempty String"
26
+ end
27
+ unless interval.is_a?(Numeric) && interval.finite? && interval.positive?
28
+ raise ArgumentError, "interval must be positive and finite"
29
+ end
30
+
31
+ needle = text.dup.freeze
32
+ budget = server.__send__(:operation_budget, timeout, cancel)
33
+ pane_id = target
34
+ first_read = true
35
+ loop do
36
+ argv, marker = Internal::TmuxVersion.identity_argv(%w[pane_id pane_dead])
37
+ probe = [argv.first, "-t", pane_id, *argv.drop(1)]
38
+ result = server.run(["capture-pane", "-p", "-J", "-t", pane_id, ";", *probe], **budget.options)
39
+ screen, ending = text_wait_frame(result, marker, pane_id)
40
+ last_text = screen if screen
41
+ matched = last_text.include?(needle)
42
+ remaining = budget.options.fetch(:timeout)
43
+
44
+ if matched
45
+ return TextWait::Result.__send__(:new, text: last_text, matched_at_entry: first_read)
46
+ end
47
+ if ending
48
+ raise PaneDied.__send__(:new, ending, last_text)
49
+ end
50
+
51
+ text_wait_pause([interval, remaining].min, cancel)
52
+ first_read = false
53
+ end
54
+ rescue DeadlineExceeded, Cancelled => error
55
+ error.__send__(:attach_wait_text, last_text)
56
+ raise
57
+ end
58
+
59
+ private
60
+
61
+ def text_wait_frame(result, marker, pane_id)
62
+ stderr = result.stderr
63
+ # A capture hook can emit its own diagnostic before the state probe runs.
64
+ state = /^unknown command: #{Regexp.escape(marker)}(%\d+)?,([01])?\n/n.match(stderr)
65
+ if state
66
+ # The parse error in stderr carries state independently of screen bytes.
67
+ unless result.stdout.end_with?("\n") && (state[1] != pane_id || state[2])
68
+ raise ProtocolError.new("tmux did not return a complete pane capture", phase: :read, delivery: :observed)
69
+ end
70
+
71
+ ending = if state[1] != pane_id
72
+ :pane_gone
73
+ elsif state[2] == "1"
74
+ :pane_exited
75
+ end
76
+ return [result.text.freeze, ending]
77
+ end
78
+
79
+ # A failed capture can print hook output without reading the screen.
80
+ if Internal::TmuxVersion.daemon_loss_delivery(result)
81
+ return [nil, :server_gone]
82
+ end
83
+ if stderr.start_with?("no current target\n") ||
84
+ stderr.match?(/\Acan't find (?:pane|window|session): #{Regexp.escape(pane_id)}\n/n)
85
+ return [nil, :pane_gone]
86
+ end
87
+
88
+ raise CommandError.new("tmux could not read the pane screen", result: result, phase: :read)
89
+ end
90
+
91
+ def text_wait_pause(duration, cancel)
92
+ if cancel
93
+ cancel.reader.wait_readable(duration)
94
+ else
95
+ sleep(duration)
96
+ end
97
+ rescue IOError
98
+ raise unless cancel&.cancelled?
99
+ end
100
+ end
101
+ end
@@ -28,7 +28,8 @@ module LibTmux
28
28
  # sharing it, refuses the server instead of silently disabling the fence.
29
29
  FENCE_COMMAND = "if-shel"
30
30
  PROBE_COMMAND = "run-shel"
31
- ABSENT = /no server running|error connecting to .*\((?:No such file or directory|Connection refused)\)/
31
+ ABSENT = /\A(?:no server running(?: on [^\n]+)?|error connecting to [^\n]+ \((?:No such file or directory|Connection refused)\))\n?\z/n
32
+ private_constant :ABSENT
32
33
  # What a daemon older than 3.2 answers to the probe. run-shell gained -C
33
34
  # in 3.2, so 3.1 reports its usage line; a 3.0 daemon speaks a protocol
34
35
  # the client refuses before any command runs.
@@ -117,7 +118,7 @@ module LibTmux
117
118
  raise UnsupportedFeatureError.new("tmux #{MINIMUM} or newer is required (the connected daemon is older than 3.2); #{REMEDY}",
118
119
  phase: :admission, expected: EXPECTED)
119
120
  end
120
- if ABSENT.match?(stderr)
121
+ if daemon_loss_delivery(result)
121
122
  raise TargetNotFoundError.new("no tmux server is running at the selected endpoint", phase: :admission)
122
123
  end
123
124
 
@@ -126,6 +127,13 @@ module LibTmux
126
127
  raise not_sent(error), cause: nil
127
128
  end
128
129
 
130
+ def daemon_loss_delivery(result)
131
+ return if result.success?
132
+ return :not_sent if result.stdout.empty? && ABSENT.match?(result.stderr.b)
133
+
134
+ :possibly_sent if result.stderr == "server exited unexpectedly\n"
135
+ end
136
+
129
137
  # Reads the executable that would start a new daemon. tmux 3.3a prints
130
138
  # its own file name where later releases print "tmux".
131
139
  def executable(path)
@@ -162,6 +170,20 @@ module LibTmux
162
170
  values.map(&:freeze)
163
171
  end
164
172
 
173
+ def daemon_identity_argv
174
+ identity_argv(%w[version pid start_time])
175
+ end
176
+
177
+ def parse_daemon_identity(result, marker, phase: :decode)
178
+ version, pid, start_time = parse_identity(result, marker, 3)
179
+ unless pid.match?(/\A[1-9][0-9]{0,9}\z/n) && start_time.match?(/\A-?[0-9]{1,19}\z/n)
180
+ raise ProtocolError.new("invalid tmux daemon identity metadata", phase: phase, delivery: :observed)
181
+ end
182
+
183
+ {version: version.dup.force_encoding(Encoding::UTF_8).freeze,
184
+ pid: Integer(pid, 10), start_time: Integer(start_time, 10)}
185
+ end
186
+
165
187
  # Leading commands for one dispatch. A daemon that no longer reports
166
188
  # +release+ fails the if-shell condition and reaches the private marker,
167
189
  # which tmux rejects before the commands that follow.
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module LibTmux
4
- VERSION = "0.1.1"
4
+ VERSION = "0.1.3"
5
5
  end
data/lib/libtmux.rb CHANGED
@@ -17,3 +17,9 @@ require "libtmux/control"
17
17
  require "libtmux/group"
18
18
  require "libtmux/owned"
19
19
  require "libtmux/terminal"
20
+ require "libtmux/text_wait"
21
+ require "libtmux/program"
22
+
23
+ module LibTmux
24
+ autoload :OptionCatalog, "libtmux/option_catalog"
25
+ end
@@ -0,0 +1,60 @@
1
+ # frozen_string_literal: true
2
+
3
+ # tmux starts this supervisor as the foreground process-group leader. Only the
4
+ # original socket peer can release the one-shot argv or keep the program alive.
5
+ require "socket"
6
+
7
+ directory, title = ARGV
8
+ if title == "prepare"
9
+ begin
10
+ UNIXSocket.open(File.join(directory, "prepare.sock")) do |socket|
11
+ socket.puts(Process.pid)
12
+ socket.read(1)
13
+ end
14
+ rescue Errno::ENOENT, Errno::ECONNREFUSED, Errno::ECONNRESET
15
+ # The launching owner has already unwound.
16
+ end
17
+ exit
18
+ end
19
+ exit 1 unless Process.getpgrp == Process.pid
20
+ begin
21
+ owner = UNIXSocket.new(File.join(directory, "owner.sock"))
22
+ rescue Errno::ENOENT, Errno::ECONNREFUSED
23
+ exit 1
24
+ end
25
+ owner.close_on_exec = true
26
+ # Terminal-generated signals also reach the supervisor. Caught dispositions
27
+ # revert to their defaults when the worker execs.
28
+ %w[HUP INT QUIT TSTP].each { |signal| Signal.trap(signal) {} }
29
+ begin
30
+ owner.puts(Process.pid)
31
+ exit unless owner.read(1) == "G"
32
+ command_file = File.join(directory, "argv")
33
+ argv = File.binread(command_file).split("\0".b, -1)
34
+ File.unlink(command_file)
35
+ Dir.rmdir(directory)
36
+ owner.write("A")
37
+ begin
38
+ child = Process.spawn([argv.first, argv.first], *argv.drop(1), close_others: true)
39
+ rescue SystemCallError => error
40
+ owner.puts("spawn #{error.errno}")
41
+ else
42
+ loop do
43
+ if (observed = Process.waitpid2(child, Process::WNOHANG))
44
+ status = observed.last
45
+ # CAN ends any unfinished escape. tmux parses the uppercase title after
46
+ # preceding output, and the title survives PTY uppercase conversion.
47
+ STDOUT.syswrite("\x18\e]2;#{title}\a")
48
+ owner.puts(status.signaled? ? "signal #{status.termsig}" : "exit #{status.exitstatus}")
49
+ break
50
+ end
51
+ exit if IO.select([owner], nil, nil, 0.01)
52
+ end
53
+ end
54
+ owner.read(1) # Keep the process generation live until close or owner death.
55
+ rescue Errno::EPIPE, Errno::ECONNRESET, Errno::EIO
56
+ # The owner or terminal disappeared.
57
+ ensure
58
+ owner.close
59
+ Process.kill("KILL", 0) # Our live process still pins this process group.
60
+ end