Debian Codegraph @

test/lib/common.rb

raw
1 # frozen_string_literal: true
2
3 require 'bundler/setup'
4 require 'minitest/autorun'
5 require 'fileutils'
6 require 'English'
7 require 'shellwords'
8 require 'erb'
9 require 'tempfile'
10 require 'net/http'
11 require 'json'
12
13 TEMPLATE = File.read(File.expand_path('common.sh', __dir__))
14 FISH_TEMPLATE = File.read(File.expand_path('common.fish', __dir__))
15 UNSETS = %w[
16 FZF_DEFAULT_COMMAND FZF_DEFAULT_OPTS
17 FZF_TMUX FZF_TMUX_OPTS
18 FZF_CTRL_T_COMMAND FZF_CTRL_T_OPTS
19 FZF_ALT_C_COMMAND
20 FZF_ALT_C_OPTS FZF_CTRL_R_OPTS
21 FZF_API_KEY
22 ].freeze
23 DEFAULT_TIMEOUT = 10
24
25 FILE = File.expand_path(__FILE__)
26 BASE = File.expand_path('../..', __dir__)
27 Dir.chdir(BASE)
28 FZF = %(FZF_DEFAULT_OPTS="--no-scrollbar --gutter ' ' --pointer '>' --marker '>'" FZF_DEFAULT_COMMAND= #{BASE}/bin/fzf).freeze
29
30 def wait(timeout = DEFAULT_TIMEOUT)
31 since = Time.now
32 begin
33 yield or raise Minitest::Assertion, 'Assertion failure'
34 rescue Minitest::Assertion
35 raise if Time.now - since > timeout
36
37 sleep(0.05)
38 retry
39 end
40 end
41
42 class Shell
43 class << self
44 def bash
45 @bash ||=
46 begin
47 bashrc = '/tmp/fzf.bash'
48 File.open(bashrc, 'w') do |f|
49 f.puts ERB.new(TEMPLATE).result(binding)
50 end
51
52 "bash --rcfile #{bashrc}"
53 end
54 end
55
56 def zsh
57 @zsh ||=
58 begin
59 zdotdir = '/tmp/fzf-zsh'
60 FileUtils.rm_rf(zdotdir)
61 FileUtils.mkdir_p(zdotdir)
62 File.open("#{zdotdir}/.zshrc", 'w') do |f|
63 f.puts ERB.new(TEMPLATE).result(binding)
64 end
65 "ZDOTDIR=#{zdotdir} zsh"
66 end
67 end
68
69 def fish
70 @fish ||=
71 begin
72 confdir = '/tmp/fzf-fish'
73 FileUtils.rm_rf(confdir)
74 FileUtils.mkdir_p("#{confdir}/fish/conf.d")
75 File.open("#{confdir}/fish/conf.d/fzf.fish", 'w') do |f|
76 f.puts ERB.new(FISH_TEMPLATE).result(binding)
77 end
78 "rm -f ~/.local/share/fish/fzf_test_history; XDG_CONFIG_HOME=#{confdir} fish"
79 end
80 end
81
82 def nushell
83 @nushell ||=
84 begin
85 xdg_home = '/tmp/fzf-nushell-xdg'
86 config_dir = "#{xdg_home}/nushell"
87 FileUtils.rm_rf(xdg_home)
88 FileUtils.mkdir_p(config_dir)
89
90 # Write env.nu to set up PATH and unset FZF variables
91 File.open("#{config_dir}/env.nu", 'w') do |f|
92 f.puts "$env.PATH = ($env.PATH | split row (char esep) | prepend '#{BASE}/bin')"
93 UNSETS.each do |var|
94 f.puts "hide-env -i #{var}"
95 end
96 f.puts "$env.FZF_DEFAULT_OPTS = \"--no-scrollbar --pointer '>' --marker '>'\""
97 f.puts '$env.config = ($env.config | upsert history { file_format: "plaintext", max_size: 100 })'
98 end
99
100 # Write config.nu with minimal prompt
101 File.open("#{config_dir}/config.nu", 'w') do |f|
102 f.puts '$env.PROMPT_COMMAND = {|| "" }'
103 f.puts '$env.PROMPT_INDICATOR = ""'
104 f.puts '$env.PROMPT_COMMAND_RIGHT = {|| "" }'
105 f.puts '$env.config = ($env.config | upsert show_banner false)'
106 f.puts "source #{BASE}/shell/key-bindings.nu"
107 f.puts "source #{BASE}/shell/completion.nu"
108 end
109
110 "unset #{UNSETS.join(' ')}; env XDG_CONFIG_HOME=#{xdg_home} XDG_DATA_HOME=#{xdg_home}/../fzf-nushell-data nu --config #{config_dir}/config.nu --env-config #{config_dir}/env.nu"
111 end
112 end
113 end
114 end
115
116 class Tmux
117 attr_reader :win
118
119 def initialize(shell = :bash)
120 @shell = shell
121 @win = go(%W[new-window -d -P -F #I #{Shell.send(shell)}]).first
122 go(%W[set-window-option -t #{@win} pane-base-index 0])
123 if shell == :fish
124 send_keys 'function fish_prompt; end; clear', :Enter
125 self.until(&:empty?)
126 elsif shell == :nushell
127 # Clear history from previous tests to avoid contamination
128 FileUtils.rm_f('/tmp/fzf-nushell-xdg/nushell/history.txt')
129 # Wait for nushell to be ready by polling with a marker command.
130 # We use 'print "fzf-ready"' and check for a line that is exactly
131 # 'fzf-ready' (not the command echo which includes 'print').
132 retries = 0
133 begin
134 send_keys 'print "fzf-ready"', :Enter
135 self.until { |lines| lines.any? { |l| l.strip == 'fzf-ready' } }
136 rescue Minitest::Assertion
137 retries += 1
138 raise if retries > 5
139
140 retry
141 end
142 send_keys 'clear', :Enter
143 self.until(&:empty?)
144 end
145 end
146
147 def kill
148 go(%W[kill-window -t #{win}])
149 end
150
151 def focus
152 go(%W[select-window -t #{win}])
153 end
154
155 def send_keys(*args)
156 go(%W[send-keys -t #{win}] + args.map(&:to_s))
157 end
158
159 # Simulate a mouse click at the given 1-based column and row using the SGR mouse protocol
160 # (xterm mouse mode 1006, which fzf enables). The escape sequence is injected as literal
161 # keystrokes via tmux, and fzf parses it like a real terminal mouse event.
162 #
163 # tmux's own mouse handling intercepts these sequences when `set -g mouse on`, so we toggle
164 # mouse off for the duration of the click and restore the previous state afterwards.
165 def click(col, row, button: 0)
166 prev = go(%w[show-options -gv mouse]).first
167 go(%w[set-option -g mouse off])
168 begin
169 seq = "\e[<#{button};#{col};#{row}M\e[<#{button};#{col};#{row}m"
170 go(%W[send-keys -t #{win} -l #{seq}])
171 ensure
172 go(%W[set-option -g mouse #{prev}]) if prev && !prev.empty?
173 end
174 end
175
176 def paste(str)
177 system('tmux', 'setb', str, ';', 'pasteb', '-t', win, ';', 'send-keys', '-t', win, 'Enter')
178 end
179
180 # Paste with bracketed paste control codes so fzf sees
181 # bracketed-paste-begin/end around the content
182 def paste_bracketed(str)
183 system('tmux', 'setb', str, ';', 'pasteb', '-p', '-t', win)
184 end
185
186 def capture
187 go(%W[capture-pane -p -J -t #{win}]).map(&:rstrip).reverse.drop_while(&:empty?).reverse
188 end
189
190 # Raw pane capture with ANSI escape sequences preserved.
191 def capture_ansi
192 go(%W[capture-pane -p -J -e -t #{win}])
193 end
194
195 # 3-bit ANSI bg code (40..47) -> color name used in --color options.
196 BG_NAMES = %w[black red green yellow blue magenta cyan white].freeze
197
198 # Parse `tmux capture-pane -e` output into per-row bg ranges. Each row is an
199 # array of [col_start, col_end, bg] tuples where bg is one of:
200 # 'default'
201 # 'red' / 'green' / 'blue' / ... (3-bit names)
202 # 'bright-red' / ... (bright variants)
203 # '256:<n>' (256-color fallback)
204 # ANSI state persists across rows, matching real terminal behavior.
205 def bg_ranges
206 raw = go(%W[capture-pane -p -J -e -t #{win}])
207 bg = 'default'
208 raw.map do |row|
209 cells = []
210 i = 0
211 len = row.length
212 while i < len
213 c = row[i]
214 if c == "\e" && row[i + 1] == '['
215 j = i + 2
216 j += 1 while j < len && row[j] != 'm'
217 parts = row[i + 2...j].split(';')
218 k = 0
219 while k < parts.length
220 p = parts[k].to_i
221 case p
222 when 0, 49 then bg = 'default'
223 when 40..47 then bg = BG_NAMES[p - 40]
224 when 100..107 then bg = "bright-#{BG_NAMES[p - 100]}"
225 when 48
226 if parts[k + 1] == '5'
227 bg = "256:#{parts[k + 2]}"
228 k += 2
229 elsif parts[k + 1] == '2'
230 bg = "rgb:#{parts[k + 2]}:#{parts[k + 3]}:#{parts[k + 4]}"
231 k += 4
232 end
233 end
234 k += 1
235 end
236 i = j + 1
237 else
238 cells << bg
239 i += 1
240 end
241 end
242 ranges = []
243 start = 0
244 cells.each_with_index do |b, idx|
245 if idx.positive? && b != cells[idx - 1]
246 ranges << [start, idx - 1, cells[idx - 1]]
247 start = idx
248 end
249 end
250 ranges << [start, cells.length - 1, cells.last] unless cells.empty?
251 ranges
252 end
253 end
254
255 def until(refresh = false, timeout: DEFAULT_TIMEOUT)
256 lines = nil
257 begin
258 wait(timeout) do
259 lines = capture
260 class << lines
261 def counts
262 lazy
263 .map { |l| l.scan(%r{^. ([0-9]+)/([0-9]+)( \(([0-9]+)\))?}) }
264 .reject(&:empty?)
265 .first&.first&.map(&:to_i)&.values_at(0, 1, 3) || [0, 0, 0]
266 end
267
268 def match_count
269 counts[0]
270 end
271
272 def item_count
273 counts[1]
274 end
275
276 def select_count
277 counts[2]
278 end
279
280 def any_include?(val)
281 method = val.is_a?(Regexp) ? :match : :include?
282 find { |line| line.send(method, val) }
283 end
284 end
285 yield(lines).tap do |ok|
286 send_keys 'C-l' if refresh && !ok
287 end
288 end
289 rescue Minitest::Assertion
290 puts $ERROR_INFO.backtrace
291 puts '>' * 80
292 puts lines
293 puts '<' * 80
294 raise
295 end
296 lines
297 end
298
299 def prepare
300 tries = 0
301 begin
302 if @shell == :nushell
303 message = "Prepare[#{tries}]"
304 send_keys 'C-u', 'C-l'
305 sleep(0.2)
306 send_keys ' ', 'C-u', :Enter, message
307 self.until { |lines| lines[-1] == message }
308 else
309 self.until(true) do |lines|
310 message = "Prepare[#{tries}]"
311 send_keys ' ', 'C-u', :Enter, message, :Left, :Right
312 sleep(0.15)
313 lines[-1] == message
314 end
315 end
316 rescue Minitest::Assertion
317 (tries += 1) < 5 ? retry : raise
318 end
319 send_keys 'C-u', 'C-l'
320 end
321
322 private
323
324 def go(args)
325 IO.popen(%w[tmux] + args) { |io| io.readlines(chomp: true) }
326 end
327 end
328
329 class TestBase < Minitest::Test
330 TEMPNAME = Dir::Tmpname.create(%w[fzf]) {}
331 FIFONAME = Dir::Tmpname.create(%w[fzf-fifo]) {}
332
333 def writelines(lines)
334 File.write(TEMPNAME, lines.join("\n"))
335 end
336
337 def tempname
338 TEMPNAME
339 end
340
341 def fzf_output
342 @thread.join.value.chomp.tap { @thread = nil }
343 end
344
345 def fzf_output_lines
346 fzf_output.lines(chomp: true)
347 end
348
349 def setup
350 File.mkfifo(FIFONAME)
351 end
352
353 def teardown
354 FileUtils.rm_f([TEMPNAME, FIFONAME])
355 end
356
357 alias assert_equal_org assert_equal
358 def assert_equal(expected, actual)
359 # Ignore info separator
360 actual = actual&.sub(/\s*─+$/, '') if actual.is_a?(String) && actual&.match?(%r{\d+/\d+})
361 assert_equal_org(expected, actual)
362 end
363
364 # Run fzf with its output piped to a fifo
365 def fzf(*opts)
366 raise 'fzf_output not taken' if @thread
367
368 @thread = Thread.new { File.read(FIFONAME) }
369 fzf!(*opts) + " > #{FIFONAME.shellescape}"
370 end
371
372 def fzf!(*opts)
373 opts = opts.filter_map do |o|
374 case o
375 when Symbol
376 o = o.to_s
377 o.length > 1 ? "--#{o.tr('_', '-')}" : "-#{o}"
378 when String, Numeric
379 o.to_s
380 end
381 end
382 "#{FZF} #{opts.join(' ')}"
383 end
384 end
385
386 class TestInteractive < TestBase
387 attr_reader :tmux
388
389 def setup
390 super
391 @tmux = Tmux.new
392 end
393
394 def teardown
395 super
396 @tmux.kill
397 end
398 end