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.
@@ -53,10 +53,12 @@ module ApiRecipes
53
53
  default_headers default_params].freeze
54
54
  ENDPOINT_ORDER = %w[path verb route ok_code resource timeout on_bad_code mime_type default_headers default_params].freeze
55
55
 
56
- def initialize(file, name: nil, version: DEFAULT_VERSION)
56
+ # calls: write beside each endpoint how it is called in Ruby.
57
+ def initialize(file, name: nil, version: DEFAULT_VERSION, calls: false)
57
58
  @file = file
58
59
  @wanted = name
59
60
  @version = version
61
+ @calls = calls
60
62
  # The mark of a tag: random, so that no file can write one.
61
63
  @mark = "__API_RECIPES_ERB_#{SecureRandom.hex(8)}_"
62
64
  @token = /#{@mark}(\d+)__/
@@ -85,10 +87,19 @@ module ApiRecipes
85
87
 
86
88
  body = api_options(options)
87
89
  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,
90
+ # A variable that has no default needs no declaration: the recipe
91
+ # uses it, and that makes it a variable that a value must be given to.
92
+ written = @variables.reject { |_, spec| spec.empty? }
93
+ body['variables'] = (body['variables'] || {}).merge(written) unless written.empty?
94
+ options = ordered(body, API_ORDER)
95
+ text = Text.new(name, options).to_yaml
96
+ definition = checked(name, text)
97
+ # The calls are those of the recipe just checked. The text is read
98
+ # back when it is written: the comments leave the data as it is.
99
+ text = Text.new(name, options, Calls.of(definition)).to_yaml if @calls
100
+ Result.new(name: name, version: @version, text: text, calls: definition.routes.size, changes: @changes,
101
+ variables: env_of(false).merge(@given), defaults: env_of(true).slice(*@expressions.keys), expressions: @expressions,
102
+ verify_with: @verify_with,
92
103
  refs: @refs.to_h { |variable, ref| [variable, ref.merge(credential: ref[:credential] || @secret.include?(variable))] })
93
104
  end
94
105
 
@@ -255,7 +266,8 @@ module ApiRecipes
255
266
  case key
256
267
  when 'verify_with' then left_out(key, value)
257
268
  when 'variables' then out[key] = declared_variables(value)
258
- when 'host', 'base_url' then out[key] = with_variables(value, key, key)
269
+ when 'host' then out[key] = with_variables(value, key, key)
270
+ when 'base_url' then out[key] = with_variables(as_text(value, key), key, key)
259
271
  when *OPTION_KEYS then out[key] = option(value, key, key)
260
272
  when *SENT then out[key] = sent(value, key)
261
273
  when 'endpoints' then out[key] = endpoints(value, key)
@@ -296,7 +308,7 @@ module ApiRecipes
296
308
  here = "#{where}.#{key}"
297
309
  case key
298
310
  when 'verify_with' then left_out(here, value)
299
- when 'path' then out[key] = with_variables(value, here, "#{name}_path")
311
+ when 'path' then out[key] = with_variables(as_text(value, here), here, "#{name}_path")
300
312
  when *OPTION_KEYS then out[key] = option(value, here, "#{name}_#{key}")
301
313
  when *SENT then out[key] = sent(value, here)
302
314
  when 'endpoints' then out[key] = endpoints(value, here)
@@ -328,12 +340,53 @@ module ApiRecipes
328
340
  end
329
341
  if secret
330
342
  [name, credential(content, here, name)]
343
+ elsif text_in_braces?(content, escaped: false)
344
+ [name, braces_kept(content, here, name)]
331
345
  else
332
346
  [name, with_variables(content, here, name)]
333
347
  end
334
348
  end
335
349
  end
336
350
 
