api_recipes 2.10.4 → 3.0.0.beta2
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.
- checksums.yaml +4 -4
- data/README.md +783 -81
- data/UPGRADING.md +473 -0
- data/exe/api_recipes +6 -0
- data/lib/api_recipes/api.rb +71 -49
- data/lib/api_recipes/cli/import/document.rb +234 -0
- data/lib/api_recipes/cli/import/security.rb +138 -0
- data/lib/api_recipes/cli/import/server.rb +166 -0
- data/lib/api_recipes/cli/import/tree.rb +288 -0
- data/lib/api_recipes/cli/import/writer.rb +127 -0
- data/lib/api_recipes/cli/import.rb +129 -0
- data/lib/api_recipes/cli/routes.rb +50 -0
- data/lib/api_recipes/cli/upgrade.rb +179 -0
- data/lib/api_recipes/cli.rb +166 -0
- data/lib/api_recipes/configuration.rb +185 -36
- data/lib/api_recipes/endpoint.rb +68 -118
- data/lib/api_recipes/errors.rb +137 -0
- data/lib/api_recipes/internals/compiler.rb +680 -0
- data/lib/api_recipes/internals/context.rb +237 -0
- data/lib/api_recipes/internals/credential.rb +86 -0
- data/lib/api_recipes/internals/declaration.rb +225 -0
- data/lib/api_recipes/internals/definition.rb +179 -0
- data/lib/api_recipes/internals/handles.rb +81 -0
- data/lib/api_recipes/internals/level.rb +192 -0
- data/lib/api_recipes/internals/path_template.rb +131 -0
- data/lib/api_recipes/internals/registry.rb +146 -0
- data/lib/api_recipes/internals/request.rb +285 -0
- data/lib/api_recipes/internals/template.rb +73 -0
- data/lib/api_recipes/response.rb +90 -9
- data/lib/api_recipes/version.rb +3 -1
- data/lib/api_recipes.rb +42 -152
- metadata +33 -12
- data/lib/api_recipes/exceptions.rb +0 -91
- data/lib/api_recipes/route.rb +0 -165
- data/lib/api_recipes/settings.rb +0 -30
- data/lib/api_recipes/utils.rb +0 -195
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module ApiRecipes
|
|
4
|
+
module CLI
|
|
5
|
+
class Import
|
|
6
|
+
# The endpoints of a recipe, from the `paths` of a description.
|
|
7
|
+
#
|
|
8
|
+
# A segment without parameters is a name, and each name is a node. The
|
|
9
|
+
# parameters that come before a name travel with that name; those at the
|
|
10
|
+
# end of the path travel with the operation. GET on a path that ends with
|
|
11
|
+
# a name is the node itself; every other operation is a child of the node
|
|
12
|
+
# of the last name, called after its verb.
|
|
13
|
+
class Tree
|
|
14
|
+
Node = Struct.new(:name, :options, :comment, :children)
|
|
15
|
+
Result = Data.define(:nodes, :warnings, :operations, :paths, :skipped)
|
|
16
|
+
|
|
17
|
+
METHODS = %w[get put post delete options head patch trace].freeze
|
|
18
|
+
# [name on a path that ends with a name, name on a path that ends with a parameter]
|
|
19
|
+
NAMES = { 'get' => [nil, 'show'], 'post' => %w[create post], 'put' => %w[replace_all replace],
|
|
20
|
+
'patch' => %w[update_all update], 'delete' => %w[delete_all delete] }.freeze
|
|
21
|
+
PARAMETER = /\{([^{}]*)\}/
|
|
22
|
+
SUCCESS_STATUS = /\A2\d\d\z/
|
|
23
|
+
|
|
24
|
+
# A node while the tree is built. key tells apart two nodes of the same
|
|
25
|
+
# parent: it is the text of the description, so two paths that the gem
|
|
26
|
+
# writes in the same way stay two nodes. base is the name before the
|
|
27
|
+
# numbers that keep siblings apart; index finds a child node by its key.
|
|
28
|
+
Entry = Struct.new(:base, :name, :key, :path, :verb, :get, :ok_code, :comment, :operation, :children, :index)
|
|
29
|
+
|
|
30
|
+
def self.build(document, only: [], except: [])
|
|
31
|
+
new(document, only, except).build
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
def initialize(document, only, except)
|
|
35
|
+
@document = document
|
|
36
|
+
@only = only.map { |glob| pattern(glob) }
|
|
37
|
+
@except = except.map { |glob| pattern(glob) }
|
|
38
|
+
@warnings = []
|
|
39
|
+
@top = entry(nil, nil)
|
|
40
|
+
@operations = 0
|
|
41
|
+
@paths = 0
|
|
42
|
+
@skipped = 0
|
|
43
|
+
@servers = false
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
def build
|
|
47
|
+
paths = @document.root['paths']
|
|
48
|
+
paths.each { |path, item| add_path(path, item) } if paths.is_a?(Hash)
|
|
49
|
+
@warnings << 'servers given for a path or an operation are not used: the recipe has one address' if @servers
|
|
50
|
+
name_children(@top, nil)
|
|
51
|
+
Result.new(nodes: nodes_of(@top), warnings: @warnings, operations: @operations, paths: @paths,
|
|
52
|
+
skipped: @skipped)
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
private
|
|
56
|
+
|
|
57
|
+
def entry(base, key, **fields)
|
|
58
|
+
Entry.new(base: base, key: key, children: [], index: {}, **fields)
|
|
59
|
+
end
|
|
60
|
+
|
|
61
|
+
# ---- reading ----
|
|
62
|
+
|
|
63
|
+
def add_path(path, item)
|
|
64
|
+
unless path.is_a?(String) && path.start_with?('/')
|
|
65
|
+
@warnings << "the path #{Import.shown(path)} does not start with /: it was left out"
|
|
66
|
+
return
|
|
67
|
+
end
|
|
68
|
+
# A path that the filters leave out is not read: only counted, when
|
|
69
|
+
# its operations are in the description itself.
|
|
70
|
+
unless selected?(path)
|
|
71
|
+
@skipped += METHODS.count { |method| item[method].is_a?(Hash) } if item.is_a?(Hash)
|
|
72
|
+
return
|
|
73
|
+
end
|
|
74
|
+
item = @document.resolve(item, "paths.#{Import.shown(path)}")
|
|
75
|
+
unless item.is_a?(Hash)
|
|
76
|
+
@warnings << "the path #{Import.shown(path)} is not a mapping: it was left out"
|
|
77
|
+
return
|
|
78
|
+
end
|
|
79
|
+
methods = METHODS.select { |method| item[method].is_a?(Hash) }
|
|
80
|
+
return if methods.empty?
|
|
81
|
+
|
|
82
|
+
@paths += 1
|
|
83
|
+
@servers ||= item.key?('servers') || methods.any? { |method| item[method].key?('servers') }
|
|
84
|
+
problem = unwritable(path)
|
|
85
|
+
if problem
|
|
86
|
+
@warnings << "#{Import.shown(path)} (#{methods.size} operation#{'s' unless methods.size == 1}) cannot be " \
|
|
87
|
+
"written as a path of the gem, because #{problem}: it was left out"
|
|
88
|
+
return
|
|
89
|
+
end
|
|
90
|
+
place(path, path.split('/').reject(&:empty?), item, methods)
|
|
91
|
+
end
|
|
92
|
+
|
|
93
|
+
def selected?(path)
|
|
94
|
+
forms = [path, path.delete_prefix('/')]
|
|
95
|
+
return false if @except.any? { |regexp| forms.any? { |form| regexp.match?(form) } }
|
|
96
|
+
|
|
97
|
+
@only.empty? || @only.any? { |regexp| forms.any? { |form| regexp.match?(form) } }
|
|
98
|
+
end
|
|
99
|
+
|
|
100
|
+
# `*` crosses slashes; every other character stands for itself.
|
|
101
|
+
def pattern(glob)
|
|
102
|
+
Regexp.new("\\A#{Regexp.escape(glob.to_s).gsub('\\*', '.*')}\\z")
|
|
103
|
+
end
|
|
104
|
+
|
|
105
|
+
def parameter?(segment) = segment.match?(PARAMETER)
|
|
106
|
+
|
|
107
|
+
# Why the gem cannot write a path, or nil. The gem reads `:name` up to
|
|
108
|
+
# the last letter, digit or _; it reads `*name` at the start of a segment
|
|
109
|
+
# as a parameter that spans segments; and it joins two slashes into one.
|
|
110
|
+
def unwritable(path)
|
|
111
|
+
segments = path.split('/', -1).drop(1)
|
|
112
|
+
segments.pop if segments.last == ''
|
|
113
|
+
return 'it has an empty segment' if segments.include?('')
|
|
114
|
+
if segments.any? { |segment| segment.match?(/\{[^{}]*\}\w/) }
|
|
115
|
+
return 'text that starts with a letter, a digit or _ comes right after a parameter'
|
|
116
|
+
end
|
|
117
|
+
return 'a segment starts with * and a name' if segments.any? { |segment| segment.match?(/\A\*[A-Za-z_]/) }
|
|
118
|
+
|
|
119
|
+
nil
|
|
120
|
+
end
|
|
121
|
+
|
|
122
|
+
def place(path, segments, item, methods)
|
|
123
|
+
slash = path.length > 1 && path.end_with?('/')
|
|
124
|
+
node = @top
|
|
125
|
+
pending = []
|
|
126
|
+
segments.each_with_index do |segment, index|
|
|
127
|
+
if parameter?(segment)
|
|
128
|
+
pending << segment
|
|
129
|
+
next
|
|
130
|
+
end
|
|
131
|
+
closing = slash && index == segments.size - 1
|
|
132
|
+
key = "#{(pending + [segment]).join('/')}#{'/' if closing}"
|
|
133
|
+
node = node.index[key] ||=
|
|
134
|
+
add_child(node, entry(name_of(segment), key, path: written_path(pending + [segment], closing)))
|
|
135
|
+
pending = []
|
|
136
|
+
end
|
|
137
|
+
methods.each { |method| add_operation(node, method, pending, slash, path, item) }
|
|
138
|
+
end
|
|
139
|
+
|
|
140
|
+
def add_child(parent, child)
|
|
141
|
+
parent.children << child
|
|
142
|
+
child
|
|
143
|
+
end
|
|
144
|
+
|
|
145
|
+
def add_operation(node, method, pending, slash, path, item)
|
|
146
|
+
@operations += 1
|
|
147
|
+
operation = item[method]
|
|
148
|
+
fields = { ok_code: ok_code(operation), comment: comment(method, path, item, operation) }
|
|
149
|
+
if pending.empty? && !node.equal?(@top) && method == 'get'
|
|
150
|
+
node.get = true
|
|
151
|
+
node.ok_code = fields[:ok_code]
|
|
152
|
+
node.comment = fields[:comment]
|
|
153
|
+
return
|
|
154
|
+
end
|
|
155
|
+
|
|
156
|
+
name = if pending.empty?
|
|
157
|
+
node.equal?(@top) && method == 'get' ? 'root' : (NAMES.dig(method, 0) || method)
|
|
158
|
+
else
|
|
159
|
+
NAMES.dig(method, 1) || "#{method}_one"
|
|
160
|
+
end
|
|
161
|
+
add_child(node, entry(name, nil, operation: true, verb: method,
|
|
162
|
+
path: pending.empty? ? '' : written_path(pending, slash), **fields))
|
|
163
|
+
end
|
|
164
|
+
|
|
165
|
+
# ---- writing paths and names ----
|
|
166
|
+
|
|
167
|
+
# "/:owner/:repo/issues" for the segments ['{owner}', '{repo}', 'issues'].
|
|
168
|
+
def written_path(segments, slash)
|
|
169
|
+
used = {}
|
|
170
|
+
text = segments.map do |segment|
|
|
171
|
+
pieces = segment.split(PARAMETER, -1)
|
|
172
|
+
pieces.each_with_index.map do |piece, index|
|
|
173
|
+
index.odd? ? ":#{parameter_name(piece, used)}" : piece.gsub(':', '\\:')
|
|
174
|
+
end.join
|
|
175
|
+
end.join('/')
|
|
176
|
+
"/#{text}#{'/' if slash}"
|
|
177
|
+
end
|
|
178
|
+
|
|
179
|
+
# The name of a parameter with letters, digits and _ only, and with a
|
|
180
|
+
# number when the same path already has one with that name.
|
|
181
|
+
def parameter_name(original, used)
|
|
182
|
+
base = original.gsub(/\W/, '_')
|
|
183
|
+
base = "_#{base}" unless base.match?(/\A[A-Za-z_]/)
|
|
184
|
+
name = base
|
|
185
|
+
count = 1
|
|
186
|
+
name = "#{base}_#{count += 1}" while used.key?(name)
|
|
187
|
+
used[name] = true
|
|
188
|
+
name
|
|
189
|
+
end
|
|
190
|
+
|
|
191
|
+
def name_of(segment)
|
|
192
|
+
segment.gsub(/([a-z\d])([A-Z])/, '\1_\2').gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
|
|
193
|
+
.downcase.gsub(/[^a-z0-9]/, '_')
|
|
194
|
+
end
|
|
195
|
+
|
|
196
|
+
# The nodes born from segments take their names first, then the
|
|
197
|
+
# operations, each in the order of the description.
|
|
198
|
+
def name_children(parent, parent_name)
|
|
199
|
+
taken = {}
|
|
200
|
+
(parent.children.reject(&:operation) + parent.children.select(&:operation)).each do |child|
|
|
201
|
+
child.name = free_name(child.base, taken)
|
|
202
|
+
full = [parent_name, child.name].compact.join('.')
|
|
203
|
+
unless child.name == child.base
|
|
204
|
+
@warnings << "#{parent_name || 'the api'} has two endpoints called #{Import.shown(child.base)}: " \
|
|
205
|
+
"one is written #{Import.shown(child.name)}"
|
|
206
|
+
end
|
|
207
|
+
warn_unreachable(parent, child, full)
|
|
208
|
+
name_children(child, full)
|
|
209
|
+
end
|
|
210
|
+
end
|
|
211
|
+
|
|
212
|
+
def free_name(base, taken)
|
|
213
|
+
name = base
|
|
214
|
+
count = 1
|
|
215
|
+
name = "#{base}_#{count += 1}" while taken.key?(name)
|
|
216
|
+
taken[name] = true
|
|
217
|
+
name
|
|
218
|
+
end
|
|
219
|
+
|
|
220
|
+
def warn_unreachable(parent, child, full)
|
|
221
|
+
base = parent.equal?(@top) ? ApiRecipes::Api : ApiRecipes::Endpoint
|
|
222
|
+
method_name = Internals::Compiler::METHOD_NAME.match?(child.name)
|
|
223
|
+
return if method_name && !Internals::Handles.taken?(base, child.name.to_sym)
|
|
224
|
+
|
|
225
|
+
reason = method_name ? 'has the name of an existing method' : 'is not the name of a method'
|
|
226
|
+
@warnings << "the endpoint #{Import.shown(full)} #{reason}: reach it with [#{Import.shown(child.name)}]"
|
|
227
|
+
end
|
|
228
|
+
|
|
229
|
+
# ---- what an operation says ----
|
|
230
|
+
|
|
231
|
+
# The 2xx statuses the operation documents: one, or the list. Nothing
|
|
232
|
+
# when 200 is the only one, since the gem accepts every 2xx by default.
|
|
233
|
+
def ok_code(operation)
|
|
234
|
+
responses = operation['responses']
|
|
235
|
+
return nil unless responses.is_a?(Hash)
|
|
236
|
+
|
|
237
|
+
codes = responses.keys.map { |key| Import.text(key).to_s }.grep(SUCCESS_STATUS).map(&:to_i).uniq.sort
|
|
238
|
+
return nil if codes.empty? || codes == [200]
|
|
239
|
+
|
|
240
|
+
codes.size == 1 ? codes.first : codes
|
|
241
|
+
end
|
|
242
|
+
|
|
243
|
+
def comment(method, path, item, operation)
|
|
244
|
+
details = []
|
|
245
|
+
details << operation['operationId'] if operation['operationId'].is_a?(String)
|
|
246
|
+
details << 'deprecated' if operation['deprecated'] == true
|
|
247
|
+
query = query_parameters(path, item, operation)
|
|
248
|
+
details << "query: #{query.join(', ')}" unless query.empty?
|
|
249
|
+
Import.one_line("#{method.upcase} #{path}#{" (#{details.join('; ')})" unless details.empty?}")
|
|
250
|
+
end
|
|
251
|
+
|
|
252
|
+
# The query parameters of the path and of the operation, the second
|
|
253
|
+
# over the first, with a star on the required ones.
|
|
254
|
+
def query_parameters(path, item, operation)
|
|
255
|
+
found = {}
|
|
256
|
+
[item['parameters'], operation['parameters']].each do |list|
|
|
257
|
+
next unless list.is_a?(Array)
|
|
258
|
+
|
|
259
|
+
list.each do |parameter|
|
|
260
|
+
parameter = @document.resolve(parameter, "paths.#{Import.shown(path)}.parameters")
|
|
261
|
+
next unless parameter.is_a?(Hash) && parameter['in'] == 'query' && parameter['name'].is_a?(String)
|
|
262
|
+
|
|
263
|
+
found[parameter['name']] = parameter['required'] == true
|
|
264
|
+
end
|
|
265
|
+
end
|
|
266
|
+
found.map { |name, required| "#{name}#{'*' if required}" }
|
|
267
|
+
end
|
|
268
|
+
|
|
269
|
+
# ---- result ----
|
|
270
|
+
|
|
271
|
+
def nodes_of(parent)
|
|
272
|
+
parent.children.map do |child|
|
|
273
|
+
Node.new(child.name, options_of(child), child.comment, nodes_of(child))
|
|
274
|
+
end
|
|
275
|
+
end
|
|
276
|
+
|
|
277
|
+
def options_of(child)
|
|
278
|
+
options = {}
|
|
279
|
+
options[:path] = child.path unless child.path == "/#{child.name}"
|
|
280
|
+
options[:verb] = child.verb if child.verb && child.verb != 'get'
|
|
281
|
+
options[:route] = false unless child.operation || child.get
|
|
282
|
+
options[:ok_code] = child.ok_code if child.ok_code
|
|
283
|
+
options
|
|
284
|
+
end
|
|
285
|
+
end
|
|
286
|
+
end
|
|
287
|
+
end
|
|
288
|
+
end
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require 'yaml'
|
|
4
|
+
|
|
5
|
+
module ApiRecipes
|
|
6
|
+
module CLI
|
|
7
|
+
class Import
|
|
8
|
+
# The text of a recipe: the api, its options, the tree of endpoints and a
|
|
9
|
+
# comment beside each operation. Every name and every value is written by
|
|
10
|
+
# Ruby's YAML generator. Before the text is returned it is read back and
|
|
11
|
+
# compared with the data it was written from.
|
|
12
|
+
class Writer
|
|
13
|
+
API_KEYS = %i[protocol host port base_url auth variables].freeze
|
|
14
|
+
ENDPOINT_KEYS = %i[path verb route ok_code].freeze
|
|
15
|
+
COMMENT_COLUMN = 34
|
|
16
|
+
MAX_NAME = 1000
|
|
17
|
+
# Control characters, and the two separators that YAML reads as a new line.
|
|
18
|
+
LINE_BREAKING = /[[:cntrl:]\u2028\u2029]/
|
|
19
|
+
INTERNAL = 'internal error: the recipe does not read back as it was written, so nothing was written'
|
|
20
|
+
|
|
21
|
+
def initialize(name:, options:, nodes:, header: nil)
|
|
22
|
+
@name = name
|
|
23
|
+
@options = options
|
|
24
|
+
@nodes = nodes
|
|
25
|
+
@header = header
|
|
26
|
+
end
|
|
27
|
+
|
|
28
|
+
def to_yaml
|
|
29
|
+
@lines = []
|
|
30
|
+
header = Import.one_line(@header)
|
|
31
|
+
@lines << "# #{header}" unless header.empty?
|
|
32
|
+
data = { @name => api }
|
|
33
|
+
text = "#{@lines.join("\n")}\n"
|
|
34
|
+
raise Error, INTERNAL unless read_back(text) == data
|
|
35
|
+
|
|
36
|
+
text
|
|
37
|
+
end
|
|
38
|
+
|
|
39
|
+
private
|
|
40
|
+
|
|
41
|
+
def read_back(text)
|
|
42
|
+
YAML.safe_load(text)
|
|
43
|
+
rescue Psych::Exception
|
|
44
|
+
raise Error, INTERNAL
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
def api
|
|
48
|
+
line(0, "#{scalar(@name, '', 'the name of the api')}:")
|
|
49
|
+
body = {}
|
|
50
|
+
API_KEYS.each do |key|
|
|
51
|
+
body[key.to_s] = value(1, key.to_s, @options[key], "#{@name}.#{key}") if @options.key?(key)
|
|
52
|
+
end
|
|
53
|
+
unless @nodes.empty?
|
|
54
|
+
line(1, 'endpoints:')
|
|
55
|
+
body['endpoints'] = nodes(@nodes, 2, "#{@name}.endpoints")
|
|
56
|
+
end
|
|
57
|
+
body.empty? ? nil : body
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
def nodes(list, indent, where)
|
|
61
|
+
list.to_h do |node|
|
|
62
|
+
name = scalar(node.name, where, 'the name of an endpoint')
|
|
63
|
+
comment = Import.one_line(node.comment)
|
|
64
|
+
line(indent, "#{name}:", comment.empty? ? nil : comment)
|
|
65
|
+
here = "#{where}.#{node.name}"
|
|
66
|
+
body = {}
|
|
67
|
+
ENDPOINT_KEYS.each do |key|
|
|
68
|
+
body[key.to_s] = value(indent + 1, key.to_s, node.options[key], "#{here}.#{key}") if node.options.key?(key)
|
|
69
|
+
end
|
|
70
|
+
unless node.children.empty?
|
|
71
|
+
line(indent + 1, 'endpoints:')
|
|
72
|
+
body['endpoints'] = nodes(node.children, indent + 2, "#{here}.endpoints")
|
|
73
|
+
end
|
|
74
|
+
[node.name, body.empty? ? nil : body]
|
|
75
|
+
end
|
|
76
|
+
end
|
|
77
|
+
|
|
78
|
+
# Writes key and content, and returns the content as YAML will read it.
|
|
79
|
+
def value(indent, key, content, where)
|
|
80
|
+
key = scalar(key, where, 'a name')
|
|
81
|
+
case content
|
|
82
|
+
when Hash
|
|
83
|
+
if content.empty?
|
|
84
|
+
line(indent, "#{key}: {}")
|
|
85
|
+
{}
|
|
86
|
+
else
|
|
87
|
+
line(indent, "#{key}:")
|
|
88
|
+
content.to_h { |name, item| [name.to_s, value(indent + 1, name.to_s, item, "#{where}.#{name}")] }
|
|
89
|
+
end
|
|
90
|
+
when Array
|
|
91
|
+
line(indent, "#{key}: [#{content.map { |item| scalar(item, where) }.join(', ')}]")
|
|
92
|
+
content
|
|
93
|
+
else
|
|
94
|
+
line(indent, "#{key}: #{scalar(content, where)}")
|
|
95
|
+
content
|
|
96
|
+
end
|
|
97
|
+
end
|
|
98
|
+
|
|
99
|
+
def line(indent, text, comment = nil)
|
|
100
|
+
text = "#{' ' * indent}#{text}"
|
|
101
|
+
text = "#{text.ljust(COMMENT_COLUMN - 1)} # #{comment}" if comment
|
|
102
|
+
@lines << text
|
|
103
|
+
end
|
|
104
|
+
|
|
105
|
+
# One name or one plain value as the YAML generator writes it, on one
|
|
106
|
+
# line. Text that a recipe file would run as ERB, or that would start a
|
|
107
|
+
# new line, is refused; the message says where and never shows it.
|
|
108
|
+
def scalar(content, where, what = nil)
|
|
109
|
+
place = [where.empty? ? nil : "#{where}:", what].compact.join(' ')
|
|
110
|
+
if content.is_a?(String)
|
|
111
|
+
raise Error, "#{place} is not valid text" unless content.valid_encoding?
|
|
112
|
+
raise Error, "#{place} contains <%, which a recipe file would run as ERB" if content.include?('<%')
|
|
113
|
+
raise Error, "#{place} contains a control character" if content.match?(LINE_BREAKING)
|
|
114
|
+
# YAML does not read a name longer than 1024 characters.
|
|
115
|
+
raise Error, "#{place} is longer than #{MAX_NAME} characters" if what && content.length > MAX_NAME
|
|
116
|
+
elsif !(content.is_a?(Integer) || content == true || content == false)
|
|
117
|
+
raise Error, INTERNAL
|
|
118
|
+
end
|
|
119
|
+
written = YAML.dump([content], line_width: -1)[/\A---\n- (.*)\n\z/m, 1]
|
|
120
|
+
raise Error, INTERNAL if written.nil? || written.include?("\n")
|
|
121
|
+
|
|
122
|
+
written
|
|
123
|
+
end
|
|
124
|
+
end
|
|
125
|
+
end
|
|
126
|
+
end
|
|
127
|
+
end
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require 'date'
|
|
4
|
+
|
|
5
|
+
module ApiRecipes
|
|
6
|
+
module CLI
|
|
7
|
+
# The import command: writes a recipe from an OpenAPI description. The
|
|
8
|
+
# description is read once, from one local file, and nothing in it is run.
|
|
9
|
+
class Import
|
|
10
|
+
# The description cannot be imported. The message says where and why.
|
|
11
|
+
class Error < ApiRecipes::Error; end
|
|
12
|
+
|
|
13
|
+
Result = Data.define(:text, :warnings, :summary)
|
|
14
|
+
MAX_WARNINGS = 100
|
|
15
|
+
|
|
16
|
+
def initialize(path, name: nil, only: [], except: [], server: 0)
|
|
17
|
+
@path = path
|
|
18
|
+
@name = name
|
|
19
|
+
@only = only
|
|
20
|
+
@except = except
|
|
21
|
+
@server = server
|
|
22
|
+
end
|
|
23
|
+
|
|
24
|
+
# Reads the description and returns the text of the recipe with the
|
|
25
|
+
# warnings and the summary. Raises Error when it cannot be imported:
|
|
26
|
+
# nothing is returned unless the text is a recipe the gem accepts.
|
|
27
|
+
def call
|
|
28
|
+
document = Document.load(@path)
|
|
29
|
+
name, warnings = api_name(document)
|
|
30
|
+
server = Server.read(document, @server)
|
|
31
|
+
security = Security.read(document)
|
|
32
|
+
tree = Tree.build(document, only: @only, except: @except)
|
|
33
|
+
options = server.options.dup
|
|
34
|
+
options[:auth] = security.auth if security.auth
|
|
35
|
+
header = "Generated by api_recipes import from #{document.title} #{document.version}"
|
|
36
|
+
text = Writer.new(name: name, options: options, nodes: tree.nodes, header: header).to_yaml
|
|
37
|
+
verify(text)
|
|
38
|
+
warnings += server.warnings + security.warnings + tree.warnings
|
|
39
|
+
warnings << 'no operation was imported' if tree.operations.zero?
|
|
40
|
+
Result.new(text: text, warnings: shown_warnings(warnings), summary: summary(tree, warnings.size))
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
private
|
|
44
|
+
|
|
45
|
+
# [name, warnings]. The name given with --name, or the title of the
|
|
46
|
+
# description in lower case with underscores, or "api".
|
|
47
|
+
def api_name(document)
|
|
48
|
+
name = @name
|
|
49
|
+
if name.nil?
|
|
50
|
+
name = Import.one_line(document.title).downcase.gsub(/[^a-z0-9]+/, '_').gsub(/\A_+|_+\z/, '')
|
|
51
|
+
name = 'api' if name.empty?
|
|
52
|
+
name = "api_#{name}" if name.match?(/\A\d/)
|
|
53
|
+
end
|
|
54
|
+
unless name.is_a?(String) && Internals::Compiler::METHOD_NAME.match?(name)
|
|
55
|
+
raise Error, '--name: must be the name of a method: letters, digits and _, not starting with a digit'
|
|
56
|
+
end
|
|
57
|
+
|
|
58
|
+
warnings = []
|
|
59
|
+
if Internals::Handles.taken?(ApiRecipes.singleton_class, name.to_sym)
|
|
60
|
+
warnings << "#{Import.shown(name)} is the name of a method of ApiRecipes: reach the api with ApiRecipes[:#{name}]"
|
|
61
|
+
end
|
|
62
|
+
[name, warnings]
|
|
63
|
+
end
|
|
64
|
+
|
|
65
|
+
# A description can be made to produce any number of warnings.
|
|
66
|
+
def shown_warnings(warnings)
|
|
67
|
+
return warnings if warnings.size <= MAX_WARNINGS
|
|
68
|
+
|
|
69
|
+
warnings.first(MAX_WARNINGS) + ["#{warnings.size - MAX_WARNINGS} more warnings were not shown"]
|
|
70
|
+
end
|
|
71
|
+
|
|
72
|
+
# The text must be a recipe that the gem compiles.
|
|
73
|
+
def verify(text)
|
|
74
|
+
apis = Internals::Compiler.normalize(YAML.safe_load(text), :options_map)
|
|
75
|
+
Internals::Compiler.compile_all(apis)
|
|
76
|
+
rescue ConfigurationError => e
|
|
77
|
+
raise Error, "the recipe would not be valid, so nothing was written:\n#{e.errors.map { |problem| " #{problem}" }.join("\n")}"
|
|
78
|
+
end
|
|
79
|
+
|
|
80
|
+
def summary(tree, warnings)
|
|
81
|
+
text = "#{count(tree.operations, 'operation')} imported from #{count(tree.paths, 'path')}"
|
|
82
|
+
text += ", #{tree.skipped} left out by the filters" if tree.skipped.positive?
|
|
83
|
+
text += ", #{count(warnings, 'warning')}" if warnings.positive?
|
|
84
|
+
text
|
|
85
|
+
end
|
|
86
|
+
|
|
87
|
+
def count(number, word) = "#{number} #{word}#{'s' unless number == 1}"
|
|
88
|
+
|
|
89
|
+
# The text of a plain value of the description, or nil for a mapping or
|
|
90
|
+
# a list. Mappings and lists are never turned into text: with YAML
|
|
91
|
+
# aliases a small file can describe a structure too large to print.
|
|
92
|
+
# Every value read from a description goes through this method, shown or
|
|
93
|
+
# one_line, never through to_s or an interpolation.
|
|
94
|
+
def self.text(value)
|
|
95
|
+
case value
|
|
96
|
+
when String then value
|
|
97
|
+
when Symbol, Numeric, true, false, Date, Time then value.to_s
|
|
98
|
+
end
|
|
99
|
+
end
|
|
100
|
+
|
|
101
|
+
# A value of the description as it is shown in a message: one line of
|
|
102
|
+
# printable characters, cut to a length that keeps the message readable.
|
|
103
|
+
def self.shown(value)
|
|
104
|
+
text = self.text(value)
|
|
105
|
+
return value.nil? ? 'nothing' : "a #{value.is_a?(Hash) ? 'mapping' : 'list'}" if text.nil?
|
|
106
|
+
|
|
107
|
+
text = text.scrub('?').gsub(/[^[:print:]]/, '?')
|
|
108
|
+
"'#{text.length > 80 ? "#{text[0, 80]}..." : text}'"
|
|
109
|
+
end
|
|
110
|
+
|
|
111
|
+
# Free text of the description (a title, a description, an operationId)
|
|
112
|
+
# as it may appear in the recipe: one line, without control characters
|
|
113
|
+
# and without the ERB delimiters, which a recipe file would evaluate.
|
|
114
|
+
# Every kind of space and of line separator becomes one space, and so do
|
|
115
|
+
# the characters that are not shown or that change the direction of text.
|
|
116
|
+
def self.one_line(value, limit = 200)
|
|
117
|
+
text = self.text(value).to_s.scrub('?').gsub(/[[:cntrl:][:space:]\p{Cf}\p{Zl}\p{Zp}]+/, ' ')
|
|
118
|
+
text = text.gsub(/<%|%>/, '') while text.match?(/<%|%>/)
|
|
119
|
+
text.strip[0, limit]
|
|
120
|
+
end
|
|
121
|
+
end
|
|
122
|
+
end
|
|
123
|
+
end
|
|
124
|
+
|
|
125
|
+
require 'api_recipes/cli/import/document'
|
|
126
|
+
require 'api_recipes/cli/import/server'
|
|
127
|
+
require 'api_recipes/cli/import/security'
|
|
128
|
+
require 'api_recipes/cli/import/tree'
|
|
129
|
+
require 'api_recipes/cli/import/writer'
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module ApiRecipes
|
|
4
|
+
module CLI
|
|
5
|
+
# The routes command: the calls that the recipes in some files offer, one
|
|
6
|
+
# per line, with the verb and the address.
|
|
7
|
+
class Routes
|
|
8
|
+
def initialize(files, erb: false)
|
|
9
|
+
@files = Array(files)
|
|
10
|
+
@erb = erb
|
|
11
|
+
end
|
|
12
|
+
|
|
13
|
+
# Prints the calls on out and the problems on err. Returns the exit code:
|
|
14
|
+
# 2 if a file could not be read, else 1 if a file is not a valid
|
|
15
|
+
# configuration, else 0.
|
|
16
|
+
def report(out, err)
|
|
17
|
+
rows = []
|
|
18
|
+
codes = @files.map { |file| read(file, rows, err) }
|
|
19
|
+
widths = [0, 1].map { |column| rows.map { |row| row[column].length }.max }
|
|
20
|
+
rows.each { |call, verb, url| out.puts "#{call.ljust(widths[0])} #{verb.ljust(widths[1])} #{url}" }
|
|
21
|
+
codes.max || 0
|
|
22
|
+
end
|
|
23
|
+
|
|
24
|
+
private
|
|
25
|
+
|
|
26
|
+
# Adds the calls of file to rows. Returns the exit code for this file.
|
|
27
|
+
def read(file, rows, err)
|
|
28
|
+
unless File.file?(file) && File.readable?(file)
|
|
29
|
+
err.puts "#{file}: #{File.file?(file) ? 'cannot be read' : (File.exist?(file) ? 'is not a file' : 'no such file')}"
|
|
30
|
+
return 2
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
apis = Configuration.new.read_recipe_file(file, erb: @erb)
|
|
34
|
+
Internals::Compiler.compile_all(apis).each_value do |api|
|
|
35
|
+
api.routes.each { |route| rows << [route.call, route.verb.to_s.upcase, route.url] }
|
|
36
|
+
end
|
|
37
|
+
0
|
|
38
|
+
rescue RecipeFileError => e
|
|
39
|
+
e.errors.each { |problem| err.puts problem }
|
|
40
|
+
1
|
|
41
|
+
rescue ConfigurationError => e
|
|
42
|
+
e.errors.each { |problem| err.puts "#{file}: #{problem}" }
|
|
43
|
+
1
|
|
44
|
+
rescue StandardError, ScriptError => e
|
|
45
|
+
err.puts "#{file}: could not be evaluated (#{e.class})"
|
|
46
|
+
1
|
|
47
|
+
end
|
|
48
|
+
end
|
|
49
|
+
end
|
|
50
|
+
end
|