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
@@ -1,108 +1,186 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require 'securerandom'
4
+ require 'api_recipes/cli/upgrade/project'
5
+ require 'api_recipes/cli/upgrade/screen'
6
+ require 'api_recipes/cli/upgrade/fix'
7
+ require 'api_recipes/cli/upgrade/tree_rules'
8
+
3
9
  module ApiRecipes
4
10
  module CLI
5
11
  # Looks for what api_recipes 3.0 removed or changed. It reads files and
6
12
  # never writes one. A result carries the file, the line, the kind and a fixed
7
13
  # message: never the text of the line, which can hold a secret.
8
14
  class Upgrade
9
- Finding = Data.define(:file, :line, :kind, :message)
15
+ # hint: lines of code shown under the finding, or nil.
16
+ Finding = Data.define(:file, :line, :kind, :message, :hint) do
17
+ def initialize(file:, line:, kind:, message:, hint: nil) = super
18
+ end
10
19
 
11
- Rule = Data.define(:kind, :pattern, :message)
20
+ # general: the pattern also matches code that has nothing to do with the
21
+ # gem. In a whole project such a rule is applied only to the files that
22
+ # use the gem.
23
+ # fix: which code to paste the line gives, when it gives one.
24
+ Rule = Data.define(:kind, :pattern, :message, :general, :fix) do
25
+ def initialize(kind:, pattern:, message:, general: false, fix: nil) = super
26
+ end
12
27
 
13
28
  RULES = [
14
- Rule.new(:breaks, /\.route\b/, 'endpoint.route was removed: use response.fill or endpoint.definition'),
29
+ Rule.new(:breaks, /\.route\b/, 'endpoint.route was removed: use response.fill or endpoint.definition', false, :route),
15
30
  Rule.new(:breaks, /RouteNameClashWithExistentMethod/,
16
31
  'this error class was removed: a name clash is now a warning'),
17
32
  Rule.new(:breaks, /RouteAndResourceNamesClashError|MissingRouteAttribute|ProvidedObjectNotAsResponseData|NoConfigurationGivenForEndpoint/,
18
33
  'this error class was removed: nothing raised it, so the rescue clause can go'),
19
- Rule.new(:breaks, /\.base_configs\b/, 'Api#base_configs was removed: use api.definition'),
34
+ Rule.new(:breaks, /\.base_configs\b/, 'Api#base_configs was removed: use api.definition', false, :base_configs),
20
35
  Rule.new(:breaks, /ApiRecipes::Route\b/, 'ApiRecipes::Route was removed: a request is sent with run'),
21
36
  Rule.new(:breaks, /ApiRecipes::Settings\b/,
22
37
  'ApiRecipes::Settings was removed: the defaults are listed in the README'),
23
38
  Rule.new(:breaks, /\bconfiguration\.setup\b/,
24
39
  'configuration.setup was removed: configure loads the configuration'),
25
- Rule.new(:breaks, /ApiRecipes\.print_urls/, 'use config.print_urls inside ApiRecipes.configure'),
40
+ Rule.new(:breaks, /\.apis_files_paths\b/,
41
+ 'apis_files_paths was removed: an api is described by a portable recipe, loaded with recipes_paths. ' \
42
+ 'Run `api_recipes convert`: it moves every description of the project to a recipe and changes this configuration'),
43
+ Rule.new(:breaks, /ApiRecipes\.print_urls/, 'use config.print_urls inside ApiRecipes.configure', false, :print_urls),
26
44
  Rule.new(:breaks, /_aprcps_|set_authorization_for_api|set_basic_auth_for_api|copy_global_authorizations_to_api/,
27
45
  'internal method removed'),
28
46
  Rule.new(:breaks, /\bApiRecipes((\.|::)\w+|\[[^\]]*\])\.(authorization|basic_auth)\s*(\|\|)?=(?![=~])/,
29
47
  'a credential of the whole application is given to ApiRecipes.configure, as ' \
30
- 'config.values = { name: { authorization: ... } }: this writer now raises'),
48
+ 'config.values = { name: { authorization: ... } }: this writer now raises', false, :global_writer),
31
49
  Rule.new(:check, /(?<!\bApiRecipes)\.\w+\.(authorization|basic_auth)\s*(\|\|)?=(?![=~])/,
32
50
  'authorization= and basic_auth= now work on an object only: on a class they raise, ' \
33
- 'give the credential to `api :name, authorization: ...`, or to with(...) for one request'),
51
+ 'give the credential to `api :name, authorization: ...`, or to with(...) for one request', false, :writer),
34
52
  Rule.new(:check, /url_encode|CGI\.escape|encode_www_form_component/,
35
- 'path parameters are now encoded by ApiRecipes: remove manual encoding of values passed to endpoints'),
53
+ 'path parameters are now encoded by ApiRecipes: remove manual encoding of values passed to endpoints', true),
36
54
  Rule.new(:check, /\brescue\s*(=>.*)?$|rescue StandardError/,
37
- 'a bare rescue now catches ApiRecipes errors too'),
38
- Rule.new(:check, /\bfollow:/, 'credentials are no longer sent to another origin after a redirect'),
55
+ 'a bare rescue now catches ApiRecipes errors too', true),
56
+ Rule.new(:check, /\bfollow:/, 'credentials are no longer sent to another origin after a redirect', true),
39
57
  Rule.new(:check, /\bresponse\.request\b/,
40
58
  'response.request was removed, because the request holds the credentials: ' \
41
- 'read response.uri, or response.original_response'),
59
+ 'read response.uri, or response.original_response', true, :request),
42
60
  Rule.new(:check, /\.(deep_merge|deep_symbolize_keys|deep_stringify_keys|symbolize_keys|stringify_keys|extract_options!|assert_valid_keys)\b/,
43
61
  'this method came from api_recipes 2.x unless ActiveSupport is loaded: ' \
44
- 'define it or add ActiveSupport')
62
+ 'define it or add ActiveSupport', true)
45
63
  ].freeze
46
64
 