351
+ # A word in braces that the file does not declare as a variable: 2.x
352
+ # sent it as text, and 3.0 would read it as a variable. In a path and
353
+ # in the base_url a backslash before the brace already keeps it text;
354
+ # a header and a parameter have no such escape.
355
+ TEXT_IN_BRACES = /(?<!\\)\{([A-Za-z_]\w*)\}/
356
+
357
+ def text_in_braces?(value, escaped: true)
358
+ pattern = escaped ? TEXT_IN_BRACES : Internals::Template::VARIABLE
359
+ value.is_a?(String) && value.scan(pattern).flatten.any? { |name| @origins[name] != :declared }
360
+ end
361
+
362
+ # In a path and in the base_url a brace is kept as text with a backslash.
363
+ def as_text(value, where)
364
+ return value unless text_in_braces?(value)
365
+
366
+ value.gsub(TEXT_IN_BRACES) do
367
+ name = Regexp.last_match(1)
368
+ next Regexp.last_match(0) if @origins[name] == :declared
369
+
370
+ @changes << "#{shown(where)}: {#{shown(name)}} was text in 2.x and would be a variable: it is written \\{#{shown(name)}}"
371
+ "\\{#{name}}"
372
+ end
373
+ end
374
+
375
+ # A header or a parameter has no way to write a brace as text: the value
376
+ # becomes the default of a variable, which is sent as it is.
377
+ def braces_kept(content, where, name)
378
+ if @token.match?(content)
379
+ refuse("#{shown(where)}: holds a word in braces, which was text in 2.x, and an ERB tag: a recipe cannot keep both " \
380
+ 'as they were; write the value by hand')
381
+ end
382
+ # Its own kind of code: a credential with the same text never shares
383
+ # this variable, nor its default.
384
+ variable = declare(variable_name(name), [:text, content], nil, content)
385
+ @changes << "#{shown(where)}: a word in braces was text in 2.x and would be a variable: the value is the default of " \
386
+ "the variable {#{variable}}"
387
+ "{#{variable}}"
388
+ end
389
+
337
390
  # A value that is already made of variables only, or of text and
338
391
  # variables the file declares, holds nothing to hide.
339
392
  def given_by_variables?(content)
@@ -467,10 +520,10 @@ module ApiRecipes
467
520
  (first + (options.keys - first - ['endpoints']) + (options.key?('endpoints') ? ['endpoints'] : [])).to_h { |key| [key, options[key]] }
468
521
  end
469
522
 
470
- # The result must be a portable recipe. Returns the number of its calls.
523
+ # The result must be a portable recipe. Returns its compiled tree.
471
524
  def checked(name, text)
472
525
  file_name = "#{name}#{Internals::Recipe::SUFFIX}"
473
- Internals::Recipe.parse(text, file_name, file_name: file_name).definition.routes.size
526
+ Internals::Recipe.parse(text, file_name, file_name: file_name).definition
474
527
  rescue ConfigurationError => e
475
528
  problems = e.errors.map { |problem| problem.delete_prefix("#{file_name}: ") }
476
529
  raise Refused.new(["#{shown(@file)} cannot become a portable recipe:"] + problems.map { |problem| " #{problem}" })
@@ -482,14 +535,20 @@ module ApiRecipes
482
535
  class Text
483
536
  INTERNAL = 'internal error: the recipe does not read back as it was written, so nothing was written'
484
537
 
485
- def initialize(name, options)
538
+ COMMENT_COLUMN = 34
539
+
540
+ # calls: { names of an endpoint => how it is called }, written in a
541
+ # comment beside the endpoint.
542
+ def initialize(name, options, calls = {})
486
543
  @name = name
487
544
  @options = options
545
+ @calls = calls
488
546
  end
489
547
 
490
548
  def to_yaml
491
549
  @lines = []
492
- write(0, @name, @options)
550
+ line(0, "#{scalar(@name)}:")
551
+ options(1, @options, [])
493
552
  text = "#{@lines.join("\n")}\n"
494
553
  raise Refused.new([INTERNAL]) unless YAML.safe_load(text) == { @name => @options }
495
554
 
@@ -500,23 +559,45 @@ module ApiRecipes
500
559
 
501
560
  private
502
561
 
