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.
@@ -0,0 +1,206 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'open3'
4
+ require 'pathname'
5
+
6
+ module ApiRecipes
7
+ module CLI
8
+ class Upgrade
9
+ # The changes `upgrade` makes by itself. Each is shown as a diff and is
10
+ # made only when the person answers yes, on a terminal. A change
11
+ # touches only files that git has committed as they are now, so that
12
+ # it can be seen and undone, and writes all its files or none.
13
+ class Fix
14
+ # key: what the change is, said once. texts: { file => its new text }.
15
+ # note: what yes and no mean, when the title does not say it: a line
16
+ # of text, then one entry for each answer.
17
+ Change = Data.define(:key, :title, :texts, :note) do
18
+ def initialize(key:, title:, texts:, note: nil) = super
19
+ end
20
+
21
+ # Whether someone is there to read the question and answer it: the
22
+ # answers come from a terminal, and the results go to one.
23
+ def self.asks?(input, out) = [input, out].all? { |io| io.respond_to?(:tty?) && io.tty? }
24
+
25
+ # shown: how the name of a file is shown. ours: { file => text } for
26
+ # the files that this run of the command already changed.
27
+ def initialize(screen, input, shown:, root: '.', ours: {})
28
+ @screen = screen
29
+ @input = input
30
+ @shown = shown
31
+ @root = root
32
+ @ours = ours
33
+ end
34
+
35
+ # Shows a change that another part of the command works out and
36
+ # makes: the files it creates, edits and deletes. Returns whether
37
+ # the answer was yes.
38
+ def confirm(title, note, preview)
39
+ @screen.section('🔧', title)
40
+ if note
41
+ @screen.line(note.first)
42
+ note.drop(1).each { |answer| @screen.item(answer) }
43
+ end
44
+ preview[:created].each { |file, text| @screen.created(@shown.call(file), text) }
45
+ preview[:edited].each { |file, (before, after)| @screen.diff(@shown.call(file), before, after) }
46
+ preview[:deleted].each { |file| @screen.deleted(@shown.call(file)) }
47
+ @screen.ask('Make this change?', @input)
48
+ end
49
+
50
+ # Shows the change and asks. Returns the files it wrote, or nil when
51
+ # the change was not made.
52
+ def offer(change)
53
+ @screen.section('🔧', change.title)
54
+ reason = blocked(change)
55
+ if reason
56
+ @screen.line("This command does not make the change: #{reason}. The code to paste is below.")
57
+ return nil
58
+ end
59
+ if change.note
60
+ @screen.line(change.note.first)
61
+ change.note.drop(1).each { |answer| @screen.item(answer) }
62
+ @screen.gap
63
+ end
64
+ before = change.texts.keys.to_h { |file| [file, File.read(full(file))] }
65
+ change.texts.each { |file, text| @screen.diff(@shown.call(file), before[file], text) }
66
+ return nil unless @screen.ask('Make this change?', @input)
67
+
68
+ changed = change.texts.keys.find { |file| File.read(full(file)) != before[file] }
69
+ if changed
70
+ @screen.line("#{@shown.call(changed)} changed while the question waited: nothing was written. Run the command again.")
71
+ return nil
72
+ end
73
+ write(change, before) ? change.texts.keys : nil
74
+ rescue SystemCallError => e
75
+ @screen.line("The change could not be written (#{e.class.name.split('::').last}): nothing was written")
76
+ nil
77
+ end
78
+
79
+ private
80
+
81
+ def full(file) = File.join(@root, file)
82
+
83
+ def git(*arguments)
84
+ Open3.capture2e({ 'GIT_OPTIONAL_LOCKS' => '0' }, *Convert::Migration::GIT, '-C', @root, *arguments)
85
+ rescue SystemCallError
86
+ ['', nil]
87
+ end
88
+
89
+ # Why the change cannot be made, or nil.
90
+ def blocked(change)
91
+ _, status = git('--version')
92
+ return 'git was not found, and without it a change could not be seen or undone' unless status&.success?
93
+
94
+ file = change.texts.keys.find { |one| !(committed?(one) || ours?(one)) || !File.writable?(full(one)) }
95
+ return "#{@shown.call(file)} is not a file that git has committed as it is now, so what changes could not be brought back" if file
96
+
97
+ # The lines of a change are written with LF, and a diff would not show the difference.
98
+ crlf = change.texts.keys.find { |one| File.binread(full(one)).include?("\r") }
99
+ crlf && "#{@shown.call(crlf)} ends its lines with CR LF, which this change would not keep"
100
+ end
101
+
102
+ # A plain file of the project: not a symbolic link, not below one,
103
+ # not outside the project.
104
+ def plain?(file)
105
+ path = full(file)
106
+ return false if File.symlink?(path) || !File.file?(path)
107
+
108
+ File.realpath(path) == File.join(File.realpath(@root), Pathname.new(file).cleanpath.to_s)
109
+ rescue SystemCallError
110
+ false
111
+ end
112
+
113
+ # Whether git tracks the file as it does any other, and has it
114
+ # committed as it is now.
115
+ def committed?(file)
116
+ listed, status = git('ls-files', '-v', '--error-unmatch', '--', file)
117
+ return false unless plain?(file) && status&.success? && listed.start_with?('H ')
118
+
119
+ Convert::Migration.as_committed?(file, full(file)) { |*arguments| git(*arguments) }
120
+ end
121
+
122
+ # Whether the file is as this command left it, after a change made
123
+ # to it when git had it committed.
124
+ def ours?(file) = plain?(file) && @ours.key?(file) && File.read(full(file)) == @ours[file]
125
+
126
+ # Writes every file of the change. When one cannot be written, every
127
+ # file is put back: also the one that failed, which can be emptied.
128
+ def write(change, before)
129
+ change.texts.each { |file, text| File.write(full(file), text) }
130
+ @ours.merge!(change.texts)
131
+ true
132
+ rescue SystemCallError => e
133
+ lost = change.texts.keys.reject do |file|
134
+ File.write(full(file), before[file])
135
+ true
136
+ rescue SystemCallError
137
+ false
138
+ end
139
+ @screen.line("The change could not be written (#{e.class.name.split('::').last}): " \
140
+ "#{lost.empty? ? 'every file was put back as it was' : "these files could not be put back: #{lost.map { |file| @shown.call(file) }.join(', ')}"}")
141
+ false
142
+ end
143
+ end
144
+
145
+ # The lines that differ between two texts, with the lines around them.
146
+ module Diff
147
+ # Above this many pairs of lines the middle of the texts is not compared line by line.
148
+ LIMIT = 400_000
149
+
150
+ # [[first line of the old text, [[sign, line], ...]], ...] where sign
151
+ # is '-' for a line taken out, '+' for one added and ' ' for one kept.
152
+ def self.hunks(old, new, context: 2)
153
+ steps = steps(old.lines(chomp: true), new.lines(chomp: true))
154
+ changed = steps.each_index.reject { |index| steps[index].first == ' ' }
155
+ ranges = changed.map { |index| [[index - context, 0].max, [index + context, steps.size - 1].min] }
156
+ ranges = ranges.each_with_object([]) do |(from, to), merged|
157
+ merged.last && from <= merged.last[1] + 1 ? merged.last[1] = [merged.last[1], to].max : merged << [from, to]
158
+ end
159
+ ranges.map { |from, to| [steps[from][2], steps[from..to].map { |sign, line, _| [sign, line] }] }
160
+ end
161
+
162
+ # [[sign, line, number of the line in the old text], ...]
163
+ def self.steps(old, new)
164
+ head = 0
165
+ head += 1 while head < old.size && head < new.size && old[head] == new[head]
166
+ tail = 0
167
+ tail += 1 while tail < old.size - head && tail < new.size - head && old[-1 - tail] == new[-1 - tail]
168
+ from = old[head...old.size - tail]
169
+ to = new[head...new.size - tail]
170
+ middle = from.size * to.size > LIMIT ? from.map { |line| ['-', line] } + to.map { |line| ['+', line] } : compared(from, to)
171
+ number = 0
172
+ (old.first(head).map { |line| [' ', line] } + middle + old.last(tail).map { |line| [' ', line] }).map do |sign, line|
173
+ number += 1 unless sign == '+'
174
+ [sign, line, sign == '+' ? number + 1 : number]
175
+ end
176
+ end
177
+
178
+ # The longest run of lines the two lists share, and what is around it.
179
+ def self.compared(from, to)
180
+ lengths = Array.new(from.size + 1) { Array.new(to.size + 1, 0) }
181
+ (from.size - 1).downto(0) do |i|
182
+ (to.size - 1).downto(0) do |j|
183
+ lengths[i][j] = from[i] == to[j] ? lengths[i + 1][j + 1] + 1 : [lengths[i + 1][j], lengths[i][j + 1]].max
184
+ end
185
+ end
186
+ steps = []
187
+ i = j = 0
188
+ while i < from.size || j < to.size
189
+ if i < from.size && j < to.size && from[i] == to[j]
190
+ steps << [' ', from[i]]
191
+ i += 1
192
+ j += 1
193
+ elsif i < from.size && (j == to.size || lengths[i + 1][j] >= lengths[i][j + 1])
194
+ steps << ['-', from[i]]
195
+ i += 1
196
+ else
197
+ steps << ['+', to[j]]
198
+ j += 1
199
+ end
200
+ end
201
+ steps
202
+ end
203
+ end
204
+ end
205
+ end
206
+ end
@@ -0,0 +1,165 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ApiRecipes
4
+ module CLI
5
+ class Upgrade
6
+ # How `upgrade` shows its results: the same sections everywhere, and on
7
+ # a terminal colours, marks and lines that fit its width. The text it
8
+ # is given holds nothing a terminal obeys; it adds only its own marks.
9
+ class Screen
10
+ # The mark and the colour of each kind of finding, the worst first.
11
+ KINDS = { breaks: ['💥', 31], config: ['🧩', 35], check: ['👀', 33] }.freeze
12
+ WIDTHS = (60..110)
13
+
14
+ def initialize(out)
15
+ @out = out
16
+ @paint = Code::Paint.on?(out)
17
+ @width = @paint ? width_of(out) : nil
18
+ @blank = true
19
+ end
20
+
21
+ def paint? = @paint
22
+
23
+ # The title of a section. plain: false leaves it out where there are
24
+ # no colours, for lines that say by themselves what they are.
25
+ def section(mark, title, note = nil, plain: true)
26
+ gap
27
+ return unless @paint || plain
28
+
29
+ put(@paint ? "#{mark} #{style(title, 1)}#{note && " #{style(note, 2)}"}" : title)
30
+ gap if @paint
31
+ end
32
+
33
+ # A line of text of a section.
34
+ def line(text)
35
+ @paint ? wrapped(text, ' ', ' ').each { |one| put(one) } : put(text)
36
+ end
37
+
38
+ # An entry of a list. What comes before its first colon is what the
39
+ # entry is about.
40
+ def item(text, mark = nil)
41
+ return put(" #{mark || '-'} #{text}") unless @paint
42
+
43
+ first = " #{mark || '•'} "
44
+ wrapped(text, first, ' ' * first.length, bold: text.index(': ') || 0).each { |one| put(one) }
45
+ end
46
+
47
+ # A finding, and under it the code that takes the place of the line.
48
+ def finding(kind, where, message, hint = nil)
49
+ if @paint
50
+ mark, colour = KINDS.fetch(kind, ['•', 0])
51
+ put(" #{mark} #{style(kind.to_s.ljust(6), 1, colour)} #{style(where, 1)}")
52
+ wrapped(message, ' ', ' ').each { |one| put(one) }
53
+ else
54
+ put("#{where}: [#{kind}] #{message}")
55
+ end
56
+ hint ? code(hint) : (gap if @paint)
57
+ end
58
+
59
+ # Code to paste, with an empty line before and after it.
60
+ def code(lines, kind = :ruby)
61
+ indent = ' ' * (@paint ? 6 : 4)
62
+ gap
63
+ lines.each { |one| put(one.empty? ? '' : "#{indent}#{@paint ? Code::Paint.public_send(kind, one) : one}") }
64
+ gap
65
+ end
66
+
67
+ # What changes in a file: the lines taken out and the lines added,
68
+ # with the lines around them. A character that a terminal would
69
+ # obey is shown as a question mark.
70
+ def diff(file, old, new)
71
+ Diff.hunks(old, new).each do |first, lines|
72
+ gap
73
+ put(@paint ? " #{style("#{file}:#{first}", 1)}" : "#{file}:#{first}")
74
+ lines.each do |sign, text|
75
+ shown = "#{@paint ? ' ' : ''}#{sign} #{text.gsub(Code::UNSAFE, '?')}".rstrip
76
+ put(@paint ? style(shown, { '-' => 31, '+' => 32 }.fetch(sign, 2)) : shown)
77
+ end
78
+ end
79
+ gap
80
+ end
81
+
82
+ # A file that a change creates: its first lines, and how many follow.
83
+ def created(file, text, limit = 30)
84
+ lines = text.lines(chomp: true)
85
+ gap
86
+ put(@paint ? " #{style("#{file} (new file)", 1)}" : "#{file} (new file)")
87
+ lines.first(limit).each do |line|
88
+ shown = "#{@paint ? ' ' : ''}+ #{line.gsub(Code::UNSAFE, '?')}".rstrip
89
+ put(@paint ? style(shown, 32) : shown)
90
+ end
91
+ more = lines.size - limit
92
+ put("#{@paint ? ' ' : ''} ... and #{more} more line#{'s' unless more == 1}") if more.positive?
93
+ gap
94
+ end
95
+
96
+ # A file that a change deletes.
97
+ def deleted(file)
98
+ gap
99
+ put(@paint ? " #{style("#{file} (deleted)", 1, 31)}" : "#{file} (deleted)")
100
+ gap
101
+ end
102
+
103
+ # Asks, and tells whether the answer was yes.
104
+ def ask(question, input)
105
+ @out.print(@paint ? " #{style(question, 1)} [y/N] " : "#{question} [y/N] ")
106
+ @out.flush if @out.respond_to?(:flush)
107
+ answer = input.gets.to_s.strip.downcase
108
+ @blank = false
109
+ %w[y yes].include?(answer)
110
+ end
111
+
112
+ # The last line of the results: how many findings, and of which kinds.
113
+ def summary(text, counts)
114
+ gap
115
+ return put(text) unless @paint
116
+ return put("✅ #{style(text, 1, 32)}") if counts.empty?
117
+
118
+ worst = KINDS.keys.find { |kind| counts.key?(kind) } || :check
119
+ kinds = KINDS.keys.select { |kind| counts.key?(kind) }.map { |kind| style("#{counts[kind]} #{kind}", KINDS[kind].last) }
120
+ put("#{KINDS[worst].first} #{style(text, 1, KINDS[worst].last)} #{kinds.join(style(' · ', 2))}")
121
+ end
122
+
123
+ # One empty line, and never two.
124
+ def gap
125
+ put('') unless @blank
126
+ end
127
+
128
+ private
129
+
130
+ def put(text)
131
+ @out.puts(text)
132
+ @blank = text.empty?
133
+ end
134
+
135
+ def style(text, *codes) = "\e[#{codes.join(';')}m#{text}\e[0m"
136
+
137
+ def width_of(out)
138
+ require 'io/console'
139
+ columns = out.respond_to?(:winsize) ? out.winsize[1].to_i : 0
140
+ columns.zero? ? 80 : columns.clamp(WIDTHS.min, WIDTHS.max)
141
+ rescue StandardError
142
+ 80
143
+ end
144
+
145
+ # text on lines that fit the width, the first after first and the
146
+ # others after rest, with its first bold characters in bold.
147
+ def wrapped(text, first, rest, bold: 0)
148
+ room = @width - first.length
149
+ lines = []
150
+ text.split(' ').each do |word|
151
+ if lines.empty? || lines.last.length + 1 + word.length > room then lines << word.dup
152
+ else lines.last << ' ' << word
153
+ end
154
+ end
155
+ at = 0
156
+ lines.each_with_index.map do |one, index|
157
+ strong = (bold - at).clamp(0, one.length)
158
+ at += one.length + 1
159
+ "#{index.zero? ? first : rest}#{strong.zero? ? one : "#{style(one[0, strong], 1)}#{one[strong..]}"}"
160
+ end
161
+ end
162
+ end
163
+ end
164
+ end
165
+ end
@@ -0,0 +1,290 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ApiRecipes
4
+ module CLI
5
+ class Upgrade
6
+ # What changed in 3.0 and is found by reading the Ruby of a file as a
7
+ # tree, where a line alone does not tell. Nothing is run.
8
+ module TreeRules
9
+ Found = Data.define(:line, :kind, :message)
10
+
11
+ WRITERS = %i[authorization= basic_auth=].freeze
12
+ SENDS = %i[send public_send __send__].freeze
13
+ ADDRESS = %w[host protocol port].freeze
14
+ CREDENTIALS = %w[authorization basic_auth].freeze
15
+ WRITER = 'authorization= and basic_auth= now work on an object only: on ApiRecipes.name, on a class and on a module ' \
16
+ 'they raise. Give the credential to config.values, to `api :name, authorization: ...`, or to with(...) for one request'
17
+ NOT_TEXT = 'a credential must be a String: a Symbol or a number raises InvalidCredential, convert it with to_s'
18
+ RUN_VALUE = 'run with a block now returns the Response, not what the block returns: take the value inside the block, or from the response'
19
+ RESPONSE = {
20
+ request: 'request was removed from the response, because the request holds the credentials: read uri, or original_response',
21
+ to_s: 'to_s on a response now returns the body, as the http.rb response does: it was the default text of the object',
22
+ respond_to?: 'respond_to? on a response now tells the truth: true for the methods the response forwards, false for the others'
23
+ }.freeze
24
+
25
+ # What gives an api in a file: the names an api is called by, and
26
+ # the variables that hold one.
27
+ Scope = Data.define(:names, :holders)
28
+
29
+ # uses_gem: whether the code names ApiRecipes or calls an api. The
30
+ # rules that also match other code are applied only then, and only
31
+ # to what an api gives.
32
+ # reported: the lines where a rule on lines already found a writer.
33
+ # apis: the names the apis of the project are called by; those that
34
+ # the file declares with `api :name` are added.
35
+ def self.findings(text, uses_gem:, reported: [], apis: [])
36
+ tree = Code.tree(text)
37
+ return [] unless tree
38
+
39
+ found = []
40
+ scope = uses_gem ? scope_of(tree, apis) : nil
41
+ responses = uses_gem ? responses_of(tree, scope) : []
42
+ each(tree) do |node, parents|
43
+ constants(node, found) if node.is_a?(Prism::ClassNode) || node.is_a?(Prism::ModuleNode)
44
+ next unless uses_gem && node.is_a?(Prism::CallNode)
45
+
46
+ declaration(node, found)
47
+ writer(node, found, reported, scope)
48
+ block_value(node, parents, found, scope)
49
+ response(node, responses, found)
50
+ end
51
+ found.uniq.sort_by(&:line)
52
+ end
53
+
54
+ def self.scope_of(tree, apis)
55
+ names = apis.map(&:to_sym)
56
+ each(tree) do |node, _|
57
+ next unless node.is_a?(Prism::CallNode) && node.name == :api && node.receiver.nil?
58
+
59
+ first = node.arguments&.arguments&.first
60
+ names << first.unescaped.to_sym if first.is_a?(Prism::SymbolNode)
61
+ as = keywords(node).to_h['as']
62
+ names << as.unescaped.to_sym if as.is_a?(Prism::SymbolNode)
63
+ end
64
+ scope = Scope.new(names: names.uniq, holders: [])
65
+ # A variable or a method that gives an api can give another one:
66
+ # twice through the file finds those.
67
+ 2.times do
68
+ each(tree) do |node, _|
69
+ scope.holders << node.name if HOLDER.match?(node.class.name) && api?(node.value, scope)
70
+ scope.names << node.name if node.is_a?(Prism::DefNode) && api?(returned(node), scope)
71
+ end
72
+ end
73
+ scope
74
+ end
75
+
76
+ # What assigns a variable: =, ||=, &&= and the others.
77
+ HOLDER = /::(Local|Instance|Class|Global)Variable(Or|And|Operator)?WriteNode\z/
78
+
79
+ # What a method returns: the last statement of its body.
80
+ def self.returned(definition)
81
+ body = definition.body
82
+ body.is_a?(Prism::StatementsNode) ? body.body.last : body
83
+ end
84
+
85
+ # Whether node gives an api, or a part of one: ApiRecipes, a call of
86
+ # an api by its name, or a variable that holds one.
87
+ def self.api?(node, scope)
88
+ case node
89
+ when Prism::CallNode
90
+ scope.names.include?(node.name) || (node.receiver ? api?(node.receiver, scope) : false)
91
+ when Prism::ConstantReadNode, Prism::ConstantPathNode then node.slice.delete_prefix('::') == 'ApiRecipes'
92
+ when Prism::LocalVariableReadNode, Prism::InstanceVariableReadNode then scope.holders.include?(node.name)
93
+ else false
94
+ end
95
+ end
96
+
97
+ # Every node of the tree with the nodes that contain it, the nearest last.
98
+ def self.each(node, parents = [], &block)
99
+ return unless node
100
+
101
+ block.call(node, parents)
102
+ inside = parents + [node]
103
+ node.compact_child_nodes.each { |child| each(child, inside, &block) }
104
+ end
105
+
106
+ def self.at(node) = node.location.start_line
107
+
108
+ # The keys of the keywords of a call, when they are written as names.
109
+ def self.keywords(call)
110
+ hash = call.arguments&.arguments&.last
111
+ return [] unless hash.is_a?(Prism::KeywordHashNode)
112
+
113
+ hash.elements.filter_map { |pair| pair.is_a?(Prism::AssocNode) && pair.key.is_a?(Prism::SymbolNode) ? [pair.key.unescaped, pair.value] : nil }
114
+ end
115
+
116
+ # `api :name`: a name that is already a method, an address of its own
117
+ # without a credential of its own, a credential that is not text.
118
+ def self.declaration(call, found)
119
+ name = call.arguments&.arguments&.first
120
+ return unless call.name == :api && call.receiver.nil? && name.is_a?(Prism::SymbolNode)
121
+
122
+ given = keywords(call)
123
+ keys = given.map(&:first)
124
+ if !keys.include?('as') && taken?(name.unescaped)
125
+ found << Found.new(at(call), :breaks, "api :#{shown(name.unescaped)} raises ApiNameClashError, because a class already has a method " \
126
+ "with that name: give another one, as in `api :#{shown(name.unescaped)}, as: :another_name`")
127
+ end
128
+ if (keys & ADDRESS).any? && (keys & CREDENTIALS).empty?
129
+ found << Found.new(at(call), :check, "this class gives the api its own #{(keys & ADDRESS).join(', ')}: the credential of the application is " \
130
+ 'not sent to another address, so give the class its own, as in `api :name, host: ..., authorization: ...`')
131
+ end
132
+ given.each { |key, value| found << Found.new(at(value), :breaks, NOT_TEXT) if key == 'authorization' && not_text?(value) }
133
+ end
134
+
135
+ def self.shown(name) = name.match?(/\A\w{1,40}[?!]?\z/) ? name : 'name'
136
+
137
+ # Whether a class cannot have a method of that name for an api:
138
+ # what Declaration checks, on a class with nothing of its own.
139
+ def self.taken?(name)
140
+ return false unless Internals::Compiler::METHOD_NAME.match?(name)
141
+
142
+ probe = Class.new
143
+ Internals::Handles::RESERVED.include?(name.to_sym) || probe.respond_to?(name, true) || probe.method_defined?(name) ||
144
+ probe.private_method_defined?(name)
145
+ end
146
+
147
+ def self.not_text?(value) = [Prism::SymbolNode, Prism::IntegerNode, Prism::FloatNode].any? { |kind| value.is_a?(kind) }
148
+
149
+ # A credential assigned with a writer: where a rule on lines did not
150
+ # see it (in the body of a class, through a variable, over two
151
+ # lines, with send), and a value that is not text.
152
+ def self.writer(call, found, reported, scope)
153
+ return unless api?(call.receiver, scope)
154
+
155
+ if WRITERS.include?(call.name)
156
+ value = call.arguments&.arguments&.first
157
+ found << Found.new(at(call), :breaks, NOT_TEXT) if call.name == :authorization= && value && not_text?(value)
158
+ found << Found.new(at(call), :check, WRITER) unless reported.include?(at(call)) || reported.include?(call.location.end_line)
159
+ elsif SENDS.include?(call.name)
160
+ name = call.arguments&.arguments&.first
161
+ found << Found.new(at(call), :check, WRITER) if name.is_a?(Prism::SymbolNode) && WRITERS.include?(name.unescaped.to_sym)
162
+ end
163
+ end
164
+
165
+ # run with a block, where what it returns is assigned, returned,
166
+ # passed on or called.
167
+ def self.block_value(call, parents, found, scope)
168
+ return unless call.name == :run && call.block.is_a?(Prism::BlockNode) && api?(call.receiver, scope)
169
+
170
+ parent = parents.last
171
+ used = parent.class.name.end_with?('WriteNode') || parent.is_a?(Prism::ArgumentsNode) ||
172
+ (parent.is_a?(Prism::CallNode) && parent.receiver.equal?(call))
173
+ found << Found.new(at(call), :check, RUN_VALUE) if used
174
+ end
175
+
176
+ # The names of the variables that hold a response: what run returned,
177
+ # and what run passes to its block.
178
+ def self.responses_of(tree, scope)
179
+ names = []
180
+ each(tree) do |node, _|
181
+ if (node.is_a?(Prism::LocalVariableWriteNode) || node.is_a?(Prism::InstanceVariableWriteNode)) && run?(node.value, scope)
182
+ names << node.name
183
+ elsif run?(node, scope) && node.block.is_a?(Prism::BlockNode)
184
+ inner = node.block.parameters
185
+ first = inner.is_a?(Prism::BlockParametersNode) ? inner.parameters&.requireds&.first : nil
186
+ names << first.name if first.respond_to?(:name)
187
+ end
188
+ end
189
+ names.uniq
190
+ end
191
+
192
+ def self.run?(node, scope) = node.is_a?(Prism::CallNode) && node.name == :run && api?(node.receiver, scope)
193
+
194
+ def self.response(call, responses, found)
195
+ holder = call.receiver
196
+ return unless RESPONSE.key?(call.name) && (holder.is_a?(Prism::LocalVariableReadNode) || holder.is_a?(Prism::InstanceVariableReadNode))
197
+ return unless responses.include?(holder.name)
198
+ # `response.request` is found by the rule on lines.
199
+ return if call.name == :request && holder.name == :response
200
+
201
+ found << Found.new(at(call), :check, RESPONSE[call.name])
202
+ end
203
+
204
+ # The constants of the gem that a class finds first once it includes
205
+ # ApiRecipes: the errors, Internals and VERSION.
206
+ def self.shadowing
207
+ @shadowing ||= ApiRecipes.constants.select do |name|
208
+ value = ApiRecipes.const_get(name)
209
+ %i[Internals VERSION].include?(name) || (value.is_a?(Class) && value <= ApiRecipes::Error)
210
+ end
211
+ end
212
+
213
+ # In the body of a class or a module that includes ApiRecipes, a
214
+ # constant written alone that the gem has too, and that the body
215
+ # does not define.
216
+ def self.constants(owner, found)
217
+ body = owner.body.is_a?(Prism::StatementsNode) ? owner.body.body : []
218
+ includes = body.any? do |node|
219
+ node.is_a?(Prism::CallNode) && node.name == :include && node.receiver.nil? &&
220
+ node.arguments&.arguments&.any? { |one| one.slice.delete_prefix('::') == 'ApiRecipes' }
221
+ end
222
+ return unless includes
223
+
224
+ defined = body.filter_map do |node|
225
+ next node.name if node.is_a?(Prism::ConstantWriteNode)
226
+
227
+ node.constant_path.slice.to_sym if node.is_a?(Prism::ClassNode) || node.is_a?(Prism::ModuleNode)
228
+ end
229
+ each(owner.body) do |node, parents|
230
+ next unless node.is_a?(Prism::ConstantReadNode) && shadowing.include?(node.name) && !defined.include?(node.name)
231
+ # A class or a module written inside has its own constants.
232
+ next if parents.any? { |one| one.is_a?(Prism::ClassNode) || one.is_a?(Prism::ModuleNode) }
233
+ # In Name::Error only Name is looked for from here. An older
234
+ # Prism gives the last name of a path as a node of its own.
235
+ path = parents.last
236
+ next if path.is_a?(Prism::ConstantPathNode) && !path.parent.equal?(node)
237
+
238
+ found << Found.new(at(node), :check, "#{node.name} written alone in a class that includes ApiRecipes is now ApiRecipes::#{node.name}: " \
239
+ "write ::#{node.name} for a constant of the application with that name")
240
+ end
241
+ end
242
+ end
243
+
244
+ # What changed in 3.0 and is found in a file that describes apis.
245
+ module ConfigRules
246
+ INHERITED = %w[timeout on_bad_code mime_type verify_with].freeze
247
+
248
+ # [message, ...] for the description of one file: { name => options }.
249
+ def self.findings(apis)
250
+ found = []
251
+ apis.each { |name, options| walk(options, [place(name)], found, true) if options.is_a?(Hash) }
252
+ found
253
+ end
254
+
255
+ def self.place(name) = name.to_s.gsub(/[^[:print:]]/, '?')[0, 40]
256
+
257
+ def self.value(options, key) = options.key?(key) ? options[key] : options[key.to_sym]
258
+
259
+ def self.walk(options, path, found, root)
260
+ endpoints = value(options, 'endpoints')
261
+ return unless endpoints.is_a?(Hash)
262
+
263
+ endpoints.each do |name, body|
264
+ here = path + ['endpoints', place(name)]
265
+ base = root ? ApiRecipes::Api : ApiRecipes::Endpoint
266
+ if Internals::Compiler::METHOD_NAME.match?(name.to_s) && Internals::Handles.taken?(base, name.to_sym)
267
+ found << "#{here.join('.')}: an endpoint with this name has no method of its own, because #{place(name)} is a method of the " \
268
+ "object that would have it: reach it with [:#{place(name)}], or give it another name and its `path`"
269
+ end
270
+ next unless body.is_a?(Hash)
271
+
272
+ inside = value(body, 'endpoints')
273
+ if inside.is_a?(Hash)
274
+ INHERITED.each do |key|
275
+ next if value(body, key).nil?
276
+
277
+ without = inside.select { |_, child| !child.is_a?(Hash) || value(child, key).nil? }.keys.map { |child| place(child) }
278
+ next if without.empty?
279
+
280
+ found << "#{here.join('.')}: #{key} is set here, and the endpoints it contains that do not set it now find it here " \
281
+ "(#{without.first(5).join(', ')}#{', ...' if without.size > 5}): in 2.x they took the one of the api"
282
+ end
283
+ end
284
+ walk(body, here, found, false)
285
+ end
286
+ end
287
+ end
288
+ end
289
+ end
290
+ end