65
+ # The rule about the Hash methods that ActiveSupport defines too.
66
+ HASH_METHODS = RULES.last
67
+
68
+ # The rules on lines about a credential assigned with a writer.
69
+ WRITER_RULES = RULES.select { |rule| %i[global_writer writer].include?(rule.fix) }.freeze
70
+
71
+ # The rule about a rescue that names no class, and what the change
72
+ # that the command offers for it means.
73
+ BARE_RESCUE = RULES.find { |rule| rule.message.start_with?('a bare rescue') }
74
+ RESCUE_NOTE = ['In 2.x this rescue did not catch the errors of api_recipes: they went on to the code that called. ' \
75
+ 'In 3.0 it catches them.',
76
+ 'y: keep what 2.x did. The errors of api_recipes are raised again before this rescue sees them',
77
+ 'n: leave the code as it is. This rescue handles the errors of api_recipes too'].freeze
78
+
79
+ # What stands for the value of an ERB tag in a file that is checked
80
+ # without running its code.
81
+ # Options whose value is a mapping: a tag that gives one gives a part
82
+ # of the structure, which is not guessed.
83
+ CONTAINERS = %w[variables endpoints default_headers default_params auth recipe resource].freeze
84
+
85
+ # What a line assigns, read without running it, to give the code to paste.
86
+ WRITTEN = '\\s*(?:\\|\\|)?=(?![=~])\\s*(?<code>.+)\\z'
87
+ FIXES = {
88
+ print_urls: /\bApiRecipes\.print_urls#{WRITTEN}/,
89
+ global_writer: /\bApiRecipes(?:(?:\.|::)(?<api>\w+)|\[\s*[:'"](?<api>\w+)['"]?\s*\])\.(?<key>authorization|basic_auth)#{WRITTEN}/,
90
+ writer: /(?<![^\s(=,])(?<receiver>[\w.@:\[\]'"]+)\.(?<api>\w+)\.(?<key>authorization|basic_auth)#{WRITTEN}/,
91
+ base_configs: /(?<![^\s(=,])(?<receiver>[\w.@:\[\]'"]+)\.base_configs\b/,
92
+ route: /\.route\.fill\((?<code>.*)\)/
93
+ }.freeze
94
+ # Code longer than this is not copied into the code to paste.
95
+ MAX_CODE = 300
96
+
47
97
  SILENT_CHANGES = [
48
- 'path parameters encoded by hand: %2F would become %252F, remove the encoding',
49
- 'a / inside a path parameter to cover several segments: use *name or two placeholders',
98
+ 'a value of a path parameter that is already encoded when it arrives: %2F would become %252F. The gem warns when it sees one',
99
+ 'a / inside the value of a path parameter to cover several segments: use *name or two placeholders. The gem warns when it sees one',
50
100
  'debug logs or print_urls output read from STDOUT: set log_to and log_level',
51
- 'a bare rescue around a call: it now catches the errors of the gem too',
52
- 'credentials assigned on an instance: they now take effect',
53
- 'a credential assigned through a variable that holds the api of the module or of a class (api = ApiRecipes.github, then api.authorization = ...), inside the body of a class (github.authorization = ...), with send, or on a statement split over two lines: the writer raises, give it to config.values or to `api :name, authorization: ...`',
101
+ 'a bare rescue in a file that does not name the gem, around code that calls it somewhere else: it now catches the errors of the gem too',
54
102
  'the response body read from the message of a verify_with error: read it from error.response',
55
- 'a block passed to run whose return value is used: it is now the Response',
56
- 'apis_configs assigned after the files to discard them: do not assign the files',
57
- 'timeout, on_bad_code, mime_type or verify_with on an endpoint that contains other endpoints: one that does not set the option now finds it there, before the api',
58
- 'an endpoint called with, definition, authorization, basic_auth or variables (on an api), or run, url, with or definition (on an endpoint): reach it with []; the warning at configuration reports it',
59
103
  'fill with private setters, or code that relies on swallowed errors: make the setters public, handle the errors',
60
- 'follow: true together with a credential: the credential no longer follows to another host',
61
- 'a class with its own host, protocol or port that relied on the global credential: set the credential on the class',
62
104
  'cookies set by a server during a redirect chain: they are no longer carried to the next hop',
63
- 'api names that are methods of Kernel, such as :open or :format: they raise ApiNameClashError, use as:',
64
105
  'Endpoint#name, #params, #children, #api and Api#name, #configs, #object were removed: use definition (a search cannot tell them from other methods called like that)',
65
106
  'an object restored from a serialized form (Marshal, YAML) has no credential: assign it again',
66
107
  'response.uri leaves out the credential query parameter when the api declares auth type query',
67
108
  'a redirect to a host with non-ASCII characters needs the addressable gem: without it the request raises InvalidUrl',
68
- 'a base_url with a placeholder in a configuration given as a Hash: it is now an error, use a variable',
69
- 'response.request was removed, whatever the name of the variable that holds the response: the request holds the credentials, read response.uri or response.original_response',
70
- 'response.to_s returns the body, as the http.rb response does: it was the default text of the object',
71
- 'a credential that is not a String, such as a Symbol or a number: it raises InvalidCredential, convert it with to_s',
72
- 'a {word} in a value of default_headers in a configuration given as a Hash: it is now a variable and must be declared',
73
- 'a {word} in the path of an endpoint in a configuration given as a Hash: it is now a variable and must be declared; to keep the braces as text write \\{word}',
74
- 'respond_to? on a response now tells the truth: it answers true for the methods the response forwards and false for the others',
75
- 'serializing an Api, an Endpoint or a Response raises TypeError: serialize response.data or response.body.to_s',
76
- 'a class that includes ApiRecipes and uses a top-level constant named Error, Internals, VERSION or like a new error class of the gem (such as ConfigurationError or InvalidUrl): it now finds the gem\'s constant first, write ::Name in that class; Route and Settings no longer exist, so a top-level Route or Settings is found again'
109
+ 'a response that a method receives as an argument: request was removed (read uri or original_response), to_s returns the body, ' \
110
+ 'respond_to? tells the truth. Those that the code takes from run are found'
77
111
  ].freeze
78
112
 
79
113
  # Problems met while reading, as "<file>: <reason>". They are not findings:
80
114
  # the file could not be checked.
81
115
  attr_reader :warnings
82
116
 
83
- def initialize(paths, config: [], erb: false)
117
+ # What was checked and how, said after the findings. Not findings.
118
+ attr_reader :notes
119
+
120
+ # project: the Project the paths and the files were found in, when the
121
+ # command was given none.
122
+ # code: false leaves out the code to paste, as in a CI whose output is kept.
123
+ def initialize(paths, config: [], erb: false, project: nil, code: true)
124
+ @code = code
84
125
  @paths = Array(paths)
85
126
  @configs = Array(config)
86
127
  @erb = erb
128
+ @project = project
87
129
  @warnings = []
130
+ @notes = []
131
+ # What stands for the value of an ERB tag in a file that is checked
132
+ # without running its code: random, so that no file can write it.
133
+ @erb_value = "API_RECIPES_ERB_VALUE_#{SecureRandom.hex(6)}"
134
+ end
135
+
136
+ # The command without arguments: the project in the current directory.
137
+ def self.for_project(project, erb: false, code: true)
138
+ new(project.ruby_files, config: project.config_files, erb: erb, project: project, code: code)
88
139
  end
89
140
 
90
141
  def run
91
- @warnings = []
92
- findings = @paths.flat_map { |path| scan_path(path) }
93
- findings + @configs.flat_map { |file| check_config(file) }
142
+ @warnings = @project ? @project.warnings.dup : []
143
+ @notes = []
144
+ @uses = 0
145
+ @startup = []
146
+ @configure = {}
147
+ @direct = {}
148
+ @rescues = []
149
+ findings = with_request_hints(@paths.flat_map { |path| scan_path(path) })
150
+ findings += @configs.flat_map { |file| check_config(file) }
151
+ @notes = scope + @notes if @project
152
+ findings
94
153
  end
95
154
 
96
- # Prints the results on out and the warnings on err. Returns the exit code.
97
- def report(out, err)
155
+ # Prints the results on out and the warnings on err. Returns the exit
156
+ # code. What needs an answer comes last, where a terminal stops: what
157
+ # was checked, what the command cannot find, the findings, what to do.
158
+ # input: where the answers come from. On a terminal the command offers
159
+ # the changes it can make by itself, one at a time.
160
+ def report(out, err, input: nil)
98
161
  findings = run
99
- findings.each { |finding| out.puts format_finding(finding) }
100
- out.puts
101
- out.puts 'What this command cannot find'
102
- SILENT_CHANGES.each { |change| out.puts " - #{change}" }
103
- out.puts
162
+ screen = Screen.new(out)
163
+ changed = @code && Fix.asks?(input, out) ? offered(screen, input, out, err) : []
164
+ findings = look_again unless changed.empty?
165
+ unless @notes.empty?
166
+ screen.section('🔎', 'What was checked', plain: false)
167
+ @notes.each { |note| screen.line(note) }
168
+ end
169
+ screen.section('🙈', 'What this command cannot find', "#{SILENT_CHANGES.size} changes")
170
+ SILENT_CHANGES.each { |change| screen.item(change) }
171
+ unless findings.empty?
172
+ screen.section('📌', 'Findings', plain: false)
173
+ findings.each { |finding| screen.finding(finding.kind, where(finding), finding.message, @code ? finding.hint : nil) }
174
+ end
175
+ pasted = @code && code_to_paste(screen)
176
+ unless changed.empty?
177
+ screen.section('✅', 'Changed in the project')
178
+ changed.each { |file, what| screen.item("#{what} #{shown_path(file)}") }
179
+ screen.line('Every change is in `git diff`.')
180
+ end
104
181
  @warnings.each { |warning| err.puts warning }
105
- out.puts summary(findings.size) if findings.any? || @warnings.empty?
182
+ screen.summary(summary(findings.size), findings.group_by(&:kind).transform_values(&:size)) if findings.any? || @warnings.empty?
183
+ what_to_do(screen, findings, pasted)
106
184
  return 1 if findings.any?
107
185
 
108
186
  @warnings.empty? ? 0 : 2
@@ -110,22 +188,327 @@ module ApiRecipes
110
188
 
111
189
  private
112
190
 
191
+ CONVERT_NOTE = ['3.0 loads only portable recipes. The description becomes one, and what its ERB tags gave is given by ' \
192
+ 'config.values, in the file that calls ApiRecipes.configure.',
193
+ 'y: move the api to a recipe now',
194
+ 'n: leave it, and run `api_recipes convert` later'].freeze
195
+
196
+ # Offers each change the command can make: first the apis that move to
197
+ # a portable recipe, then the others. The project is read again after
198
+ # a change that was made. Returns the files that were written.
199
+ def offered(screen, input, out, err)
200
+ ours = {}
201
+ fix = Fix.new(screen, input, shown: method(:shown_path), ours: ours)
202
+ declined = []
203
+ written = {}
204
+ loop do
205
+ # Only the whole project is moved to recipes: given some files, the
206
+ # command does not know the others.
207
+ key, title, migration = (@project ? conversions(ours, out, err) : []).find { |one| !declined.include?(one.first) }
208
+ if key
209
+ declined << key
210
+ preview = migration.preview
211
+ next unless fix.confirm(title, CONVERT_NOTE, preview) && migration.finish.zero?
212
+
213
+ preview[:created].each_key { |file| written[file] = 'created' }
214
+ preview[:edited].each_key { |file| written[file] ||= 'edited' }
215
+ preview[:deleted].each { |file| written[file] = 'deleted' }
216
+ look_again
217
+ next
218
+ end
219
+ change = changes.find { |one| !declined.include?(one.key) }
220
+ break unless change
221
+
222
+ files = fix.offer(change)
223
+ declined << change.key
224
+ next unless files
225
+
226
+ files.each { |file| written[file] ||= 'edited' }
227
+ look_again
228
+ end
229
+ written
230
+ end
231
+
232
+ # The project as the changes left it: its files are found again.
233
+ def look_again
234
+ if @project
235
+ @project = Project.new
236
+ @paths = @project.ruby_files
237
+ @configs = @project.config_files
238
+ @specific = @all = nil
239
+ end
240
+ run
241
+ end
242
+
243
+ # [[key, title, migration]] for each api that a file of the project
244
+ # describes and that the command can move to a portable recipe by
245
+ # itself. The others stay findings: `api_recipes convert` says why.
246
+ def conversions(ours, out, err)
247
+ described = @configs.reject { |file| file.end_with?(Internals::Recipe::SUFFIX) }
248
+ described.sort.flat_map do |file|
249
+ names = begin
250
+ Convert.shape(File.read(file)).keys
251
+ rescue Convert::Refused, Psych::Exception, SystemCallError
252
+ []
253
+ end
254
+ names.filter_map do |name|
255
+ result = Convert.new(file, name: names.size > 1 ? name : nil).call
256
+ migration = Convert::Migration.new(result, file, out: out, err: err, written: ours)
257
+ next unless migration.prepare.empty?
258
+
259
+ [[:convert, file, result.name], "Move the api #{Recipes::Summary.shown(result.name, 100)} to a portable recipe", migration]
260
+ rescue Convert::Refused, Convert::Unusable, SystemStackError
261
+ nil
262
+ end
263
+ end
264
+ end
265
+
266
+ # The changes this command is sure of, in the order they are offered.
267
+ # The rescues of a file come from the last one, so that a change does
268
+ # not move the ones still to offer.
269
+ def changes
270
+ startup_changes + @rescues.sort_by { |item| [item[:file], -item[:line]] }.filter_map { |item| rescue_change(item) }
271
+ end
272
+
273
+ # A value that a line gives when the application starts moves into the
274
+ # block of ApiRecipes.configure, when one file has it and it is read whole.
275
+ def startup_changes
276
+ file, text = @configure.size == 1 ? @configure.first : nil
277
+ block = Code::ConfigureBlock.in(text)
278
+ return [] unless block && !block.problem
279
+
280
+ urls = @startup.select { |item| item[:api].nil? }
281
+ values = @startup.select { |item| item[:api] }
282
+ found = [without_files(file, text, block)]
283
+ if urls.size == 1 && !block.assigned_anywhere?(:print_urls)
284
+ found << change(:print_urls, 'Move print_urls into the block of ApiRecipes.configure', urls, file, text, block,
285
+ ["#{block.config}.print_urls = #{urls.first[:code]}"])
286
+ end
287
+ # Two credentials for one api, or one given twice: configure would
288
+ # refuse the first, and which one 2.x kept depends on the order.
289
+ twice = values.group_by { |item| item[:api] }.any? { |_, list| list.size > 1 }
290
+ unless values.empty? || twice || block.assigned_anywhere?(:values)
291
+ found << change(:values, 'Give the credentials of the application to ApiRecipes.configure, as config.values', values, file, text,
292
+ block, ["#{block.config}.values = {", *entries_of(values).map { |entry| " #{entry}" }, '}'])
293
+ end
294
+ found.compact
295
+ end
296
+
297
+ # A rescue that names no class gets, before it, a rescue of the errors
298
+ # of the gem that raises them again: what 2.x did. nil for a rescue
299
+ # that does not start a line of its own, as in `x rescue y`.
300
+ def rescue_change(item)
301
+ text = read_ruby(item[:file])
302
+ tree = text && Code.tree(text)
303
+ clause = tree && rescue_at(tree, item[:line])&.last
304
+ line = text && text.lines[item[:line] - 1]
305
+ return nil unless clause && line.match?(/\A[ \t]*rescue\b/) && names_gem?(text)
306
+ return nil unless clause.exceptions.empty? || clause.exceptions.any? { |one| one.slice.delete_prefix('::') == 'StandardError' }
307
+
308
+ indent = line[/\A[ \t]*/]
309
+ written = text.lines.insert(item[:line] - 1, "#{indent}rescue ApiRecipes::Error\n", "#{indent} raise\n").join
310
+ return nil unless gem_errors_handled?(written, item[:line] + 2)
311
+
312
+ # Counted from the end of the file, the place of a rescue stays the
313
+ # same when a change is made above it.
314
+ Fix::Change.new([:rescue, item[:file], text.lines.size - item[:line]],
315
+ "Keep the errors of ApiRecipes out of the rescue at #{shown_path(item[:file])}:#{item[:line]}, as in 2.x",
316
+ { item[:file] => written }, RESCUE_NOTE)
317
+ end
318
+
319
+ # The rescue clause that starts at line number, after the clauses of
320
+ # the same begin that come before it: [[earlier clauses], clause].
321
+ def rescue_at(tree, number)
322
+ Code.nodes(tree) { |node| node.is_a?(Prism::BeginNode) && node.rescue_clause }.each do |owner|
323
+ earlier = []
324
+ clause = owner.rescue_clause
325
+ while clause
326
+ return [earlier, clause] if clause.location.start_line == number
327
+
328
+ earlier << clause
329
+ clause = clause.compact_child_nodes.find { |child| child.is_a?(Prism::RescueNode) }
330
+ end
331
+ end
332
+ nil
333
+ end
334
+
335
+ # Whether a clause before the one at line number catches the errors of
336
+ # the gem first: one that names ApiRecipes::Error, Exception or
337
+ # StandardError, or names no class.
338
+ def gem_errors_handled?(text, number)
339
+ tree = Code.tree(text)
340
+ earlier = tree && rescue_at(tree, number)&.first
341
+ return false unless earlier
342
+
343
+ earlier.any? do |clause|
344
+ clause.exceptions.empty? || clause.exceptions.any? { |one| %w[ApiRecipes::Error Exception StandardError].include?(one.slice.delete_prefix('::')) }
345
+ end
346
+ end
347
+
348
+ # Whether the code of a file names the gem: a change is made only there.
349
+ def names_gem?(text)
350
+ return @project.uses_gem?(text) if @project
351
+
352
+ text.each_line.reject { |line| line.lstrip.start_with?('#') }.join.match?(/\bApiRecipes\b/)
353
+ end
354
+
355
+ # apis_files_paths goes out of the block of configure once no file of
356
+ # the project describes an api: 3.0 refuses the option.
357
+ def without_files(file, text, block)
358
+ given = block.assignments(:apis_files_paths)
359
+ # Only in the whole project the command knows that no description is left.
360
+ return nil if !@project || given.empty? || @configs.any? { |one| !one.end_with?(Internals::Recipe::SUFFIX) }
361
+ # The lines of a heredoc come after the statement that opens it.
362
+ return nil if given.any? { |node| !Code.nodes(node) { |one| one.respond_to?(:opening_loc) && one.opening_loc&.slice&.start_with?('<<') }.empty? }
363
+
364
+ lines = text.lines
365
+ gone = given.flat_map do |node|
366
+ first = node.location.start_line
367
+ last = node.location.end_line
368
+ alone = lines[first - 1].b[0...node.location.start_column].strip.empty? && lines[last - 1].b[node.location.end_column..].to_s.strip.empty?
369
+ return nil unless alone
370
+
371
+ (first..last).to_a
372
+ end
373
+ written = lines.each_with_index.reject { |_, index| gone.include?(index + 1) }.map(&:first).join
374
+ Code.tree(written) ? Fix::Change.new(:files, 'Take apis_files_paths, which 3.0 refuses, out of the block of ApiRecipes.configure', { file => written }) : nil
375
+ end
376
+
377
+ # The texts of the files after the lines of items are taken out and
378
+ # added is written at the end of the block. nil when a line is not a
379
+ # whole statement of its own, or when a result is not valid Ruby.
380
+ def change(key, title, items, file, text, block, added)
381
+ texts = items.group_by { |item| item[:file] }.to_h { |path, list| [path, [path == file ? text : read_ruby(path), list.map { |item| item[:line] }]] }
382
+ texts[file] ||= [text, []]
383
+ return nil unless texts.all? { |path, (content, lines)| content && lines.all? { |number| movable?(content, number, path == file ? block : nil, lines) } }
384
+
385
+ written = texts.to_h do |path, (content, lines)|
386
+ kept = content.lines.each_with_index.reject { |_, index| lines.include?(index + 1) }
387
+ next [path, kept.map(&:first).join] unless path == file
388
+
389
+ inside = lines.select { |number| number.between?(block.first, block.last) }
390
+ now = block.lines(added, without: inside).map { |line| "#{line}\n" }
391
+ [path, kept.flat_map { |line, index| index + 1 == block.first ? now : (index + 1).between?(block.first, block.last) ? [] : [line] }.join]
392
+ end
393
+ written.values.all? { |content| Code.tree(content) } ? Fix::Change.new(key, title, written) : nil
394
+ end
395
+
396
+ MOVED = %i[print_urls= authorization= basic_auth=].freeze
397
+
398
+ # Whether line number of text holds one assignment of a value given
399
+ # when the application starts, and nothing else, whose value the block
400
+ # of configure would give the same: it reads no variable and no method
401
+ # of the file, and no other code that may prepare it
402
+ # runs before it: in the file of the block, none between the block and
403
+ # the line; in another file, which runs at another time, none at all.
404
+ # moved: the lines of the file that the change takes out.
405
+ def movable?(text, number, block, moved)
406
+ tree = Code.tree(text)
407
+ return false unless tree
408
+
409
+ statements = Code.nodes(tree) { |node| node.is_a?(Prism::StatementsNode) }.flat_map(&:body)
410
+ here = statements.select { |node| node.location.start_line == number && node.location.end_line == number }
411
+ return false unless here.size == 1 && text.lines[number - 1].strip == here.first.slice
412
+
413
+ value = assigned(here.first)
414
+ return false unless value && Code.nodes(value) { |one| local_value?(one) }.empty?
415
+
416
+ others = tree.statements.body.reject { |other| moved.include?(other.location.start_line) }
417
+ return others.empty? unless block
418
+ return true unless number > block.last
419
+
420
+ others.none? { |other| other.location.start_line > block.last && other.location.start_line < number }
421
+ end
422
+
423
+ # The value that node gives to one of the options moved, or nil.
424
+ def assigned(node)
425
+ if node.is_a?(Prism::CallNode) && MOVED.include?(node.name) && node.arguments&.arguments&.size == 1
426
+ node.arguments.arguments.first
427
+ elsif node.is_a?(Prism::CallOrWriteNode) && MOVED.include?(node.write_name)
428
+ node.value
429
+ end
430
+ end
431
+
432
+ # A value that only the place where it is written has.
433
+ def local_value?(node)
434
+ case node
435
+ when Prism::LocalVariableReadNode, Prism::InstanceVariableReadNode, Prism::ClassVariableReadNode, Prism::SelfNode,
436
+ Prism::SourceFileNode, Prism::SourceLineNode then true
437
+ when Prism::CallNode then node.receiver.nil? && !%i[[] !].include?(node.name)
438
+ else false
439
+ end
440
+ end
441
+
442
+ def entries_of(items)
443
+ entries = items.group_by { |item| item[:api] }.map do |api, list|
444
+ "#{api.match?(/\A[a-z_]\w*\z/) ? api : "\"#{api}\""}: { #{list.map { |item| "#{item[:key]}: #{item[:code]}" }.join(', ')} }"
445
+ end
446
+ entries.each_with_index.map { |entry, index| index == entries.size - 1 ? entry : "#{entry}," }
447
+ end
448
+
449
+ # What the person does with the results, in order.
450
+ def what_to_do(screen, findings, pasted)
451
+ counts = findings.group_by(&:kind).transform_values(&:size)
452
+ lines = ->(count) { "#{count} line#{'s' unless count == 1}" }
453
+ steps = []
454
+ described = @configs.reject { |file| file.end_with?(Internals::Recipe::SUFFIX) }
455
+ unless described.empty?
456
+ steps << "Run `api_recipes convert`: it moves the #{described.size == 1 ? 'description' : "#{described.size} descriptions"} of the " \
457
+ 'project to portable recipes, changes the configuration by itself and says what it did. 3.0 loads no other file'
458
+ end
459
+ other = (counts[:breaks] || 0) - findings.count { |finding| finding.kind == :breaks && (described.include?(finding.file) || finding.message.start_with?('apis_files_paths')) }
460
+ steps << "Fix the #{lines.call(other)} marked breaks#{' that convert does not take care of' unless described.empty?}: that code stops working, and each line says what to use instead#{'. The code to paste, above, does it for the values given when the application starts' if pasted}" if other.positive?
461
+ steps << "Correct what is marked config (#{counts[:config]}): each is a problem in a file that describes an api" if counts[:config]
462
+ steps << "Read the #{lines.call(counts[:check])} marked check: the result changes, and only you can tell whether the code still does what it should. A check line is reported at every run" if counts[:check]
463
+ steps << 'Go through what this command cannot find: look in the code for the changes that concern the project'
464
+ steps << 'Run this command again: go on when only check lines that you have read are left' if counts[:breaks] || counts[:config]
465
+ steps << 'Start the application and run its tests: ApiRecipes.configure checks the whole configuration when it loads, also what an ERB tag gives, and lists every problem at once'
466
+ screen.section('👉', 'What to do now')
467
+ steps.each_with_index { |step, index| screen.item(step, "#{index + 1}.") }
468
+ end
469
+
113
470
  def summary(count)
114
471
  case count
115
- when 0 then 'Nothing to change'
472
+ when 0 then nothing_found
116
473
  when 1 then '1 finding'
117
474
  else "#{count} findings"
118
475
  end
119
476
  end
120
477
 
121
- def format_finding(finding)
122
- where = finding.line ? "#{finding.file}:#{finding.line}" : finding.file
123
- "#{where}: [#{finding.kind}] #{finding.message}"
478
+ # "Nothing to change" is said only of what was checked.
479
+ def nothing_found
480
+ return 'Nothing to change' unless @project && @configs.empty?
481
+
482
+ 'Nothing to change in the Ruby files. No configuration file was found: if the apis are described in ' \
483
+ 'YAML files, name each one with --config FILE'
484
+ end
485
+
486
+ # What a run on a project looked at.
487
+ def scope
488
+ ruby = @paths.size
489
+ lines = ["Checked #{ruby} Ruby file#{'s' unless ruby == 1}, #{@uses} of them use#{'s' if @uses == 1} api_recipes"]
490
+ lines << if @configs.empty?
491
+ 'No configuration file was found'
492
+ else
493
+ "Checked #{@configs.size} configuration file#{'s' unless @configs.size == 1}: #{@configs.map { |file| shown_path(file) }.join(', ')}"
494
+ end
495
+ lines + @project.undescribed.map do |declared|
496
+ "#{shown_path(declared.file)}:#{declared.line}: declares the api '#{declared.api}', and no configuration file found here describes it"
497
+ end
498
+ end
499
+
500
+ # A name found in the project is shown without what a terminal would
501
+ # obey; a path that was given is shown as it was given.
502
+ def shown_path(file) = @project ? Recipes::Summary.shown(file, 300) : file
503
+
504
+ def where(finding)
505
+ file = shown_path(finding.file)
506
+ finding.line ? "#{file}:#{finding.line}" : file
124
507
  end
125
508
 
126
509
  def scan_path(path)
127
510
  if File.directory?(path)
128
- Dir.glob('**/*.rb', base: path).sort.flat_map do |relative|
511
+ Dir.glob('**/*.{rb,rake}', base: path).sort.flat_map do |relative|
129
512
  file = File.join(path, relative)
130
513
  File.directory?(file) ? [] : scan_file(file)
131
514
  end
@@ -141,13 +524,177 @@ module ApiRecipes
141
524
  text = read_ruby(file)
142
525
  return [] unless text
143
526
 
527
+ rules = rules_for(text)
528
+ @configure[file] = text if text.match?(/\bApiRecipes\.configure\b/)
144
529
  found = []
145
530
  text.each_line(chomp: true).with_index(1) do |line, number|
146
- RULES.each do |rule|
147
- found << Finding.new(file: file, line: number, kind: rule.kind, message: rule.message) if rule.pattern.match?(line)
531
+ rules.each do |rule|
532
+ next unless rule.pattern.match?(line)
533
+
534
+ if rule.equal?(BARE_RESCUE)
535
+ # A rescue that comes after one of ApiRecipes::Error never sees them.
536
+ next if gem_errors_handled?(text, number)
537
+
538
+ @rescues << { file: file, line: number }
539
+ end
540
+ found << Finding.new(file: file, line: number, kind: rule.kind, message: rule.message, hint: hint(rule.fix, line, file, number, text))
148
541
  end
149
542
  end
150
- found
543
+ (found + in_the_tree(file, text, found)).each_with_index.sort_by { |finding, index| [finding.line, index] }.map(&:first)
544
+ end
545
+
546
+ # ---- the code to paste ----
547
+
548
+ # The code a line assigns, when it can be copied: on one line, short,
549
+ # and with nothing a terminal would obey.
550
+ # What only the tree of the file tells. A writer that a rule on lines
551
+ # found is not said twice.
552
+ def in_the_tree(file, text, found)
553
+ reported = found.select { |finding| WRITER_RULES.any? { |rule| rule.message == finding.message } }.map(&:line)
554
+ uses = !@project || @project.uses_gem?(text)
555
+ TreeRules.findings(text, uses_gem: uses, reported: reported, apis: @project ? @project.api_names : []).map do |one|
556
+ Finding.new(file: file, line: one.line, kind: one.kind, message: one.message)
557
+ end
558
+ end
559
+
560
+ def code_of(match)
561
+ code = without_comment(match[:code].to_s.strip)
562
+ return nil if code.empty? || code.length > MAX_CODE || Code::UNSAFE.match?(code) || !expression?(code)
563
+
564
+ code
565
+ end
566
+
567
+ # code up to a comment that follows it on the line.
568
+ def without_comment(code)
569
+ quote = nil
570
+ code.each_char.with_index do |char, index|
571
+ if quote
572
+ quote = nil if char == quote && code[index - 1] != '\\'
573
+ elsif ["'", '"', '`'].include?(char)
574
+ quote = char
575
+ elsif char == '#' && (index.zero? || code[index - 1].match?(/\s/))
576
+ return code[0...index].rstrip
577
+ end
578
+ end
579
+ code
580
+ end
581
+
582
+ # Whether code is one whole Ruby expression, and not one that a word
583
+ # after it changes (if, unless, rescue, and, or). It is read, never run.
584
+ def expression?(code)
585
+ tree = Code.tree(code)
586
+ return false unless tree && tree.statements.body.size == 1
587
+
588
+ node = tree.statements.body.first
589
+ return false if [Prism::IfNode, Prism::UnlessNode, Prism::RescueModifierNode, Prism::WhileNode, Prism::UntilNode].any? { |kind| node.is_a?(kind) }
590
+
591
+ !((node.is_a?(Prism::AndNode) || node.is_a?(Prism::OrNode)) && %w[and or].include?(node.operator_loc.slice))
592
+ end
593
+
594
+ # Whether the statement on line is always run when its file is: a
595
+ # statement of the file itself, or of the block of ApiRecipes.configure,
596
+ # not one inside a condition or another block.
597
+ def always_run?(file, text, line)
598
+ @direct ||= {}
599
+ @direct[file] ||= begin
600
+ tree = Code.tree(text)
601
+ top = tree ? tree.statements.body.map { |node| node.location.start_line } : []
602
+ block = Code::ConfigureBlock.in(text)
603
+ top + (block ? block.statement_lines : [])
604
+ end
605
+ @direct[file].include?(line)
606
+ end
607
+
608
+ # The lines shown under a finding. A value given when the application
609
+ # starts is kept aside: all of them go in one block of configure.
610
+ def hint(fix, line, file, number, text)
611
+ match = FIXES[fix]&.match(line)
612
+ case fix
613
+ when :request then ['response.uri # the address of the request', 'response.original_response # the http.rb response']
614
+ when :base_configs then match && !Code::UNSAFE.match?(match[:receiver]) ? ["#{match[:receiver]}.definition"] : nil
615
+ when :route then (code = match && code_of(match)) ? ["response.fill(#{code}) # response is what run returned"] : nil
616
+ when :writer
617
+ code = match && code_of(match)
618
+ return nil unless code && !Code::UNSAFE.match?(match[:receiver])
619
+
620
+ ['# for a class, where it declares the api:', "api :#{match[:api]}, #{match[:key]}: #{code}", '# for one request:',
621
+ "#{match[:receiver]}.#{match[:api]}.with(#{match[:key]}: #{code})"]
622
+ when :print_urls, :global_writer
623
+ code = match && code_of(match)
624
+ return nil unless code && always_run?(file, text, number)
625
+
626
+ @startup << { file: file, line: number, api: fix == :print_urls ? nil : match[:api], key: fix == :print_urls ? 'print_urls' : match[:key], code: code }
627
+ nil
628
+ end
629
+ end
630
+
631
+ # A credential of the application assigned in more than one place is
632
+ # assigned for each request: each of those lines becomes a with.
633
+ def with_request_hints(findings)
634
+ repeated = @startup.group_by { |item| [item[:api], item[:key]] }.select { |(api, _), items| api && items.size > 1 }.values.flatten
635
+ @startup -= repeated
636
+ findings.map do |finding|
637
+ item = repeated.find { |one| one[:file] == finding.file && one[:line] == finding.line }
638
+ next finding unless item && finding.hint.nil? && FIXES[:global_writer].match?('ApiRecipes.x.' + item[:key] + ' = 1') && finding.message.include?('config.values')
639
+
640
+ finding.with(hint: ["ApiRecipes.#{item[:api]}.with(#{item[:key]}: #{item[:code]}) # use the api it returns for the calls of this request"])
641
+ end
642
+ end
643
+
644
+ # The values given when the application starts, in the block of
645
+ # ApiRecipes.configure: the whole block when one file has it.
646
+ def code_to_paste(screen)
647
+ return false if @startup.empty?
648
+
649
+ file, text = @configure.size == 1 ? @configure.first : nil
650
+ block = Code::ConfigureBlock.in(text)
651
+ block = nil if block&.problem
652
+ config = block ? block.config : 'config'
653
+ inside = @startup.select { |item| block && item[:file] == file && item[:line].between?(block.first, block.last) }
654
+ added = @startup.select { |item| item[:api].nil? }.first(1).map { |item| "#{config}.print_urls = #{item[:code]}" }
655
+ added = [] if block&.line_of(:print_urls)
656
+ # config.values takes one credential for an api: given both, which
657
+ # one the application uses is left to the person.
658
+ both = @startup.select { |item| item[:api] }.group_by { |item| item[:api] }.select { |_, list| list.map { |item| item[:key] }.uniq.size > 1 }
659
+ entries = entries_of(@startup.select { |item| item[:api] && !both.key?(item[:api]) })
660
+ merged = block && block.line_of(:values)
661
+ added += ["#{config}.values = {", *entries.map { |entry| " #{entry}" }, '}'] unless entries.empty? || merged
662
+
663
+ screen.section('📋', 'Code to paste')
664
+ screen.gap
665
+ if block
666
+ screen.line("In #{shown_path(file)}, replace the block of ApiRecipes.configure (lines #{block.first} to #{block.last}) with:")
667
+ screen.code(block.lines(added, without: inside.map { |item| item[:line] }))
668
+ else
669
+ screen.line('Inside the block of ApiRecipes.configure:')
670
+ screen.code(added)
671
+ end
672
+ if merged && !entries.empty?
673
+ screen.line("and add to the Hash that #{config}.values is given at line #{merged}:")
674
+ screen.code(entries)
675
+ end
676
+ outside = (@startup - inside - both.values.flatten).map { |item| "#{shown_path(item[:file])}:#{item[:line]}" }
677
+ screen.line("Then remove the lines that gave these values: #{outside.join(', ')}") unless outside.empty?
678
+ both.each do |api, list|
679
+ screen.line("#{Recipes::Summary.shown(api, 100)} is given both authorization and basic_auth " \
680
+ "(#{list.map { |item| "#{shown_path(item[:file])}:#{item[:line]}" }.join(', ')}): config.values takes one of them, " \
681
+ 'add the one the application uses')
682
+ end
683
+ true
684
+ end
685
+
686
+ # Every rule for the paths that were given. In a project, the general
687
+ # ones only for a file that uses the gem, and never the one about the
688
+ # methods that ActiveSupport defines when the project has it.
689
+ def rules_for(text)
690
+ return RULES unless @project
691
+
692
+ @specific ||= RULES.reject(&:general)
693
+ @all ||= @project.active_support? ? RULES - [HASH_METHODS] : RULES
694
+ return @specific unless @project.uses_gem?(text)
695
+
696
+ @uses += 1
697
+ @all
151
698
  end
152
699
 
153
700
  # Returns the text, or nil after recording why the file was not checked.
@@ -168,17 +715,119 @@ module ApiRecipes
168
715
  end
169
716
 
170
717
  def check_config(file)
171
- apis = Configuration.new.read_recipe_file(file, erb: @erb)
718
+ return check_recipe(file) if file.end_with?(Internals::Recipe::SUFFIX)
719
+ return [config_finding(file, 'describes more values than can be checked: aliases make them from a few lines')] if too_many_values?(file)
720
+
721
+ unchecked = []
722
+ tags = false
723
+ apis = Description.read(file, erb: @erb) do |text|
724
+ tags = true
725
+ without_erb(file, text)
726
+ end
727
+ return not_checked(file) if tags && structural_tag?(apis)
728
+
729
+ unchecked = erb_values(apis)
172
730
  Internals::Compiler.compile_all(apis)
173
- []
731
+ note_unchecked(file, unchecked)
732
+ [to_convert(file)] + ConfigRules.findings(apis).map { |message| Finding.new(file: file, line: nil, kind: :check, message: message) }
174
733
  rescue RecipeFileError => e
175
- e.errors.map { |problem| config_finding(file, problem.delete_prefix("#{file}: ")) }
734
+ return not_checked(file) if tags && e.errors.all? { |problem| problem.include?('invalid YAML') }
735
+
736
+ [to_convert(file)] + e.errors.map { |problem| config_finding(file, problem.delete_prefix("#{file}: ")) }
176
737
  rescue ConfigurationError => e
177
- e.errors.map { |problem| config_finding(file, problem) }
738
+ note_unchecked(file, unchecked)
739
+ [to_convert(file)] + checked(e.errors, unchecked).map { |problem| config_finding(file, problem) }
740
+ rescue SystemStackError
741
+ [config_finding(file, 'is nested too deeply to be checked')]
178
742
  rescue StandardError, ScriptError => e
179
743
  [config_finding(file, "could not be evaluated (#{e.class})")]
180
744
  end
181
745
 
746
+ # 3.0 loads no file of the project that describes an api.
747
+ def to_convert(file)
748
+ Finding.new(file: file, line: nil, kind: :breaks,
749
+ message: 'describes an api in a file of the project, which 3.0 no longer loads: an api is described by a ' \
750
+ 'portable recipe. `api_recipes convert` moves it to one')
751
+ end
752
+
753
+ # A file whose tags give a name or a part of the structure is not
754
+ # guessed: it is said, and it is not a finding.
755
+ def not_checked(file)
756
+ @notes << "#{shown_path(file)}: an ERB tag gives a name or a part of the structure: not checked without --erb"
757
+ []
758
+ end
759
+
760
+ def structural_tag?(value)
761
+ case value
762
+ when Hash
763
+ value.any? do |key, inner|
764
+ key.to_s.include?(@erb_value) || (CONTAINERS.include?(key.to_s) && inner.to_s == @erb_value) || structural_tag?(inner)
765
+ end
766
+ when Array then value.any? { |inner| structural_tag?(inner) }
767
+ else false
768
+ end
769
+ end
770
+
771
+ # Aliases can make millions of values from a few lines: the file is
772
+ # measured, with its tags read as a word, before anything walks it.
773
+ def too_many_values?(file)
774
+ text = File.binread(file).force_encoding(Encoding::UTF_8)
775
+ return false unless text.valid_encoding? && text.include?('*')
776
+
777
+ data = YAML.safe_load(text.gsub(/<%.*?%>/m, 'erb'), permitted_classes: [Symbol], aliases: true)
778
+ !Project.within?(data, Project::MAX_VALUES)
779
+ rescue SystemCallError, Psych::Exception, SystemStackError
780
+ false
781
+ end
782
+
783
+ # A file called NAME.recipe.yml is a portable recipe, read as data only.
784
+ def check_recipe(file)
785
+ Internals::Recipe.read(file)
786
+ []
787
+ rescue ConfigurationError => e
788
+ e.errors.map { |problem| config_finding(file, problem.delete_prefix("#{file}: ")) }
789
+ rescue StandardError => e
790
+ [config_finding(file, "could not be read (#{e.class})")]
791
+ end
792
+
793
+ # The text of a file with ERB, made checkable without running anything:
794
+ # the value of each output tag becomes ERB_VALUE. A tag that is not an
795
+ # output tag can decide which lines the file has, so it is not guessed.
796
+ def without_erb(file, text)
797
+ plain = Tags.replaced(text, @erb_value)
798
+ return plain if plain
799
+
800
+ raise RecipeFileError.new(file, 'contains ERB that decides the structure of the file (<% ... %>): run again ' \
801
+ 'with --erb to evaluate it (this executes the code in the file)')
802
+ end
803
+
804
+ # The places, as the compiler names them, whose value holds the value
805
+ # of a tag.
806
+ def erb_values(value, path = nil, found = [])
807
+ case value
808
+ when Hash then value.each { |key, inner| erb_values(inner, [path, place(key)].compact.join('.'), found) }
809
+ when Array then found << path if value.any? { |item| item.to_s.include?(@erb_value) }
810
+ else found << path if value.to_s.include?(@erb_value)
811
+ end
812
+ found
813
+ end
814
+
815
+ # A name as the compiler writes it in the place of a problem.
816
+ def place(name) = name.to_s.gsub(/[^[:print:]]/, '?')[0, 40]
817
+
818
+ # The problems that are not about a value that an ERB tag gives.
819
+ def checked(problems, unchecked)
820
+ problems.reject { |problem| unchecked.any? { |path| problem.start_with?("#{path}: ") } }
821
+ end
822
+
823
+ def note_unchecked(file, unchecked)
824
+ return if unchecked.empty?
825
+
826
+ count = unchecked.size
827
+ @notes << "#{shown_path(file)}: #{count} value#{'s' unless count == 1} come#{'s' if count == 1} from ERB and " \
828
+ "#{count == 1 ? 'was' : 'were'} not checked"
829
+ end
830
+
182
831
  def config_finding(file, message)
183
832
  Finding.new(file: file, line: nil, kind: :config, message: message)
184
833
  end