503
- def write(indent, key, value)
504
- key = scalar(key)
562
+ # The options of the api, or of the endpoint that names holds from the
563
+ # api down. Only the entries of its `endpoints` are endpoints: a
564
+ # header or a parameter with the name of one gets no call.
565
+ def options(indent, body, names)
566
+ body.each do |key, value|
567
+ next write(indent, key, value) unless key.to_s == 'endpoints' && value.is_a?(Hash) && !value.empty?
568
+
569
+ line(indent, "#{scalar(key)}:")
570
+ value.each { |name, inner| endpoint(indent + 1, name, inner, names + [name.to_s]) }
571
+ end
572
+ end
573
+
574
+ def endpoint(indent, name, body, names)
575
+ return write(indent, name, body, @calls[names]) unless body.is_a?(Hash) && !body.empty?
576
+
577
+ line(indent, "#{scalar(name)}:", @calls[names])
578
+ options(indent + 1, body, names)
579
+ end
580
+
581
+ def write(indent, key, value, comment = nil)
582
+ written = scalar(key)
505
583
  case value
506
584
  when Hash
507
585
  if value.empty?
508
- line(indent, "#{key}: {}")
586
+ line(indent, "#{written}: {}", comment)
509
587
  else
510
- line(indent, "#{key}:")
588
+ line(indent, "#{written}:", comment)
511
589
  value.each { |name, inner| write(indent + 1, name, inner) }
512
590
  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)}")
591
+ when Array then line(indent, "#{written}: [#{value.map { |item| scalar(item) }.join(', ')}]", comment)
592
+ when nil then line(indent, "#{written}:", comment)
593
+ else line(indent, "#{written}: #{scalar(value)}", comment)
516
594
  end
517
595
  end
518
596
 
519
- def line(indent, text) = @lines << "#{' ' * indent}#{text}"
597
+ def line(indent, text, comment = nil)
598
+ text = "#{' ' * indent}#{text}"
599
+ @lines << (comment ? "#{text.ljust(COMMENT_COLUMN - 1)} # #{comment}" : text)
600
+ end
520
601
 
521
602
  def scalar(content)
522
603
  plain = content.is_a?(String) || content.is_a?(Integer) || content.is_a?(Float) || content == true || content == false
@@ -0,0 +1,65 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'erb'
4
+ require 'yaml'
5
+
6
+ module ApiRecipes
7
+ module CLI
8
+ # A file of a 2.x project that describes apis: YAML, which may hold ERB.
9
+ # The gem no longer loads such a file: the commands read it to check it,
10
+ # to list its calls and to convert it into a portable recipe.
11
+ module Description
12
+ # Returns the apis of the file as { name => description }. ERB is
13
+ # evaluated only with erb: true; without it a file that contains ERB
14
+ # is given to the block, which returns the text to read, or is refused
15
+ # when there is no block. Nothing in it is run.
16
+ def self.read(path, erb: false)
17
+ unless (path.is_a?(String) || path.is_a?(Pathname)) && !path.to_s.include?("\0")
18
+ raise ConfigurationError.new(['every path must be a String or a Pathname, without null bytes'])
19
+ end
20
+
21
+ full_path = File.expand_path(path)
22
+ if shared_recipe?(full_path)
23
+ raise RecipeFileError.new(path, 'is a portable recipe (.recipe.yml): it is read as data only')
24
+ end
25
+
26
+ text = read_text(path, full_path)
27
+ if erb
28
+ text = ERB.new(text).result
29
+ elsif text.include?('<%')
30
+ unless block_given?
31
+ raise RecipeFileError.new(path, 'contains ERB: run again with --erb to evaluate it ' \
32
+ '(this executes the code in the file)')
33
+ end
34
+ text = yield(text)
35
+ end
36
+ data = begin
37
+ YAML.safe_load(text, permitted_classes: [Symbol], aliases: true)
38
+ rescue Psych::Exception => e
39
+ raise RecipeFileError.new(path, "invalid YAML: #{e.message}")
40
+ end
41
+ raise RecipeFileError.new(path, 'file is empty') if data.nil?
42
+ raise RecipeFileError.new(path, 'must contain a mapping of api names') unless data.is_a?(Hash)
43
+
44
+ Internals::Compiler.normalize(data, :options_map)
45
+ end
46
+
47
+ def self.read_text(path, full_path)
48
+ text = File.read(full_path, encoding: 'UTF-8')
49
+ raise RecipeFileError.new(path, 'file is not valid UTF-8') unless text.valid_encoding?
50
+
51
+ text
52
+ rescue Errno::ENOENT
53
+ raise RecipeFileError.new(path, 'file not found')
54
+ rescue SystemCallError => e
55
+ raise RecipeFileError.new(path, "cannot read file (#{e.class.name.split('::').last})")
56
+ end
57
+
58
+ def self.shared_recipe?(full_path)
59
+ names = [full_path]
60
+ names << File.realpath(full_path) if File.exist?(full_path)
61
+ names.any? { |name| name.downcase.end_with?('.recipe.yml') }
62
+ end
63
+ end
64
+ end
65
+ end
@@ -5,7 +5,8 @@ module ApiRecipes
5
5
  class Import
