api_recipes 3.0.0.beta4 → 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.
@@ -2,6 +2,9 @@
2
2
 
3
3
  require 'securerandom'
4
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'
5
8
 
6
9
  module ApiRecipes
7
10
  module CLI
@@ -34,6 +37,9 @@ module ApiRecipes
34
37
  'ApiRecipes::Settings was removed: the defaults are listed in the README'),
35
38
  Rule.new(:breaks, /\bconfiguration\.setup\b/,
36
39
  'configuration.setup was removed: configure loads the configuration'),
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'),
37
43
  Rule.new(:breaks, /ApiRecipes\.print_urls/, 'use config.print_urls inside ApiRecipes.configure', false, :print_urls),
38
44
  Rule.new(:breaks, /_aprcps_|set_authorization_for_api|set_basic_auth_for_api|copy_global_authorizations_to_api/,
39
45
  'internal method removed'),
@@ -59,6 +65,17 @@ module ApiRecipes
59
65
  # The rule about the Hash methods that ActiveSupport defines too.
60
66
  HASH_METHODS = RULES.last
61
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
+
62
79
  # What stands for the value of an ERB tag in a file that is checked
63
80
  # without running its code.
64
81
  # Options whose value is a mapping: a tag that gives one gives a part
@@ -76,39 +93,21 @@ module ApiRecipes
76
93
  }.freeze
77
94
  # Code longer than this is not copied into the code to paste.
78
95
  MAX_CODE = 300
79
- ERB_COMMENT = /<%#.*?%>/m
80
- ERB_OUTPUT = /<%=.*?%>/m
81
96
 
82
97
  SILENT_CHANGES = [
83
- 'path parameters encoded by hand: %2F would become %252F, remove the encoding',
84
- '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',
85
100
  'debug logs or print_urls output read from STDOUT: set log_to and log_level',
86
- 'a bare rescue around a call: it now catches the errors of the gem too',
87
- 'credentials assigned on an instance: they now take effect',
88
- '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',
89
102
  'the response body read from the message of a verify_with error: read it from error.response',
90
- 'a block passed to run whose return value is used: it is now the Response',
91
- 'apis_configs assigned after the files to discard them: do not assign the files',
92
- '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',
93
- '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',
94
103
  'fill with private setters, or code that relies on swallowed errors: make the setters public, handle the errors',
95
- 'follow: true together with a credential: the credential no longer follows to another host',
96
- 'a class with its own host, protocol or port that relied on the global credential: set the credential on the class',
97
104
  'cookies set by a server during a redirect chain: they are no longer carried to the next hop',
98
- 'api names that are methods of Kernel, such as :open or :format: they raise ApiNameClashError, use as:',
99
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)',
100
106
  'an object restored from a serialized form (Marshal, YAML) has no credential: assign it again',
101
107
  'response.uri leaves out the credential query parameter when the api declares auth type query',
102
108
  'a redirect to a host with non-ASCII characters needs the addressable gem: without it the request raises InvalidUrl',
103
- 'a base_url with a placeholder in a configuration given as a Hash: it is now an error, use a variable',
104
- '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',
105
- 'response.to_s returns the body, as the http.rb response does: it was the default text of the object',
106
- 'a credential that is not a String, such as a Symbol or a number: it raises InvalidCredential, convert it with to_s',
107
- 'a {word} in a value of default_headers in a configuration given as a Hash: it is now a variable and must be declared',
108
- '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}',
109
- 'respond_to? on a response now tells the truth: it answers true for the methods the response forwards and false for the others',
110
- 'serializing an Api, an Endpoint or a Response raises TypeError: serialize response.data or response.body.to_s',
111
- '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'
112
111
  ].freeze
113
112
 
114
113
  # Problems met while reading, as "<file>: <reason>". They are not findings:
@@ -145,30 +144,43 @@ module ApiRecipes
145
144
  @uses = 0
146
145
  @startup = []
147
146
  @configure = {}
147
+ @direct = {}
148
+ @rescues = []
148
149
  findings = with_request_hints(@paths.flat_map { |path| scan_path(path) })
