[rubygems/rubygems] Use a constant empty tar header to avoid extra allocations
[ruby.git] / lib / syntax_suggest / display_invalid_blocks.rb
blob5e79b3a262896e35ea15d6d90a383f383f476c4d
1 # frozen_string_literal: true
3 require_relative "capture_code_context"
4 require_relative "display_code_with_line_numbers"
6 module SyntaxSuggest
7   # Used for formatting invalid blocks
8   class DisplayInvalidBlocks
9     attr_reader :filename
11     def initialize(code_lines:, blocks:, io: $stderr, filename: nil, terminal: DEFAULT_VALUE)
12       @io = io
13       @blocks = Array(blocks)
14       @filename = filename
15       @code_lines = code_lines
17       @terminal = (terminal == DEFAULT_VALUE) ? io.isatty : terminal
18     end
20     def document_ok?
21       @blocks.none? { |b| !b.hidden? }
22     end
24     def call
25       if document_ok?
26         return self
27       end
29       if filename
30         @io.puts("--> #{filename}")
31         @io.puts
32       end
33       @blocks.each do |block|
34         display_block(block)
35       end
37       self
38     end
40     private def display_block(block)
41       # Build explanation
42       explain = ExplainSyntax.new(
43         code_lines: block.lines
44       ).call
46       # Enhance code output
47       # Also handles several ambiguious cases
48       lines = CaptureCodeContext.new(
49         blocks: block,
50         code_lines: @code_lines
51       ).call
53       # Build code output
54       document = DisplayCodeWithLineNumbers.new(
55         lines: lines,
56         terminal: @terminal,
57         highlight_lines: block.lines
58       ).call
60       # Output syntax error explanation
61       explain.errors.each do |e|
62         @io.puts e
63       end
64       @io.puts
66       # Output code
67       @io.puts(document)
68     end
70     private def code_with_context
71       lines = CaptureCodeContext.new(
72         blocks: @blocks,
73         code_lines: @code_lines
74       ).call
76       DisplayCodeWithLineNumbers.new(
77         lines: lines,
78         terminal: @terminal,
79         highlight_lines: @invalid_lines
80       ).call
81     end
82   end
83 end