6
6
  # One entry of `servers` as the options of an api: protocol, host, port,
7
7
  # base_url and variables. Only what differs from the defaults of the gem
8
- # is returned.
8
+ # is returned. A recipe needs a host: one that the description does not
9
+ # give is a variable, which the application gives.
9
10
  class Server
10
11
  Result = Data.define(:options, :warnings)
11
12
 
@@ -28,7 +29,7 @@ module ApiRecipes
28
29
 
29
30
  def read
30
31
  server = chosen
31
- return Result.new(options: {}, warnings: @warnings) if server.nil?
32
+ return Result.new(options: { host: host_variable('the description names no server') }, warnings: @warnings) if server.nil?
32
33
 
33
34
  @where = "servers[#{@index}]"
34
35
  @declared = server['variables'].is_a?(Hash) ? server['variables'] : {}
@@ -49,7 +50,6 @@ module ApiRecipes
49
50
  if servers.empty?
50
51
  raise Error, "--server #{@index}: the description names no server" unless @index.zero?
51
52
 
52
- @warnings << 'the description names no server: set host in the recipe'
53
53
  return nil
54
54
  end
55
55
  unless @index.between?(0, servers.size - 1)
@@ -63,8 +63,18 @@ module ApiRecipes
63
63
  end
64
64
 
65
65
  def relative(path)
66
- @warnings << 'the server address is relative: set host in the recipe'
67
- with_variables({ base_url: base_url(path) }.compact)
66
+ options = with_variables({ base_url: base_url(path) }.compact)
67
+ { host: host_variable('the server address is relative') }.merge(options)
68
+ end
69
+
70
+ # The variable that stands for the host, named so that it is not one
71
+ # of the variables of the address.
72
+ def host_variable(why)
73
+ taken = @names.values
74
+ name = %w[host api_host].find { |one| !taken.include?(one) }
75
+ name ||= (2..).lazy.map { |number| "api_host_#{number}" }.find { |one| !taken.include?(one) }
76
+ @warnings << "#{why}: the host is the variable {#{name}}, to give with config.values"
77
+ "{#{name}}"
68
78
  end
69
79
 
70
80
  def absolute(scheme, authority, path)
@@ -140,11 +150,12 @@ module ApiRecipes
140
150
  end
141
151
  end
142
152
 
143
- # Adds the variables that host and base_url use, in the order they appear.
153
+ # Adds the declarations of the variables that host and base_url use,
154
+ # in the order they appear. A variable with no default and no
155
+ # description needs none: the recipe uses it.
144
156
  def with_variables(options)
145
- return options if @names.empty?
146
-
147
- options.merge(variables: @names.to_h { |original, name| [name, declaration(original)] })
157
+ declared = @names.to_h { |original, name| [name, declaration(original)] }.reject { |_, spec| spec.empty? }
158
+ declared.empty? ? options : options.merge(variables: declared)
148
159
  end
