api_recipes 3.0.0.beta2 → 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.
Files changed (35) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +704 -81
  3. data/UPGRADING.md +149 -46
  4. data/lib/api_recipes/api.rb +14 -10
  5. data/lib/api_recipes/cli/code.rb +153 -0
  6. data/lib/api_recipes/cli/convert/migration.rb +624 -0
  7. data/lib/api_recipes/cli/convert/snippet.rb +67 -0
  8. data/lib/api_recipes/cli/convert.rb +533 -0
  9. data/lib/api_recipes/cli/recipes/git.rb +197 -0
  10. data/lib/api_recipes/cli/recipes/lock_file.rb +34 -0
  11. data/lib/api_recipes/cli/recipes/summary.rb +245 -0
  12. data/lib/api_recipes/cli/recipes.rb +287 -0
  13. data/lib/api_recipes/cli/routes.rb +8 -3
  14. data/lib/api_recipes/cli/upgrade/project.rb +194 -0
  15. data/lib/api_recipes/cli/upgrade.rb +361 -24
  16. data/lib/api_recipes/cli.rb +161 -8
  17. data/lib/api_recipes/configuration.rb +68 -18
  18. data/lib/api_recipes/endpoint.rb +10 -4
  19. data/lib/api_recipes/errors.rb +2 -1
  20. data/lib/api_recipes/internals/compiler.rb +174 -33
  21. data/lib/api_recipes/internals/context.rb +87 -20
  22. data/lib/api_recipes/internals/declaration.rb +18 -18
  23. data/lib/api_recipes/internals/definition.rb +76 -23
  24. data/lib/api_recipes/internals/level.rb +54 -43
  25. data/lib/api_recipes/internals/option_value.rb +92 -0
  26. data/lib/api_recipes/internals/path_template.rb +29 -4
  27. data/lib/api_recipes/internals/plain_yaml.rb +133 -0
  28. data/lib/api_recipes/internals/recipe.rb +297 -0
  29. data/lib/api_recipes/internals/recipe_lock.rb +115 -0
  30. data/lib/api_recipes/internals/registry.rb +61 -15
  31. data/lib/api_recipes/internals/request.rb +42 -14
  32. data/lib/api_recipes/internals/template.rb +17 -5
  33. data/lib/api_recipes/version.rb +1 -1
  34. data/lib/api_recipes.rb +8 -3
  35. metadata +14 -1
