Skip to content
Myr

common.rb

This file

Path

test/lib/common.rb

398 lines · 10.7 KiB · Ruby

Last changed by

Pass bracketed paste actions through wait/track blockJunegunn Choibefore adoption978ded5

History of this file

Take it

1# frozen_string_literal: true23require 'bundler/setup'4require 'minitest/autorun'5require 'fileutils'6require 'English'7require 'shellwords'8require 'erb'9require 'tempfile'10require 'net/http'11require 'json'1213TEMPLATE = File.read(File.expand_path('common.sh', __dir__))14FISH_TEMPLATE = File.read(File.expand_path('common.fish', __dir__))15UNSETS = %w[16  FZF_DEFAULT_COMMAND FZF_DEFAULT_OPTS17  FZF_TMUX FZF_TMUX_OPTS18  FZF_CTRL_T_COMMAND FZF_CTRL_T_OPTS19  FZF_ALT_C_COMMAND20  FZF_ALT_C_OPTS FZF_CTRL_R_OPTS21  FZF_API_KEY22].freeze23DEFAULT_TIMEOUT = 102425FILE = File.expand_path(__FILE__)26BASE = File.expand_path('../..', __dir__)27Dir.chdir(BASE)28FZF = %(FZF_DEFAULT_OPTS="--no-scrollbar --gutter ' ' --pointer '>' --marker '>'" FZF_DEFAULT_COMMAND= #{BASE}/bin/fzf).freeze2930def wait(timeout = DEFAULT_TIMEOUT)31  since = Time.now32  begin33    yield or raise Minitest::Assertion, 'Assertion failure'34  rescue Minitest::Assertion35    raise if Time.now - since > timeout3637    sleep(0.05)38    retry39  end40end4142class Shell43  class << self44    def bash45      @bash ||=46        begin47          bashrc = '/tmp/fzf.bash'48          File.open(bashrc, 'w') do |f|49            f.puts ERB.new(TEMPLATE).result(binding)50          end5152          "bash --rcfile #{bashrc}"53        end54    end5556    def zsh57      @zsh ||=58        begin59          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          end65          "ZDOTDIR=#{zdotdir} zsh"66        end67    end6869    def fish70      @fish ||=71        begin72          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          end78          "rm -f ~/.local/share/fish/fzf_test_history; XDG_CONFIG_HOME=#{confdir} fish"79        end80    end8182    def nushell83      @nushell ||=84        begin85          xdg_home = '/tmp/fzf-nushell-xdg'86          config_dir = "#{xdg_home}/nushell"87          FileUtils.rm_rf(xdg_home)88          FileUtils.mkdir_p(config_dir)8990          # Write env.nu to set up PATH and unset FZF variables91          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            end96            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          end99100          # Write config.nu with minimal prompt101          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          end109110          "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        end112    end113  end114end115116class Tmux117  attr_reader :win118119  def initialize(shell = :bash)120    @shell = shell121    @win = go(%W[new-window -d -P -F #I #{Shell.send(shell)}]).first122    go(%W[set-window-option -t #{@win} pane-base-index 0])123    if shell == :fish124      send_keys 'function fish_prompt; end; clear', :Enter125      self.until(&:empty?)126    elsif shell == :nushell127      # Clear history from previous tests to avoid contamination128      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 exactly131      # 'fzf-ready' (not the command echo which includes 'print').132      retries = 0133      begin134        send_keys 'print "fzf-ready"', :Enter135        self.until { |lines| lines.any? { |l| l.strip == 'fzf-ready' } }136      rescue Minitest::Assertion137        retries += 1138        raise if retries > 5139140        retry141      end142      send_keys 'clear', :Enter143      self.until(&:empty?)144    end145  end146147  def kill148    go(%W[kill-window -t #{win}])149  end150151  def focus152    go(%W[select-window -t #{win}])153  end154155  def send_keys(*args)156    go(%W[send-keys -t #{win}] + args.map(&:to_s))157  end158159  # Simulate a mouse click at the given 1-based column and row using the SGR mouse protocol160  # (xterm mouse mode 1006, which fzf enables). The escape sequence is injected as literal161  # 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 toggle164  # 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]).first167    go(%w[set-option -g mouse off])168    begin169      seq = "\e[<#{button};#{col};#{row}M\e[<#{button};#{col};#{row}m"170      go(%W[send-keys -t #{win} -l #{seq}])171    ensure172      go(%W[set-option -g mouse #{prev}]) if prev && !prev.empty?173    end174  end175176  def paste(str)177    system('tmux', 'setb', str, ';', 'pasteb', '-t', win, ';', 'send-keys', '-t', win, 'Enter')178  end179180  # Paste with bracketed paste control codes so fzf sees181  # bracketed-paste-begin/end around the content182  def paste_bracketed(str)183    system('tmux', 'setb', str, ';', 'pasteb', '-p', '-t', win)184  end185186  def capture187    go(%W[capture-pane -p -J -t #{win}]).map(&:rstrip).reverse.drop_while(&:empty?).reverse188  end189190  # Raw pane capture with ANSI escape sequences preserved.191  def capture_ansi192    go(%W[capture-pane -p -J -e -t #{win}])193  end194195  # 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].freeze197198  # Parse `tmux capture-pane -e` output into per-row bg ranges. Each row is an199  # 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_ranges206    raw = go(%W[capture-pane -p -J -e -t #{win}])207    bg = 'default'208    raw.map do |row|209      cells = []210      i = 0211      len = row.length212      while i < len213        c = row[i]214        if c == "\e" && row[i + 1] == '['215          j = i + 2216          j += 1 while j < len && row[j] != 'm'217          parts = row[i + 2...j].split(';')218          k = 0219          while k < parts.length220            p = parts[k].to_i221            case p222            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 48226              if parts[k + 1] == '5'227                bg = "256:#{parts[k + 2]}"228                k += 2229              elsif parts[k + 1] == '2'230                bg = "rgb:#{parts[k + 2]}:#{parts[k + 3]}:#{parts[k + 4]}"231                k += 4232              end233            end234            k += 1235          end236          i = j + 1237        else238          cells << bg239          i += 1240        end241      end242      ranges = []243      start = 0244      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 = idx248        end249      end250      ranges << [start, cells.length - 1, cells.last] unless cells.empty?251      ranges252    end253  end254255  def until(refresh = false, timeout: DEFAULT_TIMEOUT)256    lines = nil257    begin258      wait(timeout) do259        lines = capture260        class << lines261          def counts262            lazy263              .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          end267268          def match_count269            counts[0]270          end271272          def item_count273            counts[1]274          end275276          def select_count277            counts[2]278          end279280          def any_include?(val)281            method = val.is_a?(Regexp) ? :match : :include?282            find { |line| line.send(method, val) }283          end284        end285        yield(lines).tap do |ok|286          send_keys 'C-l' if refresh && !ok287        end288      end289    rescue Minitest::Assertion290      puts $ERROR_INFO.backtrace291      puts '>' * 80292      puts lines293      puts '<' * 80294      raise295    end296    lines297  end298299  def prepare300    tries = 0301    begin302      if @shell == :nushell303        message = "Prepare[#{tries}]"304        send_keys 'C-u', 'C-l'305        sleep(0.2)306        send_keys ' ', 'C-u', :Enter, message307        self.until { |lines| lines[-1] == message }308      else309        self.until(true) do |lines|310          message = "Prepare[#{tries}]"311          send_keys ' ', 'C-u', :Enter, message, :Left, :Right312          sleep(0.15)313          lines[-1] == message314        end315      end316    rescue Minitest::Assertion317      (tries += 1) < 5 ? retry : raise318    end319    send_keys 'C-u', 'C-l'320  end321322  private323324  def go(args)325    IO.popen(%w[tmux] + args) { |io| io.readlines(chomp: true) }326  end327end328329class TestBase < Minitest::Test330  TEMPNAME = Dir::Tmpname.create(%w[fzf]) {}331  FIFONAME = Dir::Tmpname.create(%w[fzf-fifo]) {}332333  def writelines(lines)334    File.write(TEMPNAME, lines.join("\n"))335  end336337  def tempname338    TEMPNAME339  end340341  def fzf_output342    @thread.join.value.chomp.tap { @thread = nil }343  end344345  def fzf_output_lines346    fzf_output.lines(chomp: true)347  end348349  def setup350    File.mkfifo(FIFONAME)351  end352353  def teardown354    FileUtils.rm_f([TEMPNAME, FIFONAME])355  end356357  alias assert_equal_org assert_equal358  def assert_equal(expected, actual)359    # Ignore info separator360    actual = actual&.sub(/\s*─+$/, '') if actual.is_a?(String) && actual&.match?(%r{\d+/\d+})361    assert_equal_org(expected, actual)362  end363364  # Run fzf with its output piped to a fifo365  def fzf(*opts)366    raise 'fzf_output not taken' if @thread367368    @thread = Thread.new { File.read(FIFONAME) }369    fzf!(*opts) + " > #{FIFONAME.shellescape}"370  end371372  def fzf!(*opts)373    opts = opts.filter_map do |o|374      case o375      when Symbol376        o = o.to_s377        o.length > 1 ? "--#{o.tr('_', '-')}" : "-#{o}"378      when String, Numeric379        o.to_s380      end381    end382    "#{FZF} #{opts.join(' ')}"383  end384end385386class TestInteractive < TestBase387  attr_reader :tmux388389  def setup390    super391    @tmux = Tmux.new392  end393394  def teardown395    super396    @tmux.kill397  end398end