api_recipes 3.0.0.beta3 → 3.0.0.beta5

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.
Files changed (35) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +377 -76
  3. data/UPGRADING.md +223 -59
  4. data/lib/api_recipes/cli/calls.rb +27 -0
  5. data/lib/api_recipes/cli/code.rb +153 -0
  6. data/lib/api_recipes/cli/convert/migration.rb +819 -0
  7. data/lib/api_recipes/cli/convert/snippet.rb +67 -0
  8. data/lib/api_recipes/cli/convert.rb +614 -0
  9. data/lib/api_recipes/cli/description.rb +65 -0
  10. data/lib/api_recipes/cli/import/server.rb +20 -9
  11. data/lib/api_recipes/cli/import/writer.rb +16 -4
  12. data/lib/api_recipes/cli/import.rb +23 -9
  13. data/lib/api_recipes/cli/recipes/summary.rb +25 -6
  14. data/lib/api_recipes/cli/recipes.rb +5 -2
  15. data/lib/api_recipes/cli/routes.rb +63 -8
  16. data/lib/api_recipes/cli/tags.rb +19 -0
  17. data/lib/api_recipes/cli/upgrade/fix.rb +206 -0
  18. data/lib/api_recipes/cli/upgrade/project.rb +194 -0
  19. data/lib/api_recipes/cli/upgrade/screen.rb +165 -0
  20. data/lib/api_recipes/cli/upgrade/tree_rules.rb +290 -0
  21. data/lib/api_recipes/cli/upgrade.rb +706 -57
  22. data/lib/api_recipes/cli.rb +171 -17
  23. data/lib/api_recipes/configuration.rb +17 -95
  24. data/lib/api_recipes/endpoint.rb +1 -1
  25. data/lib/api_recipes/internals/compiler.rb +102 -67
  26. data/lib/api_recipes/internals/context.rb +35 -6
  27. data/lib/api_recipes/internals/declaration.rb +17 -15
  28. data/lib/api_recipes/internals/definition.rb +16 -3
  29. data/lib/api_recipes/internals/option_value.rb +92 -0
  30. data/lib/api_recipes/internals/recipe.rb +1 -1
  31. data/lib/api_recipes/internals/recipe_lock.rb +12 -9
  32. data/lib/api_recipes/internals/request.rb +17 -6
  33. data/lib/api_recipes/version.rb +1 -1
  34. data/lib/api_recipes.rb +1 -0
  35. metadata +13 -1