149
160
 
150
161
  def declaration(original)
@@ -10,7 +10,7 @@ module ApiRecipes
10
10
  # Ruby's YAML generator. Before the text is returned it is read back and
11
11
  # compared with the data it was written from.
12
12
  class Writer
13
- API_KEYS = %i[protocol host port base_url auth variables].freeze
13
+ API_KEYS = %i[recipe protocol host port base_url auth variables].freeze
14
14
  ENDPOINT_KEYS = %i[path verb route ok_code].freeze
15
15
  COMMENT_COLUMN = 34
16
16
  MAX_NAME = 1000
@@ -18,11 +18,14 @@ module ApiRecipes
18
18
  LINE_BREAKING = /[[:cntrl:]\u2028\u2029]/
19
19
  INTERNAL = 'internal error: the recipe does not read back as it was written, so nothing was written'
20
20
 
21
- def initialize(name:, options:, nodes:, header: nil)
21
+ # calls: { names of an endpoint => how it is called }, written in a
22
+ # comment under the endpoint; nil to write none.
23
+ def initialize(name:, options:, nodes:, header: nil, calls: nil)
22
24
  @name = name
23
25
  @options = options
24
26
  @nodes = nodes
25
27
  @header = header
28
+ @calls = calls
26
29
  end
27
30
 
28
31
  def to_yaml
@@ -57,11 +60,13 @@ module ApiRecipes
57
60
  body.empty? ? nil : body
58
61
  end
59
62
 
60
- def nodes(list, indent, where)
63
+ def nodes(list, indent, where, names = [])
61
64
  list.to_h do |node|
62
65
  name = scalar(node.name, where, 'the name of an endpoint')
63
66
  comment = Import.one_line(node.comment)
64
67
  line(indent, "#{name}:", comment.empty? ? nil : comment)
68
+ called = names + [node.name.to_s]
69
+ call_line(@calls[called]) if @calls && @calls[called]
65
70
  here = "#{where}.#{node.name}"
66
71
  body = {}
67
72
  ENDPOINT_KEYS.each do |key|
@@ -69,7 +74,7 @@ module ApiRecipes
69
74
  end
70
75
  unless node.children.empty?
71
76
  line(indent + 1, 'endpoints:')
72
- body['endpoints'] = nodes(node.children, indent + 2, "#{here}.endpoints")
77
+ body['endpoints'] = nodes(node.children, indent + 2, "#{here}.endpoints", called)
73
78
  end
74
79
  [node.name, body.empty? ? nil : body]
75
80
  end
@@ -96,6 +101,13 @@ module ApiRecipes
96
101
  end
97
102
  end
98
103
 
104
+ # A comment of its own under the line just written, where the comment
105
+ # of that line starts: how the endpoint is called.
106
+ def call_line(call)
107
+ column = @lines.last.index(' # ') || [COMMENT_COLUMN - 1, @lines.last.length].max
108
+ @lines << "#{' ' * column} # #{Import.one_line(call)}"
109
+ end
110
+
99
111
  def line(indent, text, comment = nil)
100
112
  text = "#{' ' * indent}#{text}"
101
113
  text = "#{text.ljust(COMMENT_COLUMN - 1)} # #{comment}" if comment
@@ -10,15 +10,19 @@ module ApiRecipes
10
10
  # The description cannot be imported. The message says where and why.
11
11
  class Error < ApiRecipes::Error; end
12
12
 
13
- Result = Data.define(:text, :warnings, :summary)
13
+ Result = Data.define(:name, :text, :warnings, :summary)
14
14
  MAX_WARNINGS = 100
15
15
 
16
- def initialize(path, name: nil, only: [], except: [], server: 0)
16
+ # calls: write beside each endpoint how it is called in Ruby.
17
+ # version: the version of the recipe that is written.
18
+ def initialize(path, name: nil, only: [], except: [], server: 0, calls: false, version: Convert::DEFAULT_VERSION)
19
+ @version = version
17
20
  @path = path