149
150
  findings += @configs.flat_map { |file| check_config(file) }
150
151
  @notes = scope + @notes if @project
151
152
  findings
152
153
  end
153
154
 
154
- # Prints the results on out and the warnings on err. Returns the exit code.
155
- 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)
156
161
  findings = run
157
- findings.each do |finding|
158
- out.puts format_finding(finding)
159
- Code.show(out, finding.hint) if @code && finding.hint
160
- end
162
+ screen = Screen.new(out)
163
+ changed = @code && Fix.asks?(input, out) ? offered(screen, input, out, err) : []
164
+ findings = look_again unless changed.empty?
161
165
  unless @notes.empty?
162
- out.puts unless findings.empty?
163
- @notes.each { |note| out.puts note }
164
- end
165
- code_to_paste(out) if @code
166
- out.puts
167
- out.puts 'What this command cannot find'
168
- SILENT_CHANGES.each { |change| out.puts " - #{change}" }
169
- out.puts
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
170
181
  @warnings.each { |warning| err.puts warning }
171
- 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)
172
184
  return 1 if findings.any?
173
185
 
174
186
  @warnings.empty? ? 0 : 2
@@ -176,6 +188,285 @@ module ApiRecipes
176
188
 
177
189
  private
178
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
+
179
470
  def summary(count)
180
471
  case count
181
472
  when 0 then nothing_found
@@ -210,10 +501,9 @@ module ApiRecipes
210
501
  # obey; a path that was given is shown as it was given.
211
502
  def shown_path(file) = @project ? Recipes::Summary.shown(file, 300) : file
212
503
 
213
- def format_finding(finding)
504
+ def where(finding)
214
505
  file = shown_path(finding.file)
215
- where = finding.line ? "#{file}:#{finding.line}" : file
216
- "#{where}: [#{finding.kind}] #{finding.message}"
506
+ finding.line ? "#{file}:#{finding.line}" : file
217
507
  end
218
508
 
219
509
  def scan_path(path)
@@ -241,16 +531,32 @@ module ApiRecipes
241
531
  rules.each do |rule|
242
532
  next unless rule.pattern.match?(line)
243
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
244
540
  found << Finding.new(file: file, line: number, kind: rule.kind, message: rule.message, hint: hint(rule.fix, line, file, number, text))
245
541
  end
246
542
  end
247
- found
543
+ (found + in_the_tree(file, text, found)).each_with_index.sort_by { |finding, index| [finding.line, index] }.map(&:first)
248
544
  end
249
545
 
250
546
  # ---- the code to paste ----
251
547
 
252
548
  # The code a line assigns, when it can be copied: on one line, short,
253
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
+
254
560
  def code_of(match)
255
561
  code = without_comment(match[:code].to_s.strip)
256
562
  return nil if code.empty? || code.length > MAX_CODE || Code::UNSAFE.match?(code) || !expression?(code)
@@ -337,8 +643,8 @@ module ApiRecipes
337
643
 
338
644
  # The values given when the application starts, in the block of
339
645
  # ApiRecipes.configure: the whole block when one file has it.
340
- def code_to_paste(out)
341
- return if @startup.empty?
646
+ def code_to_paste(screen)
647
+ return false if @startup.empty?
342
648
 
343
649
  file, text = @configure.size == 1 ? @configure.first : nil
344
650
  block = Code::ConfigureBlock.in(text)
@@ -347,27 +653,34 @@ module ApiRecipes
347
653
  inside = @startup.select { |item| block && item[:file] == file && item[:line].between?(block.first, block.last) }
348
654
  added = @startup.select { |item| item[:api].nil? }.first(1).map { |item| "#{config}.print_urls = #{item[:code]}" }
349
655
  added = [] if block&.line_of(:print_urls)
350
- entries = @startup.select { |item| item[:api] }.group_by { |item| item[:api] }.map do |api, items|
351
- "#{api.match?(/\A[a-z_]\w*\z/) ? api : "\"#{api}\""}: { #{items.map { |item| "#{item[:key]}: #{item[:code]}" }.join(', ')} }"
352
- end
353
- entries = entries.each_with_index.map { |entry, index| index == entries.size - 1 ? entry : "#{entry}," }
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]) })
354
660
  merged = block && block.line_of(:values)
