api_recipes 3.0.0.beta3 → 3.0.0.beta4

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.
@@ -0,0 +1,624 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'open3'
4
+ require 'tmpdir'
5
+ require 'pathname'
6
+ require 'fileutils'
7
+
8
+ module ApiRecipes
9
+ module CLI
10
+ class Convert
11
+ # Moves one api of a project to a portable recipe, so that the project
12
+ # works afterwards: the recipe is installed, the code of the ERB tags
13
+ # goes to config.values in the file that calls ApiRecipes.configure, and
14
+ # the old description is removed.
15
+ #
16
+ # Ruby is read as a tree, never matched as lines and never run. Every
17
+ # change is worked out in memory, on the text as the changes before it
18
+ # left it, and each result must be valid Ruby. When a step cannot be
19
+ # done safely nothing is written. A write that fails puts every file
20
+ # back as it was. A file that exists is changed only when it is a plain
21
+ # file of the project that git tracks; lines are taken out of one, and
22
+ # one is deleted, only when git has it committed as it is now.
23
+ class Migration
24
+ SIMPLE_CODE = /\AENV(\[\s*(['"])\w+\2\s*\]|\.fetch\(\s*(['"])\w+\3\s*\))\z/
25
+ PLAIN_CODE = /\A("(?:[^"#\\]|\\.)*"|'[^'\\]*'|\d+)\z/
26
+ # git does not run a program that the repository names.
27
+ GIT = ['git', '-c', 'core.fsmonitor=false', '-c', 'core.hooksPath=/dev/null'].freeze
28
+
29
+ def initialize(result, source, out:, err:, root: '.')
30
+ @result = result
31
+ @source = source
32
+ @out = out
33
+ @err = err
34
+ @root = root
35
+ @blocking = []
36
+ @left = []
37
+ @done = []
38
+ # The text each file will have: nil for a file that is deleted.
39
+ @planned = {}
40
+ @notes = {}
41
+ end
42
+
43
+ # Returns the exit code: 0 when the project was changed, 1 when it was
44
+ # not, 2 when something could not be written.
45
+ def call
46
+ @project = Upgrade::Project.new(@root)
47
+ inside = Pathname.new(File.expand_path(@source)).relative_path_from(Pathname.new(File.expand_path(@root))).to_s
48
+ @source = inside unless inside.start_with?('..')
49
+ @directory = Recipes::DEFAULT_DIRECTORY
50
+ @target = File.join(@directory, "#{@result.name}#{Internals::Recipe::SUFFIX}")
51
+ @lock = File.join(@directory, Internals::RecipeLock::FILE_NAME)
52
+ place_problems
53
+ plan_initializer
54
+ plan_verify_with
55
+ plan_old_description
56
+ plan_valid
57
+ return refused unless @blocking.empty?
58
+ return 2 unless apply
59
+
60
+ report
61
+ 0
62
+ end
63
+
64
+ private
65
+
66
+ def shown(text) = Recipes::Summary.shown(text, 100)
67
+
68
+ def full(file) = File.join(@root, file)
69
+
70
+ # The text a file has now, with the changes planned so far.
71
+ def text_of(file)
72
+ return @planned[file] if @planned.key?(file)
73
+
74
+ bytes = File.binread(full(file))
75
+ text = bytes.force_encoding(Encoding::UTF_8)
76
+ text.valid_encoding? && !bytes.include?("\0") ? text : nil
77
+ rescue SystemCallError
78
+ nil
79
+ end
80
+
81
+ def plan(file, text, note)
82
+ @planned[file] = text
83
+ (@notes[file] ||= []) << note
84
+ end
85
+
86
+ # ---- what git knows ----
87
+
88
+ def git(*arguments)
89
+ Open3.capture2e({ 'GIT_OPTIONAL_LOCKS' => '0' }, *GIT, '-C', @root, *arguments)
90
+ rescue SystemCallError
91
+ ['', nil]
92
+ end
93
+
94
+ # Whether file is a plain file of the project: not a symbolic link, not
95
+ # below one, and not outside the project.
96
+ def plain?(file)
97
+ path = full(file)
98
+ return false if File.symlink?(path) || !File.file?(path)
99
+
100
+ File.realpath(path) == File.join(File.realpath(@root), Pathname.new(file).cleanpath.to_s)
101
+ rescue SystemCallError
102
+ false
103
+ end
104
+
105
+ # Whether git tracks the file as it does any other: `H` is what it
106
+ # says of a file that is neither skipped nor assumed unchanged.
107
+ def tracked?(file)
108
+ out, status = git('ls-files', '-v', '--error-unmatch', '--', file)
109
+ return false unless plain?(file) && status&.success? && out.start_with?('H ')
110
+
111
+ # A file only announced to git (add -N) has nothing to go back to.
112
+ _, known = git('cat-file', '-e', "HEAD:./#{Pathname.new(file).cleanpath}")
113
+ known&.success? ? true : false
114
+ end
115
+
116
+ # Whether git has the file committed as it is now.
117
+ def committed?(file)
118
+ return false unless tracked?(file)
119
+
120
+ changes, status = git('status', '--porcelain', '--', file)
121
+ status&.success? && changes.empty?
122
+ end
123
+
124
+ def git_reason(file)
125
+ _, status = git('--version')
126
+ return 'git was not found: without it a change could not be seen or undone' unless status&.success?
127
+ return "#{shown(file)} is a symbolic link, or is below one: this command changes only the files of the project" unless plain?(file)
128
+
129
+ nil
130
+ end
131
+
132
+ # Lines are only added to file: git must know it.
133
+ def addable(file)
134
+ return true if tracked?(file) && File.writable?(full(file))
135
+
136
+ @blocking << (git_reason(file) || "#{shown(file)} is not a file that git tracks and that can be written: " \
137
+ 'a change to it could not be seen or undone')
138
+ false
139
+ end
140
+
141
+ # Lines are taken out of file, or the file is deleted: git must have
142
+ # it as it is now.
143
+ def removable(file)
144
+ return true if committed?(file) && File.writable?(full(file)) && File.writable?(File.dirname(full(file)))
145
+
146
+ @blocking << (git_reason(file) || "#{shown(file)} is not committed in git as it is now, or cannot be written: " \
147
+ 'what is removed from it could not be brought back')
148
+ false
149
+ end
150
+
151
+ # ---- where the recipe goes ----
152
+
153
+ def place_problems
154
+ directory = full(@directory)
155
+ @blocking << "#{@target} already exists" if File.exist?(full(@target)) || File.symlink?(full(@target))
156
+ @blocking << "#{@directory} is a symbolic link: the recipe would be written outside the project" if File.symlink?(directory)
157
+ _, ignored = git('check-ignore', '-q', '--', @target)
158
+ @blocking << "#{@target} would be ignored by git: the recipe would not be committed with the rest" if ignored&.success?
159
+ lock_problem
160
+ also = (@project.config_files - [Pathname.new(@source).cleanpath.to_s]).select do |file|
161
+ !file.end_with?(Internals::Recipe::SUFFIX) && Convert.shape(@project.text(file).to_s).key?(@result.name)
162
+ rescue Refused, Psych::Exception
163
+ false
164
+ end
165
+ @blocking << "#{@result.name} is described in #{also.map { |file| shown(file) }.join(', ')} too: a recipe never takes the place of an api" unless also.empty?
166
+ end
167
+
168
+ # A recipes.lock that is there is rewritten with one more line: it must
169
+ # be a plain file that reads as a lock.
170
+ def lock_problem
171
+ return unless File.exist?(full(@lock)) || File.symlink?(full(@lock))
172
+ return @blocking << "#{@lock} is not a plain file of the project" unless plain?(@lock) && File.writable?(full(@lock))
173
+
174
+ Internals::RecipeLock.read(full(@directory))
175
+ rescue ConfigurationError
176
+ @blocking << "#{@lock} cannot be read as a lock: this command would rewrite it"
177
+ end
178
+
179
+ # ---- the file that calls ApiRecipes.configure ----
180
+
181
+ def plan_initializer
182
+ files = @project.ruby_files.select { |file| @project.text(file).to_s.include?('ApiRecipes') && Code::ConfigureBlock.in(@project.text(file)) }
183
+ if files.size != 1
184
+ @blocking << (files.empty? ? 'no Ruby file of the project calls ApiRecipes.configure once' : "ApiRecipes.configure is called in #{files.size} files (#{files.map { |file| shown(file) }.join(', ')})")
185
+ return
186
+ end
187
+
188
+ @initializer = files.first
189
+ text = text_of(@initializer)
190
+ block = Code::ConfigureBlock.in(text)
191
+ if block.problem
192
+ @blocking << "#{shown(@initializer)}: the call to ApiRecipes.configure #{block.problem}"
193
+ return
194
+ end
195
+
196
+ problems = @blocking.size
197
+ added = values_edits(block, text) + recipes_edits(block)
198
+ # What is added goes at one place, in this order.
199
+ comma, added = added.partition { |from, _, _| from != block.end_offset }
200
+ edits = comma + files_edits(block, text)
201
+ edits << [block.end_offset, block.end_offset, added.map(&:last).join] unless added.empty?
202
+ return if @blocking.size > problems
203
+
204
+ edits = edits.map { |from, to, added_text| [from, to, added_text.gsub("\n", "\r\n")] } if text.include?("\r\n")
205
+ @proposal = [text, Code.edited(text, edits)]
206
+ taken_out = edits.any? { |from, to, _| to > from }
207
+ plan(@initializer, @proposal.last, 'recipes_paths and config.values') if taken_out ? removable(@initializer) : addable(@initializer)
208
+ end
209
+
210
+ # The lines that give the variables of this api, one variable a line.
211
+ # compact: a variable whose code gives nil is not given.
212
+ def entry(indent, unit)
213
+ pairs = @result.expressions.map do |name, code|
214
+ "#{indent}#{unit}#{name}: #{code.match?(SIMPLE_CODE) || code.match?(PLAIN_CODE) ? code : "(#{code})"}"
215
+ end
216
+ "#{indent}#{Snippet.new(@result, @source).key}: { variables: {\n#{pairs.join(",\n")}\n#{indent}}.compact }\n"
217
+ end
218
+
219
+ # The edits that give the values: a new config.values, or one more
220
+ # entry in the Hash it is given. That Hash is edited only when the
221
+ # command can read all of it: every key written as a name, none of
222
+ # them this api, and its closing brace alone at the start of a line.
223
+ def values_edits(block, text)
224
+ return [] if @result.expressions.empty?
225
+
226
+ config = block.config
227
+ unit = block.indent.include?("\t") ? "\t" : ' '
228
+ given = block.assignments(:values)
229
+ if given.empty?
230
+ return blocked("#{config}.values is assigned where the block does not always run it") if block.assigned_anywhere?(:values)
231
+
232
+ return [[block.end_offset, block.end_offset, "#{block.indent}#{config}.values = {\n#{entry("#{block.indent}#{unit}", unit)}#{block.indent}}\n"]]
233
+ end
234
+
235
+ hash = given.size == 1 ? given.first.arguments&.arguments&.first : nil
236
+ return blocked("#{config}.values is not given one Hash written between braces: this command does not edit it") unless hash.is_a?(Prism::HashNode)
237
+
238
+ keys = hash.elements.map { |element| key_of(element) }
239
+ if keys.include?(:unknown)
240
+ return blocked("#{config}.values has a key that is not written as a name, or a **: this command cannot tell whether #{@result.name} is among them")
241
+ end
242
+ return blocked("#{config}.values already has #{@result.name}: this command does not merge into it") if keys.include?(@result.name)
243
+
244
+ closing = hash.closing_loc
245
+ line = text.lines[closing.start_line - 1]
246
+ alone = closing.start_line > hash.opening_loc.start_line && line.b[0...closing.start_column].strip.empty?
247
+ return blocked("#{config}.values is given a Hash whose closing brace does not start a line") unless alone
248
+
249
+ indent = line[/\A[ \t]*/]
250
+ start = closing.start_offset - closing.start_column
251
+ last = hash.elements.last
252
+ comma = last && !text.b[last.location.end_offset...start].include?(',') ? [[last.location.end_offset, last.location.end_offset, ',']] : []
253
+ comma + [[start, start, entry("#{indent}#{unit}", unit)]]
254
+ end
255
+
256
+ def blocked(reason)
257
+ @blocking << "#{shown(@initializer)}: #{reason}"
258
+ []
259
+ end
260
+
261
+ # The name of a key of a Hash, or nil when it is not written.
262
+ def key_of(element)
263
+ return :unknown unless element.is_a?(Prism::AssocNode)
264
+
265
+ key = element.key
266
+ key.is_a?(Prism::SymbolNode) || key.is_a?(Prism::StringNode) ? key.unescaped : :unknown
267
+ end
268
+
269
+ # The folder of the recipes, from the folder of the file.
270
+ def recipes_glob
271
+ relative = Pathname.new(@directory).relative_path_from(Pathname.new(File.dirname(@initializer))).to_s
272
+ "#{relative}/*#{Internals::Recipe::SUFFIX}"
273
+ end
274
+
275
+ def recipes_edits(block)
276
+ given = block.assignments(:recipes_paths)
277
+ if given.empty?
278
+ return blocked("#{block.config}.recipes_paths is assigned where the block does not always run it") if block.assigned_anywhere?(:recipes_paths)
279
+
280
+ return [[block.end_offset, block.end_offset, "#{block.indent}#{block.config}.recipes_paths = Dir[File.expand_path('#{recipes_glob}', __dir__)]\n"]]
281
+ end
282
+ return [] if given.all? { |node| node.slice.include?(Internals::Recipe::SUFFIX) && node.slice.include?(File.basename(@directory)) }
283
+
284
+ blocked("#{block.config}.recipes_paths is assigned at line #{given.first.location.start_line} in a way this command cannot " \
285
+ "read: it must give #{@target}")
286
+ end
287
+
288
+ # When the old file goes, what names it must go too. The command must
289
+ # be able to read how the project loads its files: apis_files_paths
290
+ # given patterns of Dir, or a list written between brackets, from
291
+ # which the one element that names the file is taken out. Anything
292
+ # else, and any other mention of the file in the code, stops it.
293
+ def files_edits(block, text)
294
+ return [] unless whole_file?
295
+
296
+ name = File.basename(@source)
297
+ given = block.assignments(:apis_files_paths)
298
+ if given.empty?
299
+ blocked("#{block.config}.apis_files_paths is not assigned in the block, or only sometimes: this command cannot see how " \
300
+ "the project loads #{shown(name)}, which would be deleted")
301
+ end
302
+ edits = []
303
+ covered = []
304
+ given.each do |node|
305
+ found = named_in(node.arguments&.arguments&.first, name, text)
306
+ if found.nil?
307
+ blocked("#{block.config}.apis_files_paths is given, at line #{node.location.start_line}, in a way this command cannot " \
308
+ "read: it cannot tell whether it names #{shown(name)}, which would be deleted")
309
+ elsif found != :none
310
+ edits << found.first
311
+ covered << found.last
312
+ end
313
+ end
314
+ @project.ruby_files.each do |file|
315
+ @project.text(file).to_s.lines.each_with_index do |line, index|
316
+ next unless line.include?(name)
317
+ next if file == @initializer && covered.any? { |lines| lines.cover?(index + 1) }
318
+
319
+ @blocking << "#{shown(file)}:#{index + 1} names #{shown(name)}, which would be deleted: take the name out first"
320
+ end
321
+ end
322
+ edits
323
+ end
324
+
325
+ # Whether value, given to apis_files_paths, names the file called
326
+ # name. :none when it does not; [edit, lines] to take out the one
327
+ # element that does; nil when the command cannot read value.
328
+ def named_in(value, name, text)
329
+ return :none if pattern?(value)
330
+
331
+ if value.is_a?(Prism::CallNode) && value.name == :+ && value.arguments&.arguments&.size == 1
332
+ sides = [named_in(value.receiver, name, text), named_in(value.arguments.arguments.first, name, text)]
333
+ return nil if sides.include?(nil) || sides.count { |side| side != :none } > 1
334
+
335
+ return sides.find { |side| side != :none } || :none
336
+ end
337
+ return nil unless value.is_a?(Prism::ArrayNode) && value.opening_loc&.slice == '['
338
+ return nil unless value.elements.all? { |element| written?(element) || pattern?(element.is_a?(Prism::SplatNode) ? element.expression : element) }
339
+
340
+ named = value.elements.select { |element| written?(element) && element.slice.include?(name) }
341
+ return :none if named.empty?
342
+ return nil unless named.size == 1
343
+
344
+ edit = removal(value, named.first, text)
345
+ edit && [edit, named.first.location.start_line..named.first.location.end_line]
346
+ end
347
+
348
+ # Dir['...*...'] or Dir.glob('...*...'): files found when the
349
+ # application starts, not named one by one.
350
+ def pattern?(node)
351
+ node.is_a?(Prism::CallNode) && node.receiver.is_a?(Prism::ConstantReadNode) && node.receiver.name == :Dir &&
352
+ %i[[] glob].include?(node.name) && node.block.nil? && node.slice.include?('*') && !node.slice.include?('#{')
353
+ end
354
+
355
+ # One file named with text only: 'a/b.yml', File.expand_path('a/b.yml', __dir__), Rails.root.join('a', 'b.yml').
356
+ def written?(node)
357
+ return true if node.is_a?(Prism::StringNode)
358
+ return false unless node.is_a?(Prism::CallNode) && %i[expand_path join].include?(node.name) && node.block.nil? && node.arguments
359
+
360
+ node.arguments.arguments.all? { |one| one.is_a?(Prism::StringNode) || (one.is_a?(Prism::CallNode) && one.name == :__dir__) }
361
+ end
362
+
363
+ # The edit that takes element out of its list, or nil when it shares
364
+ # its lines with something else.
365
+ def removal(list, element, text)
366
+ others = list.elements - [element]
367
+ if list.location.start_line == list.location.end_line
368
+ return [list.location.start_offset, list.location.end_offset, "[#{others.map(&:slice).join(', ')}]"]
369
+ end
370
+
371
+ first = element.location.start_line
372
+ last = element.location.end_line
373
+ alone = others.none? { |one| one.location.end_line >= first && one.location.start_line <= last } &&
374
+ list.opening_loc.start_line < first && list.closing_loc.start_line > last
375
+ return nil unless alone
376
+
377
+ lines = text.lines
378
+ from = lines[0...first - 1].sum(&:bytesize)
379
+ [from, from + lines[first - 1..last - 1].sum(&:bytesize), '']
380
+ end
381
+
382
+ # ---- verify_with ----
383
+
384
+ # A recipe cannot carry verify_with: the one of the api goes on each
385
+ # `api :name` that a class or a module declares, right after what the
386
+ # call is given. When one of them is written in a way the command
387
+ # cannot read, none is changed and the step is left to the person.
388
+ def plan_verify_with
389
+ @result.verify_with.each do |place, method|
390
+ calls = place == 'verify_with' && Internals::Compiler::METHOD_NAME.match?(method.to_s) ? declarations : []
391
+ files = calls.map(&:first).uniq
392
+ unless !calls.empty? && calls.all? { |_, node| readable?(node) } && files.all? { |file| tracked?(file) && File.writable?(full(file)) }
393
+ @left << "#{shown(place)}: was left out of the recipe and could not be written in the code: give it where a class " \
394
+ "declares the api, as `api :#{@result.name}, verify_with: ...`, or the answers are no longer verified"
395
+ next
396
+ end
397
+ files.each do |file|
398
+ text = text_of(file)
399
+ edits = declarations_in(text).map { |node| [at(node), at(node), ", verify_with: :#{method}"] }
400
+ plan(file, Code.edited(text, edits), 'verify_with on the declaration of the api')
401
+ end
402
+ end
403
+ end
404
+
405
+ # Where the arguments of a call end: before its closing parenthesis.
406
+ def at(node) = node.closing_loc ? node.closing_loc.start_offset : node.arguments.location.end_offset
407
+
408
+ # [file, node] for each `api :name` of a class or a module that gives
409
+ # no verify_with.
410
+ def declarations(planned: true)
411
+ @project.ruby_files.flat_map do |file|
412
+ text = planned ? text_of(file) : @project.text(file)
413
+ text.to_s.include?('api') ? declarations_in(text).map { |node| [file, node] } : []
414
+ end
415
+ end
416
+
417
+ def declarations_in(text)
418
+ tree = Code.tree(text)
419
+ return [] unless tree
420
+
421
+ owners = Code.nodes(tree) { |node| node.is_a?(Prism::ClassNode) || node.is_a?(Prism::ModuleNode) }
422
+ owners.flat_map { |owner| declared_in(owner.body) }.uniq
423
+ end
424
+
425
+ # The calls `api :name` in the body of a class or a module: not inside
426
+ # a method, a block or another class, which have a body of their own.
427
+ def declared_in(node, found = [])
428
+ return found if node.nil? || [Prism::DefNode, Prism::BlockNode, Prism::LambdaNode, Prism::ClassNode, Prism::ModuleNode].any? { |kind| node.is_a?(kind) }
429
+
430
+ arguments = node.is_a?(Prism::CallNode) && node.name == :api && node.receiver.nil? ? node.arguments&.arguments : nil
431
+ if arguments && arguments.first.is_a?(Prism::SymbolNode) && arguments.first.unescaped == @result.name
432
+ found << node unless options_of(node)&.include?('verify_with')
433
+ end
434
+ node.compact_child_nodes.each { |child| declared_in(child, found) }
435
+ found
436
+ end
437
+
438
+ # The names of the options a call gives, or nil when it gives them in
439
+ # a way the command cannot read: a **, a Hash in braces, a block.
440
+ def options_of(node)
441
+ rest = node.arguments.arguments.drop(1)
442
+ return nil unless node.block.nil? && rest.all? { |one| one.is_a?(Prism::KeywordHashNode) }
443
+
444
+ keys = rest.flat_map(&:elements).map { |element| element.is_a?(Prism::AssocNode) && element.key.is_a?(Prism::SymbolNode) ? element.key.unescaped : nil }
445
+ keys.include?(nil) ? nil : keys
446
+ end
447
+
448
+ def readable?(node) = !options_of(node).nil?
449
+
450
+ # ---- the old description ----
451
+
452
+ def whole_file?
453
+ @whole_file = Convert.shape(File.read(full(@source))).keys == [@result.name] if @whole_file.nil?
454
+ @whole_file
455
+ rescue Refused, Psych::Exception, SystemCallError
456
+ @whole_file = false
457
+ end
458
+
459
+ def plan_old_description
460
+ return unless removable(@source)
461
+ return plan(@source, nil, nil) if whole_file?
462
+
463
+ text = text_of(@source)
464
+ others = Convert.shape(text)
465
+ lines = text.lines
466
+ start = lines.index { |line| line.match?(/\A(['"]?)#{Regexp.escape(@result.name)}\1:/) }
467
+ finish = start && ((start + 1...lines.size).find { |index| lines[index].match?(/\A\S/) } || lines.size)
468
+ rest = start && (lines[0...start] + lines[finish..]).join
469
+ others.delete(@result.name)
470
+ return plan(@source, rest, "the lines of #{@result.name} are gone") if rest && Convert.shape(rest) == others
471
+
472
+ @blocking << "#{shown(@source)} describes other apis too, and the lines of #{@result.name} could not be taken out of it safely"
473
+ rescue Refused, Psych::Exception
474
+ @blocking << "#{shown(@source)} describes other apis too, and the lines of #{@result.name} could not be taken out of it safely"
475
+ end
476
+
477
+ # Every Ruby file must still be Ruby with its changes.
478
+ def plan_valid
479
+ @planned.each do |file, text|
480
+ next if text.nil? || !file.match?(Upgrade::Project::RUBY) || Code.tree(text)
481
+
482
+ @blocking << "#{shown(file)} would not be valid Ruby after the change"
483
+ end
484
+ end
485
+
486
+ # ---- writing ----
487
+
488
+ # Installs the recipe and writes every planned text. When a step
489
+ # fails, whatever the reason, every file is put back as it was.
490
+ def apply
491
+ paths = [@target, @lock, *@planned.keys].uniq
492
+ before = paths.to_h { |path| [path, File.exist?(full(path)) ? [File.binread(full(path)), File.stat(full(path)).mode] : nil] }
493
+ made = !File.directory?(full(@directory))
494
+ install
495
+ @planned.each { |file, text| text.nil? ? File.delete(full(file)) : File.write(full(file), text) }
496
+ true
497
+ rescue Exception => e # rubocop:disable Lint/RescueException
498
+ lost = restore(before, made)
499
+ reason = e.is_a?(Refused) ? e.message : e.class.name.split('::').last
500
+ @err.puts "the project could not be changed (#{reason}): " \
501
+ "#{lost.empty? ? 'every file was put back as it was' : "these files could not be put back: #{lost.map { |path| shown(path) }.join(', ')}"}"
502
+ raise unless e.is_a?(SystemCallError) || e.is_a?(Refused)
503
+
504
+ false
505
+ end
506
+
507
+ # Returns the paths that could not be put back.
508
+ def restore(before, made)
509
+ lost = before.reject do |path, saved|
510
+ if saved
511
+ File.binwrite(full(path), saved.first)
512
+ File.chmod(saved.last & 0o7777, full(path))
513
+ else
514
+ FileUtils.rm_f(full(path))
515
+ end
516
+ true
517
+ rescue SystemCallError
518
+ false
519
+ end.keys
520
+ Dir.rmdir(full(@directory)) if made && Dir.exist?(full(@directory)) && Dir.empty?(full(@directory))
521
+ lost
522
+ end
523
+
524
+ def install
525
+ Dir.mktmpdir do |dir|
526
+ file = File.join(dir, "#{@result.name}#{Internals::Recipe::SUFFIX}")
527
+ File.write(file, @result.text)
528
+ quiet = StringIO.new
529
+ code = Recipes.new(out: quiet, err: quiet, input: StringIO.new).install(file, directory: full(@directory), yes: true)
530
+ raise Refused.new(["#{@target} could not be installed"]) unless code.zero?
531
+ end
532
+ end
533
+
534
+ # ---- what is said ----
535
+
536
+ def refused
537
+ @err.puts "#{shown(@source)} can become a portable recipe, but the project was not changed:"
538
+ @blocking.each { |reason| @err.puts " - #{reason}" }
539
+ @err.puts 'Nothing was written.'
540
+ by_hand
541
+ 1
542
+ end
543
+
544
+ # What the command would have done, as steps with the code to paste.
545
+ def by_hand
546
+ @out.puts '', 'What to do by hand', '', '1. Write the recipe and install it:'
547
+ Code.show(@out, ["bundle exec api_recipes convert #{shown(@source)} --to #{@directory}",
548
+ "bundle exec api_recipes install #{@target} --yes"], :shell)
549
+ configure_step
550
+ number = 3
551
+ @result.verify_with.each do |place, method|
552
+ next unless place == 'verify_with'
553
+
554
+ places = declarations(planned: false).map { |file, node| "#{shown(file)}:#{node.location.start_line}" }
555
+ @out.puts "#{number}. #{places.empty? ? 'Where a class declares the api' : "Where the api is declared (#{places.join(', ')})"}, give verify_with:"
556
+ Code.show(@out, ["api :#{@result.name}, verify_with: #{Internals::Compiler::METHOD_NAME.match?(method.to_s) ? ":#{method}" : '...'}"])
557
+ number += 1
558
+ end
559
+ @out.puts "#{number}. Remove the old description: #{old_description}"
560
+ end
561
+
562
+ # The block of ApiRecipes.configure as it is after the change, to put
563
+ # in the place of the one that is there; or, when the command could
564
+ # not work it out, the lines to add.
565
+ def configure_step
566
+ before, after = @proposal && @proposal.map { |text| Code::ConfigureBlock.in(text) }
567
+ if before && after && !Code::UNSAFE.match?(after.lines.join("\n"))
568
+ @out.puts "2. In #{shown(@initializer)}, replace the block of ApiRecipes.configure (lines #{before.first} to #{before.last}) with:"
569
+ return Code.show(@out, after.lines)
570
+ end
571
+
572
+ block = @initializer && Code::ConfigureBlock.in(@project.text(@initializer))
573
+ unless block&.config
574
+ @out.puts "2. In #{@initializer ? shown(@initializer) : 'the file that calls ApiRecipes.configure'}, inside the block of ApiRecipes.configure, add:"
575
+ recipes = @initializer ? "Dir[File.expand_path('#{recipes_glob}', __dir__)]" : "Dir['#{@directory}/*#{Internals::Recipe::SUFFIX}']"
576
+ return Code.show(@out, Snippet.new(@result, @source, recipes: recipes).lines)
577
+ end
578
+
579
+ recipes = block.assigned_anywhere?(:recipes_paths) ? nil : "Dir[File.expand_path('#{recipes_glob}', __dir__)]"
580
+ snippet = Snippet.new(@result, @source, config: block.config, recipes: recipes)
581
+ values = block.line_of(:values) || (block.assigned_anywhere?(:values) ? 'another line' : nil)
582
+ values = "line #{values}" if values.is_a?(Integer)
583
+ if values && !@result.expressions.empty?
584
+ @out.puts "2. In #{shown(@initializer)}, inside the block of ApiRecipes.configure (line #{block.first}), add this to the Hash that " \
585
+ "#{block.config}.values is given at #{values}#{', and the line of recipes_paths' if recipes}:"
586
+ Code.show(@out, snippet.entry + (recipes ? ['', "#{block.config}.recipes_paths = #{recipes}"] : []))
587
+ else
588
+ @out.puts "2. In #{shown(@initializer)}, inside the block of ApiRecipes.configure (line #{block.first}), add:"
589
+ Code.show(@out, snippet.lines)
590
+ end
591
+ end
592
+
593
+ def old_description
594
+ return "delete #{shown(@source)}" if whole_file?
595
+
596
+ lines = File.read(full(@source)).lines
597
+ start = lines.index { |line| line.match?(/\A(['"]?)#{Regexp.escape(@result.name)}\1:/) }
598
+ finish = start && ((start + 1...lines.size).find { |index| lines[index].match?(/\A\S/) } || lines.size)
599
+ "take the lines of #{@result.name} out of #{shown(@source)}#{start ? " (lines #{start + 1} to #{finish})" : ''}"
600
+ end
601
+
602
+ def report
603
+ calls = @result.calls
604
+ @out.puts "#{@result.name} #{@result.version} now comes from a portable recipe: #{calls} call#{'s' unless calls == 1}"
605
+ @out.puts '', 'Changed in the project'
606
+ @out.puts " created #{@target}, with its line in #{@lock}"
607
+ @planned.each do |file, text|
608
+ @out.puts(text.nil? ? " deleted #{shown(file)}" : " edited #{shown(file)}: #{@notes[file].compact.join(', and ')}")
609
+ end
610
+ unless @result.changes.empty?
611
+ @out.puts '', 'What changed in the description'
612
+ @result.changes.each { |change| @out.puts " #{change}" }
613
+ end
614
+ unless @left.empty?
615
+ @out.puts '', 'Left to you'
616
+ @left.each { |one| @out.puts " - #{one}" }
617
+ end
618
+ @out.puts '', 'Every change is in `git status` and `git diff`. Check the recipes with `api_recipes check`, then start ' \
619
+ 'the application.'
620
+ end
621
+ end
622
+ end
623
+ end
624
+ end