18
21
  @name = name
19
22
  @only = only
20
23
  @except = except
21
24
  @server = server
25
+ @calls = calls
22
26
  end
23
27
 
24
28
  # Reads the description and returns the text of the recipe with the
@@ -30,14 +34,22 @@ module ApiRecipes
30
34
  server = Server.read(document, @server)
31
35
  security = Security.read(document)
32
36
  tree = Tree.build(document, only: @only, except: @except)
33
- options = server.options.dup
37
+ raise Error, '--version: must be made of digits, letters and dots, such as 1.2.0' unless Internals::Recipe::VERSION.match?(@version.to_s)
38
+
39
+ options = { recipe: { 'name' => name, 'version' => @version, 'format' => Internals::Recipe::FORMAT } }.merge(server.options)
34
40
  options[:auth] = security.auth if security.auth
35
41
  header = "Generated by api_recipes import from #{document.title} #{document.version}"
36
42
  text = Writer.new(name: name, options: options, nodes: tree.nodes, header: header).to_yaml
37
- verify(text)
43
+ compiled = verify(text)
44
+ if @calls
45
+ # The calls are those of the recipe just written and checked. The
46
+ # writer reads its text back: the comments leave the data as it is.
47
+ calls = Calls.of(compiled)
48
+ text = Writer.new(name: name, options: options, nodes: tree.nodes, header: header, calls: calls).to_yaml
49
+ end
38
50
  warnings += server.warnings + security.warnings + tree.warnings
39
51
  warnings << 'no operation was imported' if tree.operations.zero?
40
- Result.new(text: text, warnings: shown_warnings(warnings), summary: summary(tree, warnings.size))
52
+ Result.new(name: name, text: text, warnings: shown_warnings(warnings), summary: summary(tree, warnings.size))
41
53
  end
42
54
 
43
55
  private
@@ -51,8 +63,8 @@ module ApiRecipes
51
63
  name = 'api' if name.empty?
52
64
  name = "api_#{name}" if name.match?(/\A\d/)
53
65
  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'
66
+ unless name.is_a?(String) && Internals::Compiler::METHOD_NAME.match?(name) && Internals::Recipe::NAME.match?(name)
67
+ raise Error, '--name: must be the name of a recipe and of a method: lowercase letters, digits and _, not starting with a digit'
56
68
  end
57
69
 
58
70
  warnings = []
@@ -70,9 +82,11 @@ module ApiRecipes
70
82
  end
71
83
 
72
84
  # The text must be a recipe that the gem compiles.
85
+ # What is written is a portable recipe: it is checked as one. Returns
86
+ # its compiled tree.
73
87
  def verify(text)
74
- apis = Internals::Compiler.normalize(YAML.safe_load(text), :options_map)
75
- Internals::Compiler.compile_all(apis)
88
+ file_name = "#{YAML.safe_load(text).keys.first}#{Internals::Recipe::SUFFIX}"
89
+ Internals::Recipe.parse(text, file_name, file_name: file_name).definition
76
90
  rescue ConfigurationError => e
77
91
  raise Error, "the recipe would not be valid, so nothing was written:\n#{e.errors.map { |problem| " #{problem}" }.join("\n")}"
78
92
  end
@@ -18,7 +18,7 @@ module ApiRecipes
18
18
 
19
19
  # A header or a parameter sent with every request. where: the name of
20
20
  # the endpoint that adds it, nil for the api; below: whether that
21
- # endpoint has others below it, which take it too.
21
+ # endpoint contains others, whose requests find it there too.
22
22
  Sent = Data.define(:name, :value, :where, :below) do
23
23
  def key = [name, where]
24
24
  end
@@ -166,7 +166,7 @@ module ApiRecipes
166
166
  def sent_row(one) = "#{clip(one.name, PART)}: #{clip(one.value, PART)}#{place(one, PART)}"