@@ -0,0 +1,206 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'open3'
4
+ require 'pathname'
5
+
6
+ module ApiRecipes
7
+ module CLI
8
+ class Upgrade
9
+ # The changes `upgrade` makes by itself. Each is shown as a diff and is
10
+ # made only when the person answers yes, on a terminal. A change
11
+ # touches only files that git has committed as they are now, so that
12
+ # it can be seen and undone, and writes all its files or none.
13
+ class Fix
14
+ # key: what the change is, said once. texts: { file => its new text }.
15
+ # note: what yes and no mean, when the title does not say it: a line
16
+ # of text, then one entry for each answer.
17
+ Change = Data.define(:key, :title, :texts, :note) do
18
+ def initialize(key:, title:, texts:, note: nil) = super
19
+ end
20
+
21
+ # Whether someone is there to read the question and answer it: the
22
+ # answers come from a terminal, and the results go to one.
23
+ def self.asks?(input, out) = [input, out].all? { |io| io.respond_to?(:tty?) && io.tty? }
24
+
25
+ # shown: how the name of a file is shown. ours: { file => text } for
26
+ # the files that this run of the command already changed.
27
+ def initialize(screen, input, shown:, root: '.', ours: {})
28
+ @screen = screen
29
+ @input = input
30
+ @shown = shown
31
+ @root = root
32
+ @ours = ours
33
+ end
34
+
35
+ # Shows a change that another part of the command works out and
36
+ # makes: the files it creates, edits and deletes. Returns whether
37
+ # the answer was yes.
38
+ def confirm(title, note, preview)
39
+ @screen.section('🔧', title)
40
+ if note
41
+ @screen.line(note.first)
42
+ note.drop(1).each { |answer| @screen.item(answer) }
43
+ end
44
+ preview[:created].each { |file, text| @screen.created(@shown.call(file), text) }
45
+ preview[:edited].each { |file, (before, after)| @screen.diff(@shown.call(file), before, after) }
46
+ preview[:deleted].each { |file| @screen.deleted(@shown.call(file)) }
47
+ @screen.ask('Make this change?', @input)
48
+ end
49
+
50
+ # Shows the change and asks. Returns the files it wrote, or nil when
51
+ # the change was not made.
52
+ def offer(change)
53
+ @screen.section('🔧', change.title)
54
+ reason = blocked(change)
55
+ if reason
56
+ @screen.line("This command does not make the change: #{reason}. The code to paste is below.")
57
+ return nil
58
+ end
59
+ if change.note
60
+ @screen.line(change.note.first)
61
+ change.note.drop(1).each { |answer| @screen.item(answer) }
62
+ @screen.gap
63
+ end
64
+ before = change.texts.keys.to_h { |file| [file, File.read(full(file))] }
65
+ change.texts.each { |file, text| @screen.diff(@shown.call(file), before[file], text) }
66
+ return nil unless @screen.ask('Make this change?', @input)
67
+
68
+ changed = change.texts.keys.find { |file| File.read(full(file)) != before[file] }
69
+ if changed
70
+ @screen.line("#{@shown.call(changed)} changed while the question waited: nothing was written. Run the command again.")
71
+ return nil
72
+ end
73
+ write(change, before) ? change.texts.keys : nil
74
+ rescue SystemCallError => e
75
+ @screen.line("The change could not be written (#{e.class.name.split('::').last}): nothing was written")
76
+ nil
77
+ end
78
+
79
+ private
80
+
81
+ def full(file) = File.join(@root, file)
82
+
83
+ def git(*arguments)
84
+ Open3.capture2e({ 'GIT_OPTIONAL_LOCKS' => '0' }, *Convert::Migration::GIT, '-C', @root, *arguments)
85
+ rescue SystemCallError
86
+ ['', nil]
87
+ end
88
+
89
+ # Why the change cannot be made, or nil.
90
+ def blocked(change)
91
+ _, status = git('--version')
92
+ return 'git was not found, and without it a change could not be seen or undone' unless status&.success?
93
+
94
+ file = change.texts.keys.find { |one| !(committed?(one) || ours?(one)) || !File.writable?(full(one)) }
95
+ return "#{@shown.call(file)} is not a file that git has committed as it is now, so what changes could not be brought back" if file
96
+
97
+ # The lines of a change are written with LF, and a diff would not show the difference.
98
+ crlf = change.texts.keys.find { |one| File.binread(full(one)).include?("\r") }
99
+ crlf && "#{@shown.call(crlf)} ends its lines with CR LF, which this change would not keep"
100
+ end
101
+
102
+ # A plain file of the project: not a symbolic link, not below one,
103
+ # not outside the project.
104
+ def plain?(file)
105
+ path = full(file)
106
+ return false if File.symlink?(path) || !File.file?(path)
107
+
108
+ File.realpath(path) == File.join(File.realpath(@root), Pathname.new(file).cleanpath.to_s)
109
+ rescue SystemCallError
110
+ false
111
+ end
112
+
113
+ # Whether git tracks the file as it does any other, and has it
114
+ # committed as it is now.
115
+ def committed?(file)
116
+ listed, status = git('ls-files', '-v', '--error-unmatch', '--', file)
117
+ return false unless plain?(file) && status&.success? && listed.start_with?('H ')
118
+
119
+ Convert::Migration.as_committed?(file, full(file)) { |*arguments| git(*arguments) }
120
+ end
121
+
122
+ # Whether the file is as this command left it, after a change made
123
+ # to it when git had it committed.
124
+ def ours?(file) = plain?(file) && @ours.key?(file) && File.read(full(file)) == @ours[file]
125
+
126
+ # Writes every file of the change. When one cannot be written, every
127
+ # file is put back: also the one that failed, which can be emptied.
128
+ def write(change, before)
129
+ change.texts.each { |file, text| File.write(full(file), text) }
130
+ @ours.merge!(change.texts)
131
+ true
132
+ rescue SystemCallError => e
133
+ lost = change.texts.keys.reject do |file|
134
+ File.write(full(file), before[file])
135
+ true
136
+ rescue SystemCallError
137
+ false
138
+ end
139
+ @screen.line("The change could not be written (#{e.class.name.split('::').last}): " \
140
+ "#{lost.empty? ? 'every file was put back as it was' : "these files could not be put back: #{lost.map { |file| @shown.call(file) }.join(', ')}"}")
141
+ false
142
+ end
143
+ end
144
+
145
+ # The lines that differ between two texts, with the lines around them.
146
+ module Diff
147
+ # Above this many pairs of lines the middle of the texts is not compared line by line.
148
+ LIMIT = 400_000
149
+
150
+ # [[first line of the old text, [[sign, line], ...]], ...] where sign
151
+ # is '-' for a line taken out, '+' for one added and ' ' for one kept.
152
+ def self.hunks(old, new, context: 2)
153
+ steps = steps(old.lines(chomp: true), new.lines(chomp: true))
154
+ changed = steps.each_index.reject { |index| steps[index].first == ' ' }
155
+ ranges = changed.map { |index| [[index - context, 0].max, [index + context, steps.size - 1].min] }
156
+ ranges = ranges.each_with_object([]) do |(from, to), merged|
157
+ merged.last && from <= merged.last[1] + 1 ? merged.last[1] = [merged.last[1], to].max : merged << [from, to]
158
+ end
159
+ ranges.map { |from, to| [steps[from][2], steps[from..to].map { |sign, line, _| [sign, line] }] }
160
+ end
161
+
162
+ # [[sign, line, number of the line in the old text], ...]
163
+ def self.steps(old, new)
164
+ head = 0
165
+ head += 1 while head < old.size && head < new.size && old[head] == new[head]
166
+ tail = 0
167
+ tail += 1 while tail < old.size - head && tail < new.size - head && old[-1 - tail] == new[-1 - tail]
168
+ from = old[head...old.size - tail]
169
+ to = new[head...new.size - tail]
170
+ middle = from.size * to.size > LIMIT ? from.map { |line| ['-', line] } + to.map { |line| ['+', line] } : compared(from, to)
171
+ number = 0
172
+ (old.first(head).map { |line| [' ', line] } + middle + old.last(tail).map { |line| [' ', line] }).map do |sign, line|
173
+ number += 1 unless sign == '+'
174
+ [sign, line, sign == '+' ? number + 1 : number]
175
+ end
176
+ end
177
+
178
+ # The longest run of lines the two lists share, and what is around it.
179
+ def self.compared(from, to)
180
+ lengths = Array.new(from.size + 1) { Array.new(to.size + 1, 0) }
181
+ (from.size - 1).downto(0) do |i|
182
+ (to.size - 1).downto(0) do |j|
183
+ lengths[i][j] = from[i] == to[j] ? lengths[i + 1][j + 1] + 1 : [lengths[i + 1][j], lengths[i][j + 1]].max
184
+ end
185
+ end
186
+ steps = []
187
+ i = j = 0
188
+ while i < from.size || j < to.size
189
+ if i < from.size && j < to.size && from[i] == to[j]
190
+ steps << [' ', from[i]]
191
+ i += 1
192
+ j += 1
193
+ elsif i < from.size && (j == to.size || lengths[i + 1][j] >= lengths[i][j + 1])
194
+ steps << ['-', from[i]]
195
+ i += 1
196
+ else
197
+ steps << ['+', to[j]]
198
+ j += 1
199
+ end
200
+ end
201
+ steps
202
+ end
203
+ end
204
+ end
205
+ end
206
+ end
@@ -0,0 +1,194 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'yaml'
4
+
5
+ module ApiRecipes
6
+ module CLI
7
+ class Upgrade
8
+ # The project in a directory, as `api_recipes upgrade` without arguments
9
+ # sees it: its Ruby files, the files that describe an api and the names
10
+ # of its apis. It reads files and never runs one, and it does not follow
11
+ # a symbolic link.
12
+ class Project
13
+ # Top-level folders that hold no code of the project.
14
+ SKIPPED = %w[vendor node_modules tmp log coverage public storage].freeze
15
+ # Folders skipped wherever they are.
16
+ SKIPPED_ANYWHERE = %w[node_modules].freeze
17
+ # Top-level folders whose YAML files are fixtures, not the configuration.
18
+ NO_CONFIGURATION = %w[spec test features].freeze
19
+ RUBY = /\.(rb|rake)\z/
20
+ YAML_FILE = /\.(yml|yaml)(\.erb)?\z/
21
+ # The line of a file that ERB shapes, which cannot be parsed: enough
22
+ # to report it.
23
+ ENDPOINTS_LINE = /^[ \t]+endpoints:[ \t]*(#.*)?$/
24
+ DECLARATION = /^[ \t]*api[ \t(]+:([A-Za-z_]\w*)(?:.*?\bas:[ \t]*[:'"]([A-Za-z_]\w*))?/
25
+ # A file larger than this is not a description of an api.
26
+ LARGEST = 2 * 1024 * 1024
27
+ # More values than a description holds: aliases make them from a few lines.
28
+ MAX_VALUES = 200_000
29
+
30
+ # api: the name given to `api`; method: the name it is called by.
31
+ Declared = Data.define(:file, :line, :api, :method)
32
+
33
+ # Paths relative to root, sorted. warnings: what could not be read.
34
+ attr_reader :ruby_files, :config_files, :warnings
35
+
36
+ # Whether data holds no more than limit values, aliases counted each
37
+ # time they are used. It stops as soon as the limit is passed.
38
+ def self.within?(data, limit, seen = [0])
39
+ seen[0] += 1
40
+ return false if seen[0] > limit
41
+
42
+ case data
43
+ when Hash then data.all? { |key, inner| within?(key, limit, seen) && within?(inner, limit, seen) }
44
+ when Array then data.all? { |inner| within?(inner, limit, seen) }
45
+ else true
46
+ end
47
+ end
48
+
49
+ def initialize(root = '.')
50
+ @root = root
51
+ @ruby_files = []
52
+ @config_files = []
53
+ @warnings = []
54
+ @texts = {}
55
+ @described = []
56
+ walk(nil)
57
+ end
58
+
59
+ # Rails and most applications load ActiveSupport, which defines the
60
+ # Hash methods that api_recipes 2.x also added.
61
+ def active_support?
62
+ lock = File.join(@root, 'Gemfile.lock')
63
+ File.file?(lock) && File.foreach(lock).any? { |line| line.match?(/\A\s+activesupport \(/) }
64
+ rescue SystemCallError, ArgumentError
65
+ false
66
+ end
67
+
68
+ # The text of a file of the project, or nil when it is not text.
69
+ def text(file)
70
+ return @texts[file] if @texts.key?(file)
71
+
72
+ @texts[file] = read(file)
73
+ end
74
+
75
+ # The names an api is called by: those the files describe, and those
76
+ # given to `api` in the code, with `as:` when there is one.
77
+ def api_names
78
+ @api_names ||= (described + declarations.map(&:method)).uniq.sort
79
+ end
80
+
81
+ # The apis the files of the project describe.
82
+ def described = @described.uniq
83
+
84
+ # Where the code declares an api: a line that starts with `api :name`.
85
+ def declarations
86
+ @declarations ||= @ruby_files.flat_map do |file|
87
+ found = []
88
+ text(file).to_s.each_line.with_index(1) do |line, number|
89
+ match = DECLARATION.match(line)
90
+ found << Declared.new(file: file, line: number, api: match[1], method: match[2] || match[1]) if match
91
+ end
92
+ found
93
+ end
94
+ end
95
+
96
+ # The declarations of an api that no file found here describes, and
97
+ # that do not describe it themselves.
98
+ def undescribed
99
+ return [] if @ruby_files.any? { |file| text(file).to_s.include?('apis_configs') }
100
+
101
+ declarations.reject do |declared|
102
+ described.include?(declared.api) || text(declared.file).to_s.lines[declared.line - 1].to_s.match?(/\b(endpoints|host):/)
103
+ end
104
+ end
105
+
106
+ # Whether the code of a Ruby file names the gem or calls one of the
107
+ # apis. Comment lines are not code.
108
+ def uses_gem?(text)
109
+ code = text.each_line.reject { |line| line.lstrip.start_with?('#') }.join
110
+ return true if code.match?(/\bApiRecipes\b/)
111
+
112
+ names = api_names
113
+ !names.empty? && code.match?(%r{(?<![\w/])(?:#{names.map { |name| Regexp.escape(name) }.join('|')})\b[ \t]*(?:\.[a-z_]|\[)})
114
+ end
115
+
116
+ private
117
+
118
+ def walk(directory)
119
+ entries = Dir.children(directory ? File.join(@root, directory) : @root).sort
120
+ entries.each do |name|
121
+ next if name.start_with?('.') || SKIPPED_ANYWHERE.include?(name)
122
+ next if directory.nil? && SKIPPED.include?(name)
123
+
124
+ relative = directory ? File.join(directory, name) : name
125
+ full = File.join(@root, relative)
126
+ next if File.symlink?(full)
127
+
128
+ if File.directory?(full)
129
+ walk(relative)
130
+ elsif File.file?(full)
131
+ keep(relative, name)
132
+ end
133
+ end
134
+ rescue SystemCallError => e
135
+ @warnings << "#{directory || @root}: cannot read (#{e.class.name.split('::').last})"
136
+ end
137
+
138
+ def keep(relative, name)
139
+ if RUBY.match?(name)
140
+ @ruby_files << relative
141
+ elsif name.end_with?(Internals::Recipe::SUFFIX)
142
+ @config_files << relative
143
+ @described.concat(apis_in(text(relative)) || [])
144
+ elsif YAML_FILE.match?(name) && !NO_CONFIGURATION.include?(relative.split('/').first)
145
+ names = apis_in(text(relative))
146
+ return if names.nil?
147
+
148
+ @config_files << relative
149
+ @described.concat(names)
150
+ end
151
+ end
152
+
153
+ # The names of the apis that text describes, or nil when it describes
154
+ # none. An api is a name with endpoints, each with its options or with
155
+ # none. Tags are read as a word, never run.
156
+ def apis_in(text)
157
+ return nil if text.nil? || !text.include?('endpoints')
158
+
159
+ plain = text.gsub(/<%#.*?%>/m, '').gsub(/<%=.*?%>/m, 'erb')
160
+ return (ENDPOINTS_LINE.match?(text) ? [] : nil) if plain.gsub('<%%', '').include?('<%')
161
+
162
+ data = YAML.safe_load(plain, permitted_classes: [Symbol], aliases: true)
163
+ return nil unless data.is_a?(Hash) && self.class.within?(data, MAX_VALUES)
164
+
165
+ names = data.select { |_, options| api?(options) }.keys.map(&:to_s)
166
+ names.empty? ? nil : names
167
+ rescue Psych::Exception, SystemStackError
168
+ ENDPOINTS_LINE.match?(text) ? [] : nil
169
+ end
170
+
171
+ def api?(options)
172
+ return false unless options.is_a?(Hash)
173
+
174
+ endpoints = options['endpoints'] || options[:endpoints]
175
+ endpoints.is_a?(Hash) && endpoints.values.all? { |one| one.nil? || one.is_a?(Hash) }
176
+ end
177
+
178
+ def read(file)
179
+ full = File.join(@root, file)
180
+ return nil if File.size(full) > LARGEST
181
+
182
+ bytes = File.binread(full)
183
+ return nil if bytes.include?("\0")
184
+
185
+ text = bytes.force_encoding(Encoding::UTF_8)
186
+ text.valid_encoding? ? text : nil
187
+ rescue SystemCallError => e
188
+ @warnings << "#{file}: cannot read (#{e.class.name.split('::').last})"
189
+ nil
190
+ end
191
+ end
192
+ end
193
+ end
194
+ end
@@ -0,0 +1,165 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ApiRecipes
4
+ module CLI
5
+ class Upgrade
6
+ # How `upgrade` shows its results: the same sections everywhere, and on
7
+ # a terminal colours, marks and lines that fit its width. The text it
8
+ # is given holds nothing a terminal obeys; it adds only its own marks.
9
+ class Screen
10
+ # The mark and the colour of each kind of finding, the worst first.
11
+ KINDS = { breaks: ['💥', 31], config: ['🧩', 35], check: ['👀', 33] }.freeze
12
+ WIDTHS = (60..110)
13
+
14
+ def initialize(out)
15
+ @out = out
16
+ @paint = Code::Paint.on?(out)
17
+ @width = @paint ? width_of(out) : nil
18
+ @blank = true
19
+ end
20
+
21
+ def paint? = @paint
22
+
23
+ # The title of a section. plain: false leaves it out where there are
24
+ # no colours, for lines that say by themselves what they are.
25
+ def section(mark, title, note = nil, plain: true)
26
+ gap
27
+ return unless @paint || plain
28
+
29
+ put(@paint ? "#{mark} #{style(title, 1)}#{note && " #{style(note, 2)}"}" : title)
30
+ gap if @paint
31
+ end
32
+
33
+ # A line of text of a section.
34
+ def line(text)
35
+ @paint ? wrapped(text, ' ', ' ').each { |one| put(one) } : put(text)
36
+ end
37
+
38
+ # An entry of a list. What comes before its first colon is what the
39
+ # entry is about.
40
+ def item(text, mark = nil)
41
+ return put(" #{mark || '-'} #{text}") unless @paint
42
+
43
+ first = " #{mark || '•'} "
44
+ wrapped(text, first, ' ' * first.length, bold: text.index(': ') || 0).each { |one| put(one) }
45
+ end
46
+
47
+ # A finding, and under it the code that takes the place of the line.
48
+ def finding(kind, where, message, hint = nil)
49
+ if @paint
50
+ mark, colour = KINDS.fetch(kind, ['•', 0])
51
+ put(" #{mark} #{style(kind.to_s.ljust(6), 1, colour)} #{style(where, 1)}")
52
+ wrapped(message, ' ', ' ').each { |one| put(one) }
53
+ else
54
+ put("#{where}: [#{kind}] #{message}")
55
+ end
56
+ hint ? code(hint) : (gap if @paint)
57
+ end
58
+
59
+ # Code to paste, with an empty line before and after it.
60
+ def code(lines, kind = :ruby)
61
+ indent = ' ' * (@paint ? 6 : 4)
62
+ gap
63
+ lines.each { |one| put(one.empty? ? '' : "#{indent}#{@paint ? Code::Paint.public_send(kind, one) : one}") }
64
+ gap
65
+ end
66
+
67
+ # What changes in a file: the lines taken out and the lines added,
68
+ # with the lines around them. A character that a terminal would
69
+ # obey is shown as a question mark.
70
+ def diff(file, old, new)
71
+ Diff.hunks(old, new).each do |first, lines|
72
+ gap
73
+ put(@paint ? " #{style("#{file}:#{first}", 1)}" : "#{file}:#{first}")
74
+ lines.each do |sign, text|
75
+ shown = "#{@paint ? ' ' : ''}#{sign} #{text.gsub(Code::UNSAFE, '?')}".rstrip
76
+ put(@paint ? style(shown, { '-' => 31, '+' => 32 }.fetch(sign, 2)) : shown)
77
+ end
78
+ end
79
+ gap
80
+ end
81
+
82
+ # A file that a change creates: its first lines, and how many follow.
83
+ def created(file, text, limit = 30)
84
+ lines = text.lines(chomp: true)
85
+ gap
86
+ put(@paint ? " #{style("#{file} (new file)", 1)}" : "#{file} (new file)")
87
+ lines.first(limit).each do |line|
88
+ shown = "#{@paint ? ' ' : ''}+ #{line.gsub(Code::UNSAFE, '?')}".rstrip
89
+ put(@paint ? style(shown, 32) : shown)
90
+ end
91
+ more = lines.size - limit
92
+ put("#{@paint ? ' ' : ''} ... and #{more} more line#{'s' unless more == 1}") if more.positive?
93
+ gap
94
+ end
95
+
96
+ # A file that a change deletes.
97
+ def deleted(file)
98
+ gap
99
+ put(@paint ? " #{style("#{file} (deleted)", 1, 31)}" : "#{file} (deleted)")
100
+ gap
101
+ end
102
+
103
+ # Asks, and tells whether the answer was yes.
104
+ def ask(question, input)
105
+ @out.print(@paint ? " #{style(question, 1)} [y/N] " : "#{question} [y/N] ")
106
+ @out.flush if @out.respond_to?(:flush)
107
+ answer = input.gets.to_s.strip.downcase
108
+ @blank = false
109
+ %w[y yes].include?(answer)
110
+ end
111
+
112
+ # The last line of the results: how many findings, and of which kinds.
113
+ def summary(text, counts)
114
+ gap
115
+ return put(text) unless @paint
116
+ return put("✅ #{style(text, 1, 32)}") if counts.empty?
117
+
118
+ worst = KINDS.keys.find { |kind| counts.key?(kind) } || :check
119
+ kinds = KINDS.keys.select { |kind| counts.key?(kind) }.map { |kind| style("#{counts[kind]} #{kind}", KINDS[kind].last) }
120
+ put("#{KINDS[worst].first} #{style(text, 1, KINDS[worst].last)} #{kinds.join(style(' · ', 2))}")
121
+ end
122
+
123
+ # One empty line, and never two.
124
+ def gap
125
+ put('') unless @blank
126
+ end
127
+
128
+ private
129
+
130
+ def put(text)
131
+ @out.puts(text)
132
+ @blank = text.empty?
133
+ end
134
+
135
+ def style(text, *codes) = "\e[#{codes.join(';')}m#{text}\e[0m"
136
+
137
+ def width_of(out)
138
+ require 'io/console'
139
+ columns = out.respond_to?(:winsize) ? out.winsize[1].to_i : 0
140
+ columns.zero? ? 80 : columns.clamp(WIDTHS.min, WIDTHS.max)
141
+ rescue StandardError
142
+ 80
143
+ end
144
+
145
+ # text on lines that fit the width, the first after first and the
146
+ # others after rest, with its first bold characters in bold.
147
+ def wrapped(text, first, rest, bold: 0)
148
+ room = @width - first.length
149
+ lines = []
150
+ text.split(' ').each do |word|
151
+ if lines.empty? || lines.last.length + 1 + word.length > room then lines << word.dup
152
+ else lines.last << ' ' << word
153
+ end
154
+ end
155
+ at = 0
156
+ lines.each_with_index.map do |one, index|
157
+ strong = (bold - at).clamp(0, one.length)
158
+ at += one.length + 1
159
+ "#{index.zero? ? first : rest}#{strong.zero? ? one : "#{style(one[0, strong], 1)}#{one[strong..]}"}"
160
+ end
161
+ end
162
+ end
163
+ end
164
+ end
165
+ end