Class: BeLetItBe::CLI

Inherits:
Thor
  • Object
show all
Defined in:
lib/be_let_it_be/cli.rb

Instance Method Summary collapse

Instance Method Details

#convert(file) ⇒ Object



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
# File 'lib/be_let_it_be/cli.rb', line 14

def convert(file)
  @processed_let_lines = []

  unless File.exist?(file)
    error "File not found: #{file}"
    exit 1
  end

  unless run_rspec(file)
    error "Initial RSpec test failed. Aborting."
    exit 1
  end
  say "Initial tests passed. Starting conversion..."

  temp_file = file + ".temp"
  begin
    File.write(temp_file, File.read(file))

    processed_num = 0
    converted_count = 0
    lets = extract_let_info(file)
    num_of_lets = lets.length

    if num_of_lets.zero?
      say "✨ no let/let! in the given spec; do nothing"
      exit 0
    end

    say "Found #{num_of_lets} let/let! definitions:"
    lets.each { |let| say "  - #{let[:type]} :#{let[:name]} at #{file}:#{let[:line]}" }

    until lets.empty?
      processed_num += 1
      converter = Converter.new(temp_file)
      let = lets.first

      say "[#{processed_num}/#{num_of_lets}] Testing conversion of #{let[:type]} :#{let[:name]} at #{file}:#{let[:line]}"

      if converter.try_conversion_single_let(let, temp_file, -> { run_rspec(temp_file) })
        say "  ✅ Converted to let_it_be"
        converter = Converter.new(temp_file) # pile the converted items
        converted_count += 1
      else
        say "  ❌ Keeping original #{let[:type]} (test failed with let_it_be)"
      end

      @processed_let_lines << let[:line]
      lets = extract_let_info(temp_file)
    end

    if converted_count > 0
      say "🚀 Successfully converted #{converted_count} out of #{lets.size} definitions to let_it_be"

      if options[:dryrun]
        puts File.read(temp_file)
        exit options[:dryrun_exit_code]
      else
        File.write(file, File.read(temp_file))
      end
    else
      say "❣️ No conversions were possible (all tests failed with let_it_be)"
    end
  ensure
    File.unlink(temp_file) if File.exist?(temp_file)
  end
end