167
167
 
168
168
  def place(one, limit)
169
- one.where ? " (#{clip(one.where, limit)}#{' and below' if one.below})" : ''
169
+ one.where ? " (#{clip(one.where, limit)}#{' and the endpoints it contains' if one.below})" : ''
170
170
  end
171
171
 
172
172
  # What changes between two lists of headers or of parameters, a line
@@ -171,7 +171,9 @@ module ApiRecipes
171
171
  summary.warnings.each { |warning| @out.puts " warning: #{warning}" }
172
172
  return if current.nil? || current == summary.text
173
173
 
174
- if entry && entry.sha256 != Recipe.digest(current)
174
+ if entry.nil?
175
+ @out.puts " #{destination} is a recipe that recipes.lock does not name: what it holds now will be lost"
176
+ elsif entry.sha256 != Recipe.digest(current)
175
177
  @out.puts " #{destination} was changed after it was installed: those changes will be lost"
176
178
  end
177
179
  summary.changes_from(installed_summary(current, destination)).each { |line| @out.puts line }
@@ -274,7 +276,8 @@ module ApiRecipes
274
276
 
275
277
  recipe = Recipe.parse(text, file, file_name: File.basename(file))
276
278
  describe(file, recipe)
277
- return 0 if lock[name].version == recipe.version
279
+ # A recipe of the project has its version in the file, and nowhere else.
280
+ return 0 if !lock.from_a_repository?(name) || lock[name].version == recipe.version
278
281
 
279
282
  @err.puts "#{lock.path}: #{name} is version #{lock[name].version} in the lock, but the file says #{recipe.version}"
280
283
  1
@@ -1,14 +1,24 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require 'securerandom'
4
+
3
5
  module ApiRecipes
4
6
  module CLI
5
7
  # The routes command: the calls that the recipes in some files offer, one
6
8
  # per line, with the verb and the address. A file called NAME.recipe.yml is
7
9
  # a portable recipe, read as data only.
8
10
  class Routes
9
- def initialize(files, erb: false)
11
+ STRUCTURE = 'contains ERB that decides the structure of the file (<% ... %>): run again with --erb to evaluate it ' \
12
+ '(this executes the code in the file)'
13
+
14
+ # project: the files were found in the project, not given: their names
15
+ # are shown without what a terminal would obey.
16
+ def initialize(files, erb: false, project: false)
10
17
  @files = Array(files)
11
18
  @erb = erb
19
+ @project = project
20
+ # What stands for the value of an ERB tag: random, so that no file can write it.
21
+ @mark = "API_RECIPES_ERB_#{SecureRandom.hex(6)}"
12
22
  end
13
23
 
14
24
  # Prints the calls on out and the problems on err. Returns the exit code:
@@ -24,32 +34,77 @@ module ApiRecipes
24
34
 
25
35
  private
26
36
 
37
+ def shown(file) = @project ? Recipes::Summary.shown(file, 300) : file
38
+
27
39
  # Adds the calls of file to rows. Returns the exit code for this file.
28
40
  def read(file, rows, err)
29
41
  unless File.file?(file) && File.readable?(file)
30
- err.puts "#{file}: #{File.file?(file) ? 'cannot be read' : (File.exist?(file) ? 'is not a file' : 'no such file')}"
42
+ err.puts "#{shown(file)}: #{File.file?(file) ? 'cannot be read' : (File.exist?(file) ? 'is not a file' : 'no such file')}"
31
43
  return 2
32
44
  end
33
45
 
46
+ tags = false
34
47
  apis = if file.end_with?(Internals::Recipe::SUFFIX)
35
48
  Internals::Recipe.read(file, compile: false).apis
36
49
  else
37
- Configuration.new.read_recipe_file(file, erb: @erb)
50
+ Description.read(file, erb: @erb) do |text|
51
+ tags = true
52
+ Tags.replaced(text, @mark) || raise(RecipeFileError.new(file, STRUCTURE))
53
+ end
38
54
  end