355
661
  added += ["#{config}.values = {", *entries.map { |entry| " #{entry}" }, '}'] unless entries.empty? || merged
356
662
 
357
- out.puts '', 'Code to paste', ''
663
+ screen.section('📋', 'Code to paste')
664
+ screen.gap
358
665
  if block
359
- out.puts "In #{shown_path(file)}, replace the block of ApiRecipes.configure (lines #{block.first} to #{block.last}) with:"
360
- Code.show(out, block.lines(added, without: inside.map { |item| item[:line] }))
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] }))
361
668
  else
362
- out.puts 'Inside the block of ApiRecipes.configure:'
363
- Code.show(out, added)
669
+ screen.line('Inside the block of ApiRecipes.configure:')
670
+ screen.code(added)
364
671
  end
365
672
  if merged && !entries.empty?
366
- out.puts "and add to the Hash that #{config}.values is given at line #{merged}:"
367
- Code.show(out, entries)
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')
368
682
  end
369
- outside = (@startup - inside).map { |item| "#{shown_path(item[:file])}:#{item[:line]}" }
370
- out.puts "Then remove the lines that gave these values: #{outside.join(', ')}" unless outside.empty?
683
+ true
371
684
  end
372
685
 
373
686
  # Every rule for the paths that were given. In a project, the general
@@ -407,7 +720,7 @@ module ApiRecipes
407
720
 
408
721
  unchecked = []
409
722
  tags = false
410
- apis = Configuration.new.read_recipe_file(file, erb: @erb) do |text|
723
+ apis = Description.read(file, erb: @erb) do |text|
411
724
  tags = true
412
725
  without_erb(file, text)
413
726
  end
@@ -416,20 +729,27 @@ module ApiRecipes
416
729
  unchecked = erb_values(apis)
417
730
  Internals::Compiler.compile_all(apis)
418
731
  note_unchecked(file, unchecked)
419
- []
732
+ [to_convert(file)] + ConfigRules.findings(apis).map { |message| Finding.new(file: file, line: nil, kind: :check, message: message) }
420
733
  rescue RecipeFileError => e
421
734
  return not_checked(file) if tags && e.errors.all? { |problem| problem.include?('invalid YAML') }
422
735
 
423
- e.errors.map { |problem| config_finding(file, problem.delete_prefix("#{file}: ")) }
736
+ [to_convert(file)] + e.errors.map { |problem| config_finding(file, problem.delete_prefix("#{file}: ")) }
424
737
  rescue ConfigurationError => e
425
738
  note_unchecked(file, unchecked)
426
- checked(e.errors, unchecked).map { |problem| config_finding(file, problem) }
739
+ [to_convert(file)] + checked(e.errors, unchecked).map { |problem| config_finding(file, problem) }
427
740
  rescue SystemStackError
428
741
  [config_finding(file, 'is nested too deeply to be checked')]
429
742
  rescue StandardError, ScriptError => e
430
743
  [config_finding(file, "could not be evaluated (#{e.class})")]
431
744
  end
432
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
+
433
753
  # A file whose tags give a name or a part of the structure is not
434
754
  # guessed: it is said, and it is not a finding.
435
755
  def not_checked(file)
@@ -474,8 +794,8 @@ module ApiRecipes
474
794
  # the value of each output tag becomes ERB_VALUE. A tag that is not an
475
795
  # output tag can decide which lines the file has, so it is not guessed.
476
796
  def without_erb(file, text)
477
- plain = text.gsub(ERB_COMMENT, '').gsub(ERB_OUTPUT, @erb_value)
478
- return plain.gsub('<%%', '<%') unless plain.gsub('<%%', '').include?('<%')
797
+ plain = Tags.replaced(text, @erb_value)
798
+ return plain if plain
479
799
 
480
800
  raise RecipeFileError.new(file, 'contains ERB that decides the structure of the file (<% ... %>): run again ' \
481
801
  'with --erb to evaluate it (this executes the code in the file)')