@@ -0,0 +1,67 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ApiRecipes
4
+ module CLI
5
+ class Convert
6
+ # The code to paste where the command did not write it: the lines for the
7
+ # block of ApiRecipes.configure, with the code of each ERB tag and each
8
+ # value as they are written in the file, so that what is pasted works.
9
+ # Only what a terminal would obey is left out: that value is given as
10
+ # nil, with a comment that says where to copy it from.
11
+ class Snippet
12
+ ENV_ONLY = /\AENV(\[\s*(['"])\w+\2\s*\]|\.fetch\(\s*(['"])\w+\3\s*\))\z/
13
+ PLAIN = /\A("(?:[^"#\\]|\\.)*"|'[^'\\]*'|\d+)\z/
14
+
15
+ # config: the name of the block parameter. recipes: the code that
16
+ # gives recipes_paths, or nil when the file assigns it already.
17
+ def initialize(result, source, config: 'config', recipes: "Dir['config/api_recipes/*.recipe.yml']")
18
+ @result = result
19
+ @source = source
20
+ @config = config
21
+ @recipes = recipes
22
+ end
23
+
24
+ # The lines to add inside the block.
25
+ def lines
26
+ out = []
27
+ out << "#{@config}.recipes_paths = #{@recipes}" if @recipes
28
+ return out if @result.expressions.empty?
29
+
30
+ out + ["#{@config}.values = {", *entry(' '), '}']
31
+ end
32
+
33
+ # The lines of this api inside the Hash given to config.values.
34
+ def entry(indent = '')
35
+ names = @result.expressions.keys
36
+ pairs = names.each_with_index.map do |name, index|
37
+ code, comment = value(name)
38
+ "#{indent} #{name}: #{code}#{',' unless index == names.size - 1}#{" # #{comment}" if comment}"
39
+ end
40
+ ["#{indent}#{key}: { variables: {", *pairs, "#{indent}}.compact }"]
41
+ end
42
+
43
+ # The name of the api as a key of a Hash.
44
+ def key
45
+ name = @result.name
46
+ name.match?(/\A[a-z_]\w*\z/) ? name : "\"#{name}\""
47
+ end
48
+
49
+ private
50
+
51
+ # [code, comment]: the code of the tag, or nil and where to copy from.
52
+ def value(name)
53
+ code = @result.expressions[name]
54
+ ref = @result.refs[name] || {}
55
+ return [ENV_ONLY.match?(code) || PLAIN.match?(code) ? code : "(#{code})", nil] if shown?(code, ref)
56
+
57
+ what = ref[:literal] ? 'the value written' : 'the code of the tag'
58
+ where = [ref[:place] && "for #{Recipes::Summary.shown(ref[:place], 100)}", ref[:line] && "at line #{ref[:line]}"].compact.join(', ')
59
+ ['nil', "paste here #{what} #{where} of #{Recipes::Summary.shown(@source, 100)}"]
60
+ end
61
+
62
+ # Everything is shown but what would change what the terminal shows.
63
+ def shown?(code, _ref) = !Code::UNSAFE.match?(code)
64
+ end
65
+ end
66
+ end
67
+ end
@@ -0,0 +1,533 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'yaml'
4
+ require 'securerandom'
5
+
6
+ module ApiRecipes
7
+ module CLI
8
+ # The convert command: from a configuration file of a project to the text
9
+ # of a portable recipe. The file is read and never run: an ERB tag becomes
10
+ # a variable where a recipe can have one, and is left out elsewhere. What
11
+ # is named like a credential is never copied. The result is checked as a
12
+ # portable recipe before it is returned.
13
+ class Convert
14
+ # The file cannot become a recipe. reasons: one line each.
15
+ class Refused < StandardError
16
+ attr_reader :reasons
17
+
18
+ def initialize(reasons)
19
+ @reasons = Array(reasons)
20
+ super(@reasons.join("\n"))
21
+ end
22
+ end
23
+
24
+ # The arguments are wrong, or the file cannot be read.
25
+ class Unusable < StandardError; end
26
+
27
+ # variables: { name => environment variable or nil } for those without a
28
+ # default; defaults: the same for those that have one. expressions:
29
+ # { name => Ruby code } for every variable the conversion made: the code
30
+ # of the tag it comes from, or the value that was written, as a literal.
31
+ # verify_with: where one was left out, as [place, method name].
32
+ # refs: { name => { place:, line:, credential:, literal: } }, where the
33
+ # value of each of those variables is in the file.
34
+ Result = Data.define(:name, :version, :text, :calls, :changes, :variables, :defaults, :expressions, :verify_with, :refs)
35
+
36
+ Tag = Data.define(:line, :env, :default, :code)
37
+
38
+ DEFAULT_VERSION = '1.0.0'
39
+ COMMENT = /<%#.*?%>/m
40
+ OUTPUT = /<%=(.*?)-?%>/m
41
+ # A tag longer than this is not read as a read of the environment.
42
+ MAX_TAG = 300
43
+ # More values than a recipe can hold: aliases can make them from a few lines.
44
+ MAX_VALUES = 200_000
45
+ ENV_FETCH = /\AENV\.fetch\(\s*(?:'([A-Za-z_]\w*)'|"([A-Za-z_]\w*)")\s*(?:,\s*([^,()]+?)\s*)?\)\z/
46
+ ENV_INDEX = /\AENV\[\s*(?:'([A-Za-z_]\w*)'|"([A-Za-z_]\w*)")\s*\](?:\s*\|\|\s*([^|&]+?))?\z/
47
+ # A header or a parameter with such a name holds a credential.
48
+ CREDENTIAL = /auth|key|token|secret|passw|credential|signature|cookie|session/i
49
+ SENT = %w[default_headers default_params].freeze
50
+ # The options of a request that a variable can give whole.
51
+ OPTION_KEYS = Internals::OptionValue::KEYS.map(&:to_s).freeze
52
+ API_ORDER = %w[recipe auth variables protocol host port base_url timeout on_bad_code mime_type
53
+ default_headers default_params].freeze
54
+ ENDPOINT_ORDER = %w[path verb route ok_code resource timeout on_bad_code mime_type default_headers default_params].freeze
55
+
56
+ def initialize(file, name: nil, version: DEFAULT_VERSION)
57
+ @file = file
58
+ @wanted = name
59
+ @version = version
60
+ # The mark of a tag: random, so that no file can write one.
61
+ @mark = "__API_RECIPES_ERB_#{SecureRandom.hex(8)}_"
62
+ @token = /#{@mark}(\d+)__/
63
+ end
64
+
65
+ def call
66
+ raise Unusable, '--version: must be made of digits, letters and dots, such as 1.2.0' unless version_valid?
67
+ raise Unusable, "#{shown(@file)}: is already called #{Internals::Recipe::SUFFIX}: check it with `api_recipes check`" if @file.end_with?(Internals::Recipe::SUFFIX)
68
+
69
+ @changes = []
70
+ @variables = {}
71
+ @origins = {}
72
+ @envs = {}
73
+ @expressions = {}
74
+ @verify_with = []
75
+ @secret = []
76
+ @given = {}
77
+ @refs = {}
78
+ name, options = api(parsed(plain(source)))
79
+ @name = name
80
+ declared = options['variables']
81
+ refuse('variables: must be a mapping of names') unless declared.nil? || declared.is_a?(Hash)
82
+ (declared || {}).each_key { |variable| @origins[variable.to_s] = :declared }
83
+ refuse('the name of the api must be made of lowercase letters, digits, - and _ to be the name of a recipe') unless Internals::Recipe::NAME.match?(name)
84
+ refuse('already has the key recipe: rename the file to NAME.recipe.yml and check it') if options.key?('recipe')
85
+
86
+ body = api_options(options)
87
+ body = { 'recipe' => { 'name' => name, 'version' => @version, 'format' => Internals::Recipe::FORMAT } }.merge(body)
88
+ body['variables'] = (body['variables'] || {}).merge(@variables) unless @variables.empty?
89
+ text = Text.new(name, ordered(body, API_ORDER)).to_yaml
90
+ Result.new(name: name, version: @version, text: text, calls: checked(name, text), changes: @changes,
91
+ variables: env_of(false).merge(@given), defaults: env_of(true), expressions: @expressions, verify_with: @verify_with,
92
+ refs: @refs.to_h { |variable, ref| [variable, ref.merge(credential: ref[:credential] || @secret.include?(variable))] })
93
+ end
94
+
95
+ # What is said after the recipe is written in path: what changed from
96
+ # the file, and what the application gives from now on. It holds names
97
+ # only, never a value of the file.
98
+ def self.report(result, source, path, out)
99
+ calls = result.calls
100
+ out.puts "#{result.name} #{result.version} is written in #{path}: #{calls} call#{'s' unless calls == 1}"
101
+ unless result.changes.empty?
102
+ out.puts '', "What changed from #{Recipes::Summary.shown(source, 100)}"
103
+ result.changes.each { |change| out.puts " #{change}" }
104
+ end
105
+ out.puts '', 'In the file that calls ApiRecipes.configure, inside its block:'
106
+ Code.show(out, Snippet.new(result, source).lines)
107
+ unless result.defaults.empty?
108
+ out.puts "Variables that have a default in the recipe: #{result.defaults.keys.join(', ')}. .compact leaves out " \
109
+ 'the ones whose code gives nil.', ''
110
+ end
111
+ out.puts "Read the file, then check it: api_recipes check #{path}"
112
+ end
113
+
114
+ # The apis that text describes, with every ERB tag read as the same
115
+ # word: what two texts must share to describe the same thing.
116
+ def self.shape(text)
117
+ plain = text.gsub(COMMENT, '').gsub(OUTPUT, '__API_RECIPES_ERB__')
118
+ raise Refused.new(['an ERB tag decides the structure of the file']) if plain.gsub('<%%', '').include?('<%')
119
+
120
+ data = YAML.safe_load(plain, permitted_classes: [Symbol], aliases: true)
121
+ data.is_a?(Hash) ? data.transform_keys(&:to_s) : {}
122
+ end
123
+
124
+ private
125
+
126
+ def shown(text) = Recipes::Summary.shown(text, 100)
127
+
128
+ def refuse(reasons) = raise(Refused.new(Array(reasons).map { |reason| "#{shown(@file)}: #{reason}" }))
129
+
130
+ def version_valid?
131
+ @version.is_a?(String) && @version.length <= Internals::Recipe::MAX_VERSION && Internals::Recipe::VERSION.match?(@version)
132
+ end
133
+
134
+ def source
135
+ raise Unusable, "#{shown(@file)}: no such file" unless File.exist?(@file)
136
+ raise Unusable, "#{shown(@file)}: is not a file that can be read" unless File.file?(@file) && File.readable?(@file)
137
+ raise Unusable, "#{shown(@file)}: is larger than a recipe can be" if File.size(@file) > Internals::Recipe::MAX_BYTES
138
+
139
+ text = File.binread(@file).force_encoding(Encoding::UTF_8)
140
+ refuse('is not text') if text.include?("\0") || !text.valid_encoding?
141
+ text
142
+ rescue SystemCallError => e
143
+ raise Unusable, "#{shown(@file)}: cannot be read (#{e.class.name.split('::').last})"
144
+ end
145
+
146
+ # The text with each output tag replaced by a token, and the tags kept
147
+ # aside. Nothing of a tag is run.
148
+ def plain(text)
149
+ @tags = []
150
+ plain = text.gsub(COMMENT) { |comment| comment.gsub(/[^\n]/, '') }
151
+ plain = plain.gsub(OUTPUT) do
152
+ code = Regexp.last_match(1)
153
+ @tags << tag(code, Regexp.last_match.pre_match.count("\n") + 1)
154
+ "#{@mark}#{@tags.size - 1}__#{"\n" * code.count("\n")}"
155
+ end
156
+ left = plain.gsub('<%%', '')
157
+ return plain.gsub('<%%', '<%') unless left.include?('<%')
158
+
159
+ lines = left.each_line.with_index(1).select { |line, _| line.include?('<%') }.map(&:last)
160
+ raise Refused.new(lines.map do |line|
161
+ "#{shown(@file)}:#{line}: an ERB tag that is not <%= ... %> decides the structure of the file: " \
162
+ 'write the file without it first'
163
+ end)
164
+ end
165
+
166
+ # What can be known of a tag without running it: the environment
167
+ # variable it reads and the default written beside it.
168
+ def tag(code, line)
169
+ code = code.strip
170
+ match = code.length <= MAX_TAG && (ENV_FETCH.match(code) || ENV_INDEX.match(code))
171
+ return Tag.new(line: line, env: nil, default: nil, code: code) unless match
172
+
173
+ Tag.new(line: line, env: match[1] || match[2], default: literal(match[3]), code: code)
174
+ end
175
+
176
+ def literal(code)
177
+ case code
178
+ when /\A'([^'\\]*)'\z/, /\A"([^"\\#]*)"\z/ then Regexp.last_match(1)
179
+ when /\A\d+\z/ then code.to_i
180
+ when /\A\d+\.\d+\z/ then code.to_f
181
+ when 'true' then true
182
+ when 'false' then false
183
+ end
184
+ end
185
+
186
+ def parsed(text)
187
+ data = YAML.safe_load(text, permitted_classes: [Symbol], aliases: true)
188
+ refuse('does not describe an api') unless data.is_a?(Hash) && !data.empty?
189
+ bounded(data)
190
+ named = names_from_tags(data)
191
+ unless named.empty?
192
+ raise Refused.new(named.map { |line| "#{shown(@file)}:#{line}: an ERB tag gives a name: a recipe needs the name written" })
193
+ end
194
+
195
+ stringify(data)
196
+ rescue Psych::SyntaxError => e
197
+ refuse("is not valid YAML, at line #{e.line}")
198
+ rescue Psych::Exception
199
+ refuse('is not valid YAML')
200
+ end
201
+
202
+ # Aliases make a huge structure from a few lines: it is counted before
203
+ # anything walks it whole.
204
+ def bounded(value, seen = [0])
205
+ seen[0] += 1
206
+ refuse('describes more values than a recipe can hold') if seen[0] > MAX_VALUES
207
+ case value
208
+ when Hash then value.each { |key, inner| bounded(key, seen) && bounded(inner, seen) }
209
+ when Array then value.each { |inner| bounded(inner, seen) }
210
+ end
211
+ true
212
+ end
213
+
214
+ # The lines of the tags that stand where a name does.
215
+ def names_from_tags(value, found = [])
216
+ case value
217
+ when Hash
218
+ value.each do |key, inner|
219
+ key.to_s.scan(@token) { found << @tags[Regexp.last_match(1).to_i].line }
220
+ names_from_tags(inner, found)
221
+ end
222
+ when Array then value.each { |inner| names_from_tags(inner, found) }
223
+ end
224
+ found
225
+ end
226
+
227
+ def stringify(value)
228
+ case value
229
+ when Hash then value.to_h { |key, inner| [key.to_s, stringify(inner)] }
230
+ when Array then value.map { |inner| stringify(inner) }
231
+ when Symbol then value.to_s
232
+ else value
233
+ end
234
+ end
235
+
236
+ def api(data)
237
+ names = data.keys
238
+ if @wanted
239
+ raise Unusable, "#{shown(@file)}: does not describe an api called #{shown(@wanted)}" unless data.key?(@wanted)
240
+
241
+ refuse('does not describe an api') unless data[@wanted].nil? || data[@wanted].is_a?(Hash)
242
+ return [@wanted, data[@wanted] || {}]
243
+ end
244
+ unless names.size == 1
245
+ raise Unusable, "#{shown(@file)}: describes #{names.size} apis (#{names.map { |name| shown(name) }.join(', ')}): choose one with --name"
246
+ end
247
+
248
+ refuse('does not describe an api') unless data[names.first].is_a?(Hash)
249
+ [names.first, data[names.first]]
250
+ end
251
+
252
+ def api_options(options)
253
+ out = {}
254
+ options.each do |key, value|
255
+ case key
256
+ when 'verify_with' then left_out(key, value)
257
+ when 'variables' then out[key] = declared_variables(value)
258
+ when 'host', 'base_url' then out[key] = with_variables(value, key, key)
259
+ when *OPTION_KEYS then out[key] = option(value, key, key)
260
+ when *SENT then out[key] = sent(value, key)
261
+ when 'endpoints' then out[key] = endpoints(value, key)
262
+ else keep(out, key, value, key)
263
+ end
264
+ end
265
+ out
266
+ end
267
+
268
+ # The variables the file declares already. A default that a tag gives
269
+ # is given by the application from now on.
270
+ def declared_variables(value)
271
+ value.to_h do |name, spec|
272
+ next [name, spec] unless spec.is_a?(Hash) && holds_tag?(spec['default'])
273
+
274
+ match = /\A#{@token.source}\z/.match(spec['default'].to_s)
275
+ refuse("variables.#{shown(name)}.default: an ERB tag gives a part of the value: a recipe needs it written") unless match
276
+ @expressions[name.to_s] = @tags[match[1].to_i].code
277
+ @given[name.to_s] = @tags[match[1].to_i].env
278
+ @refs[name.to_s] = { place: "variables.#{name}.default", line: @tags[match[1].to_i].line, credential: false }
279
+ @changes << "variables.#{shown(name)}.default: came from an ERB tag: the application gives the variable from now on"
280
+ [name, spec.reject { |key, _| key == 'default' }]
281
+ end
282
+ end
283
+
284
+ def endpoints(value, where)
285
+ return value unless value.is_a?(Hash)
286
+
287
+ value.to_h do |name, options|
288
+ here = "#{where}.#{name}"
289
+ [name, options.is_a?(Hash) ? ordered(endpoint(options, here, name), ENDPOINT_ORDER) : fixed(options, here)]
290
+ end
291
+ end
292
+
293
+ def endpoint(options, where, name)
294
+ out = {}
295
+ options.each do |key, value|
296
+ here = "#{where}.#{key}"
297
+ case key
298
+ when 'verify_with' then left_out(here, value)
299
+ when 'path' then out[key] = with_variables(value, here, "#{name}_path")
300
+ when *OPTION_KEYS then out[key] = option(value, here, "#{name}_#{key}")
301
+ when *SENT then out[key] = sent(value, here)
302
+ when 'endpoints' then out[key] = endpoints(value, here)
303
+ else keep(out, key, value, here)
304
+ end
305
+ end
306
+ out
307
+ end
308
+
309
+ def left_out(where, value)
310
+ @verify_with << [where, holds_tag?(value) ? nil : value.to_s]
311
+ @changes << "#{shown(where)}: left out, a recipe cannot carry it: give it where a class declares the api, " \
312
+ "as `api :#{@name}, verify_with: ...`"
313
+ end
314
+
315
+ # Headers and parameters: a tag becomes a variable, and what is named
316
+ # like a credential is never copied.
317
+ def sent(value, where)
318
+ return fixed(value, where) unless value.is_a?(Hash)
319
+
320
+ value.to_h do |name, content|
321
+ here = "#{where}.#{name}"
322
+ if content.to_s.length > Internals::Recipe::MAX_LENGTH
323
+ refuse("#{shown(here)}: is longer than the #{Internals::Recipe::MAX_LENGTH} characters a recipe allows for a value")
324
+ end
325
+ secret = CREDENTIAL.match?(name) && !given_by_variables?(content)
326
+ if !secret && content.is_a?(String) && Code::UNSAFE.match?(content.gsub(@token, ''))
327
+ refuse("#{shown(here)}: holds a character that is not printed: a recipe holds visible text only")
328
+ end
329
+ if secret
330
+ [name, credential(content, here, name)]
331
+ else
332
+ [name, with_variables(content, here, name)]
333
+ end
334
+ end
335
+ end
336
+
337
+ # A value that is already made of variables only, or of text and
338
+ # variables the file declares, holds nothing to hide.
339
+ def given_by_variables?(content)
340
+ return false unless content.is_a?(String) && !@token.match?(content)
341
+
342
+ names = content.scan(Internals::Template::VARIABLE).flatten
343
+ !names.empty? && names.all? { |name| @origins[name] == :declared }
344
+ end
345
+
346
+ def credential(content, where, name)
347
+ tags = content.to_s.scan(@token).flatten.map { |index| @tags[index.to_i] }
348
+ if tags.size == 1 && content.to_s.match?(/\A#{@token.source}\z/)
349
+ variable = variable_for(tags.first, name, where, default: false)
350
+ @changes << "#{shown(where)}: the ERB tag is now the variable {#{variable}}; the value is not in the recipe"
351
+ else
352
+ code = written(content)
353
+ variable = declare(variable_name(name), code, nil, nil)
354
+ @expressions[variable] ||= code
355
+ @refs[variable] ||= { place: where, line: nil, credential: true, literal: true }
356
+ @changes << "#{shown(where)}: looks like a credential: its value is not copied, it is now the variable {#{variable}}"
357
+ end
358
+ "{#{variable}}"
359
+ end
360
+
361
+ # A value where a recipe can have a variable.
362
+ def with_variables(value, where, fallback)
363
+ return fixed(value, where) unless value.is_a?(String) && @token.match?(value)
364
+
365
+ value.gsub(@token) do
366
+ tag = @tags[Regexp.last_match(1).to_i]
367
+ variable = variable_for(tag, fallback, where, default: true)
368
+ kept = @variables[variable].key?('default') ? ', with the default written in the tag' : ''
369
+ @changes << "#{shown(where)}: the ERB tag is now the variable {#{variable}}#{kept}"
370
+ "{#{variable}}"
371
+ end
372
+ end
373
+
374
+ def variable_for(tag, fallback, where, default:)
375
+ # What is named like a credential in the environment has no default either.
376
+ default &&= !CREDENTIAL.match?(tag.env.to_s)
377
+ name = declare(variable_name(tag.env || fallback), tag.code, tag.env, default ? tag.default : nil)
378
+ @refs[name] ||= { place: where, line: tag.line, credential: !default }
379
+ # A variable that gives a credential has no default, also when the
380
+ # same environment variable is read elsewhere with one.
381
+ @secret << name unless default
382
+ @variables[name] = {} if @secret.include?(name)
383
+ @expressions[name] ||= tag.code
384
+ name
385
+ end
386
+
387
+ # A value written in the file, as the Ruby code that gives it again. A
388
+ # tag inside it stays what it was: an interpolation.
389
+ def written(content)
390
+ return content.to_s.inspect unless content.is_a?(String) && @token.match?(content)
391
+
392
+ parts = content.split(@token).each_slice(2).flat_map do |text, index|
393
+ [text.inspect[1..-2], index && "\#{#{@tags[index.to_i].code}}"]
394
+ end
395
+ "\"#{parts.compact.join}\""
396
+ end
397
+
398
+ # One of the options of a request: a tag that gives it whole becomes a
399
+ # variable, which is all a recipe can have there.
400
+ def option(value, where, fallback)
401
+ return value unless holds_tag?(value)
402
+ return with_variables(value, where, fallback) if value.is_a?(String) && value.match?(/\A#{@token.source}\z/)
403
+
404
+ refuse("#{shown(where)}: an ERB tag gives a part of the value: a recipe needs it written, or given whole by one tag")
405
+ end
406
+
407
+ def variable_name(text)
408
+ name = text.to_s.downcase.gsub(/[^a-z0-9_]+/, '_').gsub(/\A_+|_+\z/, '')
409
+ name = "v_#{name}" unless name.match?(/\A[a-z_]/)
410
+ name
411
+ end
412
+
413
+ # Declares the variable and returns its name. The same code gives the
414
+ # same variable; another code gives another one, also at the same place
415
+ # or for the same environment variable, so that nothing is lost.
416
+ def declare(name, code, env, default)
417
+ taken = @origins.key(code)
418
+ return taken if taken
419
+
420
+ base = name
421
+ number = 1
422
+ name = "#{base}_#{number += 1}" while @origins.key?(name)
423
+ @origins[name] = code
424
+ @variables[name] = default.nil? ? {} : { 'default' => default.to_s }
425
+ @envs[name] = env
426
+ name
427
+ end
428
+
429
+ def env_of(with_default)
430
+ @variables.select { |_, spec| spec.key?('default') == with_default }.keys.sort.to_h { |name| [name, @envs[name]] }
431
+ end
432
+
433
+ # Any other option: a recipe cannot have a variable there.
434
+ def keep(out, key, value, where)
435
+ unless holds_tag?(value)
436
+ out[key] = value
437
+ return
438
+ end
439
+
440
+ tag = value.is_a?(String) && (match = /\A#{@token.source}\z/.match(value)) ? @tags[match[1].to_i] : nil
441
+ if tag && !tag.default.nil?
442
+ out[key] = tag.default
443
+ @changes << "#{shown(where)}: came from an ERB tag: the recipe has the default written in the tag"
444
+ else
445
+ @changes << "#{shown(where)}: came from an ERB tag with no default that can be read without running it: " \
446
+ 'left out, so the default of the gem applies; write the value in the recipe if it is always the same'
447
+ end
448
+ end
449
+
450
+ def fixed(value, where)
451
+ return value unless holds_tag?(value)
452
+
453
+ refuse("#{shown(where)}: an ERB tag gives a value that a recipe needs written")
454
+ end
455
+
456
+ def holds_tag?(value)
457
+ case value
458
+ when Hash then value.any? { |key, inner| @token.match?(key.to_s) || holds_tag?(inner) }
459
+ when Array then value.any? { |inner| holds_tag?(inner) }
460
+ when String then @token.match?(value)
461
+ else false
462
+ end
463
+ end
464
+
465
+ def ordered(options, order)
466
+ first = order.select { |key| options.key?(key) }
467
+ (first + (options.keys - first - ['endpoints']) + (options.key?('endpoints') ? ['endpoints'] : [])).to_h { |key| [key, options[key]] }
468
+ end
469
+
470
+ # The result must be a portable recipe. Returns the number of its calls.
471
+ def checked(name, text)
472
+ file_name = "#{name}#{Internals::Recipe::SUFFIX}"
473
+ Internals::Recipe.parse(text, file_name, file_name: file_name).definition.routes.size
474
+ rescue ConfigurationError => e
475
+ problems = e.errors.map { |problem| problem.delete_prefix("#{file_name}: ") }
476
+ raise Refused.new(["#{shown(@file)} cannot become a portable recipe:"] + problems.map { |problem| " #{problem}" })
477
+ end
478
+
479
+ # The text of the recipe. Every name and every value is written by Ruby's
480
+ # YAML generator, on one line, and the text is read back and compared
481
+ # with the data before it is returned.
482
+ class Text
483
+ INTERNAL = 'internal error: the recipe does not read back as it was written, so nothing was written'
484
+
485
+ def initialize(name, options)
486
+ @name = name
487
+ @options = options
488
+ end
489
+
490
+ def to_yaml
491
+ @lines = []
492
+ write(0, @name, @options)
493
+ text = "#{@lines.join("\n")}\n"
494
+ raise Refused.new([INTERNAL]) unless YAML.safe_load(text) == { @name => @options }
495
+
496
+ text
497
+ rescue Psych::Exception
498
+ raise Refused.new([INTERNAL])
499
+ end
500
+
501
+ private
502
+
503
+ def write(indent, key, value)
504
+ key = scalar(key)
505
+ case value
506
+ when Hash
507
+ if value.empty?
508
+ line(indent, "#{key}: {}")
509
+ else
510
+ line(indent, "#{key}:")
511
+ value.each { |name, inner| write(indent + 1, name, inner) }
512
+ end
513
+ when Array then line(indent, "#{key}: [#{value.map { |item| scalar(item) }.join(', ')}]")
514
+ when nil then line(indent, "#{key}:")
515
+ else line(indent, "#{key}: #{scalar(value)}")
516
+ end
517
+ end
518
+
519
+ def line(indent, text) = @lines << "#{' ' * indent}#{text}"
520
+
521
+ def scalar(content)
522
+ plain = content.is_a?(String) || content.is_a?(Integer) || content.is_a?(Float) || content == true || content == false
523
+ raise Refused.new(['a value of the file is not text, a number, true or false: a recipe holds nothing else']) unless plain
524
+
525
+ written = YAML.dump([content], line_width: -1)[/\A---\n- (.*)\n\z/m, 1]
526
+ raise Refused.new(['a name or a value of the file takes more than one line: a recipe holds one line each']) if written.nil? || written.include?("\n")
527
+
528
+ written
529
+ end
530
+ end
531
+ end
532
+ end
533
+ end