55
+ shown_as = []
56
+ apis = with_tags_shown(file, apis, shown_as) if tags
39
57
  Internals::Compiler.compile_all(apis).each_value do |api|
40
58
  api.routes.each { |route| rows << [route.call, Internals::OptionValue.shown_verb(route.verb), route.url] }
41
59
  end
60
+ if tags
61
+ err.puts "#{shown(file)}: what an ERB tag gives is shown as #{(shown_as.empty? ? ['erb'] : shown_as.uniq).map { |name| "{#{name}}" }.join(' and ')}; " \
62
+ '--erb evaluates the file, which runs the code in it'
63
+ end
42
64
  0
43
65
  rescue RecipeFileError => e
44
- e.errors.each { |problem| err.puts problem }
66
+ e.errors.each { |problem| err.puts(@project ? "#{shown(file)}: #{problem.delete_prefix("#{file}: ")}" : problem) }
45
67
  1
46
68
  rescue ConfigurationError => e
47
- e.errors.each { |problem| err.puts "#{file}: #{problem}" }
69
+ e.errors.each { |problem| err.puts "#{shown(file)}: #{problem}" }
48
70
  1
49
- rescue StandardError, ScriptError => e
50
- err.puts "#{file}: could not be evaluated (#{e.class})"
71
+ rescue StandardError, ScriptError, SystemStackError => e
72
+ err.puts "#{shown(file)}: could not be evaluated (#{e.class})"
51
73
  1
52
74
  end
75
+
76
+ # The apis with what each ERB tag gives written as a variable, which
77
+ # every api declares for it: the calls are listed, the tags are not run.
78
+ # The name of the variable is added to shown_as.
79
+ def with_tags_shown(file, apis, shown_as)
80
+ apis.to_h do |name, options|
81
+ raise RecipeFileError.new(file, 'an ERB tag gives a name: run again with --erb to evaluate it (this executes the code in the file)') if names_a_key?(name => options)
82
+ next [name, options] unless options.is_a?(Hash) && options.to_s.include?(@mark)
83
+
84
+ declared = options[:variables].is_a?(Hash) ? options[:variables] : {}
85
+ # A variable called erb that the api declares or uses is another one.
86
+ variable = declared.key?(:erb) || options.to_s.include?('{erb}') ? 'erb_tag' : 'erb'
87
+ shown_as << variable
88
+ [name, shown_as(options, "{#{variable}}").merge(variables: declared.merge(variable.to_sym => nil))]
89
+ end
90
+ end
91
+
92
+ def names_a_key?(value)
93
+ case value
94
+ when Hash then value.any? { |key, inner| key.to_s.include?(@mark) || names_a_key?(inner) }
95
+ when Array then value.any? { |inner| names_a_key?(inner) }
96
+ else false
97
+ end
98
+ end
99
+
100
+ def shown_as(value, variable)
101
+ case value
102
+ when Hash then value.transform_values { |inner| shown_as(inner, variable) }
103
+ when Array then value.map { |inner| shown_as(inner, variable) }
104
+ when String then value.include?(@mark) ? value.gsub(@mark, variable) : value
105
+ else value
106
+ end
107
+ end
53
108
  end
54
109
  end
55
110
  end
@@ -0,0 +1,19 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ApiRecipes
4
+ module CLI
5
+ # The ERB tags of a file that is read without running its code.
6
+ module Tags
7
+ COMMENT = /<%#.*?%>/m
8
+ OUTPUT = /<%=.*?%>/m
9
+
10
+ # text with each output tag replaced by mark and each comment tag
11
+ # removed; nil when another tag is left, which can decide the lines the
12
+ # file has.
13
+ def self.replaced(text, mark)
14
+ plain = text.gsub(COMMENT, '').gsub(OUTPUT, mark)
15
+ plain.gsub('<%%', '').include?('<%') ? nil : plain.gsub('<%%', '<%')
16
+ end
17
+ end
18
+ end
19
+ end