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
@@ -18,8 +18,23 @@ module ApiRecipes
18
18
  end
19
19
  end
20
20
 
21
- # A definition holds the values of default_headers. Marshal and YAML
22
- # would write them, so they are refused; JSON gets to_h, which hides them.
21
+ # The name of a header as http.rb compares it: without case, and with
22
+ # _ read as -.
23
+ def self.header_key(name) = name.to_s.downcase.tr('_', '-')
24
+
25
+ # added over the headers of base that have the same name. One of the
26
+ # two is returned as it is when the other is empty.
27
+ def self.over_headers(base, added)
28
+ return base if added.empty?
29
+ return added if base.empty?
30
+
31
+ names = added.each_key.to_h { |name| [header_key(name), true] }
32
+ base.reject { |name, _| names.key?(header_key(name)) }.merge(added).freeze
33
+ end
34
+
35
+ # A definition holds the values of default_headers and default_params.
36
+ # Marshal and YAML would write them, so they are refused; JSON gets to_h,
37
+ # which hides them.
23
38
  module Serialization
24
39
  def marshal_dump = raise(TypeError, "an #{self.class} cannot be serialized: use to_h")
25
40
 
@@ -34,12 +49,12 @@ module ApiRecipes
34
49
  include Serialization
35
50
 
36
51
  attr_reader :name, :protocol, :host, :port, :base_url, :timeout, :on_bad_code, :mime_type,
37
- :verify_with, :default_headers, :auth, :variables, :recipe, :endpoints,
38
- :host_template, :base_url_template, :header_templates
52
+ :verify_with, :default_headers, :default_params, :auth, :variables, :recipe, :endpoints,
53
+ :host_template, :base_url_template, :header_templates, :param_templates
39
54
 
40
55
  def initialize(name:, protocol:, host:, port:, base_url:, timeout:, on_bad_code:, mime_type:, verify_with:,
41
- default_headers:, auth:, variables:, recipe:, host_template:, base_url_template:,
42
- header_templates:, children:)
56
+ default_headers:, default_params:, auth:, variables:, recipe:, host_template:,
57
+ base_url_template:, header_templates:, param_templates:, children:)
43
58
  @name = name
44
59
  @protocol = protocol
45
60
  @host = host
@@ -50,12 +65,14 @@ module ApiRecipes
50
65
  @mime_type = mime_type
51
66
  @verify_with = verify_with
52
67
  @default_headers = default_headers
68
+ @default_params = default_params
53
69
  @auth = auth
54
70
  @variables = variables
55
71
  @recipe = recipe
56
72
  @host_template = host_template
57
73
  @base_url_template = base_url_template
58
74
  @header_templates = header_templates
75
+ @param_templates = param_templates
59
76
  @endpoints = children.call(self).freeze
60
77
  freeze
61
78
  end
@@ -72,13 +89,14 @@ module ApiRecipes
72
89
  {
73
90
  name: name, protocol: protocol, host: host, port: port, base_url: base_url, timeout: timeout,
74
91
  on_bad_code: on_bad_code, mime_type: mime_type, verify_with: verify_with,
75
- default_headers: default_headers.transform_values { '[FILTERED]' }, auth: Definition.plain(auth),
92
+ default_headers: default_headers.transform_values { '[FILTERED]' },
93
+ default_params: default_params.transform_values { '[FILTERED]' }, auth: Definition.plain(auth),
76
94
  variables: Definition.plain(variables), recipe: Definition.plain(recipe),
77
95
  endpoints: endpoints.transform_values(&:to_h)
78
96
  }
79
97
  end
80
98
 
81
- # Never shows header values or the tree below.
99
+ # Never shows the values of headers and parameters, or the tree below.
82
100
  def inspect
83
101
  list = endpoints.empty? ? '' : " endpoints: #{endpoints.keys.join(', ')}"
84
102
  "#<#{self.class} #{name} #{protocol}://#{host}#{port && ":#{port}"}#{list}>"
@@ -111,8 +129,21 @@ module ApiRecipes
111
129
  class Endpoint
112
130
  include Serialization
113
131
 
114
- attr_reader :name, :full_name, :path, :full_path, :path_params, :verb, :ok_code, :timeout, :on_bad_code,
115
- :mime_type, :verify_with, :parent, :endpoints, :template
132
+ NONE = {}.freeze
133
+ # The options an endpoint that does not set them looks for up the
134
+ # tree: in the endpoints that contain it, from the nearest, then in the
135
+ # api; the first value found is used. default_headers and
136
+ # default_params are looked for in the same way, one name at a time.
137
+ # path, verb, route, ok_code and resource are read only on their endpoint.
138
+ INHERITED = %i[timeout on_bad_code mime_type verify_with].freeze
139
+
140
+ # header_templates, param_templates: the headers and the parameters
141
+ # written on this endpoint and on the endpoints above it, the nearest
142
+ # winning, ready to be filled; those of the api are not among them. An
143
+ # endpoint that adds none shares the Hash of the endpoint above it.
144
+ attr_reader :name, :full_name, :path, :full_path, :path_params, :path_variables, :verb, :ok_code, :timeout,
145
+ :on_bad_code, :mime_type, :verify_with, :header_templates, :param_templates, :parent,
146
+ :endpoints, :template
116
147
 
117
148
  def initialize(name:, parent:, own:, template:, children:)
118
149
  @name = name
@@ -126,13 +157,23 @@ module ApiRecipes
126
157
  @path = (own[:path] || name.to_s).dup.freeze
127
158
  @full_path = join_path(parent_path, template.to_s)
128
159
  @path_params = template.param_names
160
+ @path_variables = template.variable_names
129
161
  @verb = own[:verb] || :get
130
162
  @route = own[:route].nil? ? true : own[:route]
131
163
  @ok_code = own[:ok_code]
132
- @timeout = own[:timeout].nil? ? api.timeout : own[:timeout]
133
- @on_bad_code = own[:on_bad_code] || api.on_bad_code
134
- @mime_type = own[:mime_type].nil? ? api.mime_type : own[:mime_type]
135
- @verify_with = own(:verify_with) || api.verify_with
164
+ above = parent.is_a?(Endpoint) ? parent : nil
165
+ # The result of the search, kept on each endpoint: the parent has
166
+ # already made its own, so a request does not walk the tree again.
167
+ @taken = INHERITED.to_h { |key| [key, own[key].nil? && above ? above.own(key) : own[key]] }.freeze
168
+ @timeout = @taken[:timeout].nil? ? api.timeout : @taken[:timeout]
169
+ @on_bad_code = @taken[:on_bad_code] || api.on_bad_code
170
+ @mime_type = @taken[:mime_type].nil? ? api.mime_type : @taken[:mime_type]
171
+ @verify_with = @taken[:verify_with] || api.verify_with
172
+ @header_templates = Definition.over_headers(above ? above.header_templates : NONE,
173
+ templates(own[:default_headers], :header))
174
+ params = templates(own[:default_params], :param)
175
+ taken = above ? above.param_templates : NONE
176
+ @param_templates = params.empty? ? taken : taken.merge(params).freeze
136
177
  @endpoints = children.call(self).freeze
137
178
  freeze
138
179
  end
@@ -141,17 +182,20 @@ module ApiRecipes
141
182
  @route
142
183
  end
143
184
 
144
- # The value written on this endpoint, or nil. For :verify_with, the
145
- # value of the nearest endpoint, this one included, that has one.
146
- def own(key)
147
- value = @own[key]
148
- return value unless value.nil? && key == :verify_with && parent.is_a?(Endpoint)
185
+ # The headers and the parameters of header_templates and
186
+ # param_templates as they are written. They are built when asked: a
187
+ # copy kept on every endpoint would cost as much as the tree is deep.
188
+ def default_headers = @header_templates.transform_values(&:to_s).freeze
149
189
 
150
- parent.own(key)
151
- end
190
+ def default_params = @param_templates.transform_values(&:to_s).freeze
191
+
192
+ # The value written on this endpoint, or nil. For the options of
193
+ # INHERITED, the first value found from this endpoint up to the one
194
+ # under the api: the api is not looked at.
195
+ def own(key) = @taken.key?(key) ? @taken[key] : @own[key]
152
196
 
153
197
  def inspect
154
- "#<#{self.class} #{full_name} #{verb.to_s.upcase} #{full_path}>"
198
+ "#<#{self.class} #{full_name} #{OptionValue.shown_verb(verb)} #{full_path}>"
155
199
  end
156
200
 
157
201
  def pretty_print(printer)
@@ -161,14 +205,23 @@ module ApiRecipes
161
205
  def to_h
162
206
  {
163
207
  name: name, full_name: full_name, path: path, full_path: full_path,
164
- path_params: path_params.dup, verb: verb, route: route?, ok_code: Definition.plain(ok_code),
208
+ path_params: path_params.dup, path_variables: path_variables.dup, verb: verb, route: route?,
209
+ ok_code: Definition.plain(ok_code),
165
210
  timeout: timeout, on_bad_code: on_bad_code, mime_type: mime_type, verify_with: verify_with,
211
+ default_headers: @header_templates.transform_values { '[FILTERED]' },
212
+ default_params: @param_templates.transform_values { '[FILTERED]' },
166
213
  endpoints: endpoints.transform_values(&:to_h)
167
214
  }
168
215
  end
169
216
 
170
217
  private
171
218
 
219
+ def templates(texts, position)
220
+ return NONE if texts.nil? || texts.empty?
221
+
222
+ texts.transform_values { |text| Template.new(text, position) }.freeze
223
+ end
224
+
172
225
  def join_path(parent_path, own_path)
173
226
  joined = own_path.empty? ? parent_path : "#{parent_path}/#{own_path}"
174
227
  joined.gsub(%r{/+}, '/').freeze
@@ -30,10 +30,9 @@ module ApiRecipes
30
30
  end
31
31
 
32
32
  # Immutable map key => Level. It is stored in the instance variable
33
- # @__api_recipes of its owner (an instance, a class, a module or the
34
- # ApiRecipes module) and is replaced, never changed. The key of a level
35
- # written through a declaration is that Declaration, compared by identity;
36
- # the key of the global level is the api name. It never writes its content
33
+ # @__api_recipes of its owner, an object, and is replaced, never changed.
34
+ # The key of a level is the Declaration it was written through, compared
35
+ # by identity. It never writes its content
37
36
  # when serialized: a rebuilt LevelSet is sealed and answers "no credential"
38
37
  # for every key.
39
38
  class LevelSet
@@ -56,7 +55,11 @@ module ApiRecipes
56
55
  set.fetch(key.is_a?(String) ? key.to_sym : key)
57
56
  end
58
57
 
58
+ # Only an object has a set: the level of a class or a module is the
59
+ # one of its declaration, and the level of the application is in the
60
+ # registry. Both are given when the application starts.
59
61
  def write(owner, key)
62
+ raise Error, 'a level is written on an object, not on a class or a module' if Module === owner
60
63
  if owner.frozen?
61
64
  raise Error, 'cannot assign credentials or variables on a frozen object. ' \
62
65
  'Use with(...) to get a modified copy instead'
@@ -73,20 +76,18 @@ module ApiRecipes
73
76
  end
74
77
  end
75
78
 
76
- # Sets the variables of the levels in values (name => variables) and
77
- # removes those of the levels named in cleared, in one replacement of
78
- # the set. The credentials are not touched.
79
- def replace_variables(owner, values, cleared)
80
- WRITES.synchronize do
81
- set = live_set(owner)
82
- changes = cleared.to_h do |name|
83
- level = set&.fetch(name)
84
- [name, level && level.variables ? level.with(variables: nil) : level]
85
- end.compact
86
- values.each do |name, variables|
87
- changes[name] = (set&.fetch(name) || Level.new(credential: nil, variables: nil)).with(variables: variables)
88
- end
89
- store(owner, set, changes) unless changes.empty?
79
+ # Why a writer of Api refuses: what is the option (:authorization,
80
+ # :basic_auth, :variables), owner the caller, api the name of the api,
81
+ # plain false for an api returned by with.
82
+ def refusal(what, owner, api, plain)
83
+ return "an api returned by with cannot set #{what} for the caller: use with(#{what}: ...)" unless plain
84
+
85
+ if owner.equal?(ApiRecipes)
86
+ "ApiRecipes.#{api} is shared by the whole application, in every thread: give its #{what} to " \
87
+ "ApiRecipes.configure, as config.values = { #{api}: { #{what}: ... } }, or use with(#{what}: ...) for one chain"
88
+ else
89
+ "a class or a module is shared by all its objects, in every thread: give its #{what} to " \
90
+ "`api :#{api}, #{what}: ...`, or use an object or with(#{what}: ...) for one chain"
90
91
  end
91
92
  end
92
93
 
@@ -156,36 +157,46 @@ module ApiRecipes
156
157
  end
157
158
 
158
159
  module Levels
159
- # Levels that hold a value for one api, nearest first. Those of an object,
160
- # a class or a module are the ones written through declaration: the
161
- # object, every ancestor of its class (the owner itself for a class or a
162
- # module), then the class or module that declared the api when it is not
163
- # among them (an object or a class extended with it). A level written
164
- # through another declaration is never returned. Last the global level,
165
- # by api name. Without a declaration (a global api) only the global level.
160
+ # The levels of one request, nearest first, as [kind, level] pairs, with
161
+ # the registry the global one was read from: a request takes the tree in
162
+ # force and the values of the application from the same registry.
163
+ class Chain < Array
164
+ attr_reader :registry
165
+
166
+ def initialize(entries, registry)
167
+ super(entries)
168
+ @registry = registry
169
+ freeze
170
+ end
171
+ end
172
+
173
+ # Levels that hold a value for one api, nearest first: the one of the
174
+ # object, written through declaration; the one that declaration gives to
175
+ # the class or module where `api` was called, which is the only level a
176
+ # class or a module has; last the level of the application, by api name,
177
+ # which the registry in force holds. A level of another declaration is
178
+ # never returned. Without a declaration (a global api) only the last one.
166
179
  def self.chain(owner, api_name, declaration)
167
- chain = []
180
+ registry = Registry.current
181
+ entries = []
168
182
  if declaration
169
- if owner.is_a?(Module)
170
- klass = owner
171
- else
172
- klass = owner.class
183
+ unless Module === owner
173
184
  level = LevelSet.read(owner, declaration)
174
- chain << [:instance, level] if level
175
- end
176
- klass.ancestors.each do |mod|
177
- level = LevelSet.read(mod, declaration)
178
- chain << [:class, level] if level
179
- end
180
- declared_in = declaration.declared_in
181
- unless klass <= declared_in
182
- level = LevelSet.read(declared_in, declaration)
183
- chain << [:class, level] if level
185
+ entries << [:instance, level] if level
184
186
  end
187
+ level = declaration.level
188
+ entries << [:class, level] if level
185
189
  end
186
- level = LevelSet.read(ApiRecipes, api_name)
187
- chain << [:global, level] if level
188
- chain
190
+ level = registry.level(api_name)
191
+ entries << [:global, level] if level
192
+ Chain.new(entries, registry)
193
+ end
194
+
195
+ # The level of owner alone: what the readers of an api show.
196
+ def self.own(owner, api_name, declaration)
197
+ return LevelSet.read(owner, declaration) unless Module === owner
198
+
199
+ declaration ? declaration.level : Registry.current.level(api_name)
189
200
  end
190
201
  end
191
202
  end
@@ -0,0 +1,92 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ApiRecipes
4
+ module Internals
5
+ # The options that are read when a request is sent and can be written with
6
+ # {variables}: protocol, port, timeout, on_bad_code, mime_type, verb and
7
+ # ok_code. The tree keeps what is written; the value is made when the
8
+ # request is built, from the variables of the levels, and is checked for
9
+ # the option it is used as.
10
+ module OptionValue
11
+ KEYS = %i[protocol port timeout on_bad_code mime_type verb ok_code].freeze
12
+ USED_AS = {
13
+ protocol: 'the protocol, which must be http or https',
14
+ port: 'the port, which must be an integer from 1 to 65535',
15
+ timeout: 'the timeout, which must be a positive number',
16
+ on_bad_code: 'on_bad_code, which must be raise or ignore',
17
+ mime_type: 'the mime_type, which must not be empty or contain control characters',
18
+ verb: 'the verb, which must be one known to http.rb',
19
+ ok_code: 'the status that means success, which must be an integer from 100 to 599'
20
+ }.freeze
21
+ CONTROL = /[\x00-\x1F\x7F]/
22
+ WHOLE = /\A\{([A-Za-z_]\w*)\}\z/
23
+
24
+ class << self
25
+ # Whether the value of the option key is written with variables.
26
+ def variable?(key, value)
27
+ KEYS.include?(key) && value.is_a?(String) && Template::VARIABLE.match?(value)
28
+ end
29
+
30
+ # The name of the variable that gives the whole value, or nil.
31
+ def whole(value)
32
+ match = value.is_a?(String) && WHOLE.match(value)
33
+ match ? match[1].to_sym : nil
34
+ end
35
+
36
+ # The value of the option key, with the variables of values filled.
37
+ # What is written without variables is returned as it is. The message
38
+ # of the error names the variable and the option, never the value.
39
+ def resolve(key, value, values, api:)
40
+ return value unless variable?(key, value)
41
+
42
+ first = nil
43
+ text = value.gsub(Template::VARIABLE) do
44
+ name = Regexp.last_match(1).to_sym
45
+ first ||= name
46
+ raise MissingVariable.new(api, name) unless values.key?(name)
47
+
48
+ values[name].to_s
49
+ end
50
+ made = typed(key, text)
51
+ raise InvalidVariable.new(api, first, "is used as #{USED_AS.fetch(key)}") if made.nil?
52
+
53
+ made
54
+ end
55
+
56
+ # text as the value of the option key, or nil when it is not one.
57
+ def typed(key, text)
58
+ case key
59
+ when :protocol, :on_bad_code then (key == :protocol ? %w[http https] : %w[raise ignore]).include?(text) ? text.dup.freeze : nil
60
+ when :port then integer(text, 1, 65_535)
61
+ when :ok_code then integer(text, 100, 599)
62
+ when :timeout then number(text)
63
+ when :mime_type then text.empty? || CONTROL.match?(text.b) ? nil : text.dup.freeze
64
+ when :verb
65
+ verb = text.downcase.to_sym if text.match?(/\A[A-Za-z]{1,16}\z/)
66
+ verb && HTTP::Request::METHODS.include?(verb) ? verb : nil
67
+ end
68
+ end
69
+
70
+ # The verb as it is shown: in capitals, or as it is written when a
71
+ # variable gives it.
72
+ def shown_verb(verb) = variable?(:verb, verb) ? verb : verb.to_s.upcase
73
+
74
+ private
75
+
76
+ def integer(text, low, high)
77
+ return nil unless text.match?(/\A[0-9]{1,5}\z/)
78
+
79
+ number = text.to_i
80
+ number.between?(low, high) ? number : nil
81
+ end
82
+
83
+ def number(text)
84
+ return nil unless text.match?(/\A[0-9]{1,9}(\.[0-9]{1,9})?\z/)
85
+
86
+ number = text.include?('.') ? text.to_f : text.to_i
87
+ number.positive? ? number : nil
88
+ end
89
+ end
90
+ end
91
+ end
92
+ end
@@ -3,7 +3,8 @@
3
3
  module ApiRecipes
4
4
  module Internals
5
5
  # The `path` of one endpoint, parsed once. Fixed text is percent-encoded at
6
- # parse time; placeholder values are encoded at expand time.
6
+ # parse time; the values of placeholders and of {variables} are encoded at
7
+ # expand time.
7
8
  class PathTemplate
8
9
  NAME = /[A-Za-z_]\w*/
9
10
  FIXED_KEPT = /\A(?:[A-Za-z0-9\-._~!$&'()*+,;=:@\/]|%\h\h)/
@@ -24,21 +25,29 @@ module ApiRecipes
24
25
 
25
26
  def initialize(string)
26
27
  @parts = parse_parts(string).freeze
27
- names = @parts.select { |kind, _| kind != :text }.map(&:last)
28
+ names = @parts.select { |kind, _| %i[param splat].include?(kind) }.map(&:last)
28
29
  repeated = names.find { |name| names.count(name) > 1 }
29
30
  raise ArgumentError, "placeholder '#{repeated}' is repeated in '#{string}'" if repeated
30
31
  @param_names = names.freeze
32
+ @variable_names = @parts.select { |kind, _| kind == :variable }.map(&:last).uniq.freeze
31
33
  end
32
34
 
33
- attr_reader :param_names
35
+ # param_names: the placeholders, which take an argument each, in order.
36
+ # variable_names: the {variables} of the api, each once.
37
+ attr_reader :param_names, :variable_names
34
38
 
35
39
  # The block, if given, is called with the name of a parameter, :slash when
36
40
  # its value (not a splat) contains '/' or :encoded when it contains a
37
41
  # sequence %XX, and the endpoint. It never receives the value.
38
- def expand(values, endpoint:)
42
+ #
43
+ # context gives the values of the variables (variables) and the name of
44
+ # the api (definition.name). It is asked once, and only by a path that
45
+ # has a variable.
46
+ def expand(values, endpoint:, context: nil)
39
47
  remaining = values.dup
40
48
  out = +''
41
49
  index = 0
50
+ variables = nil
42
51
  # No &block parameter and no block inside this loop: either would allocate
43
52
  # a Proc at every call. The values are read from their encoded form: a '/'
44
53
  # in the value is '%2F' there, and a sequence %XX is '%25' and two hex
@@ -59,6 +68,14 @@ module ApiRecipes
59
68
  encoded = encode_splat(remaining.shift, content, endpoint)
60
69
  out << encoded
61
70
  yield content, :encoded, endpoint if block_given? && encoded.include?('%25') && encoded.match?(ENCODED_SEQUENCE)
71
+ when :variable
72
+ raise ArgumentError, 'a path with variables needs a context' if context.nil?
73
+
74
+ variables ||= context.variables
75
+ api = context.definition.name
76
+ raise MissingVariable.new(api, content) unless variables.key?(content)
77
+
78
+ out << Template.segment(variables[content], content, api)
62
79
  end
63
80
  end
64
81
  out
@@ -70,6 +87,7 @@ module ApiRecipes
70
87
  when :text then content
71
88
  when :param then ":#{content}"
72
89
  when :splat then "*#{content}"
90
+ when :variable then "{#{content}}"
73
91
  end
74
92
  end.join
75
93
  end
@@ -86,6 +104,13 @@ module ApiRecipes
86
104
  if rest.start_with?('\\:')
87
105
  text << ':'
88
106
  index += 2
107
+ elsif rest.start_with?('\\{')
108
+ text << '%7B'
109
+ index += 2
110
+ elsif (match = rest.match(/\A\{(#{NAME})\}/o))
111
+ flush(parts, text)
112
+ parts << [:variable, match[1].to_sym]
113
+ index += match[0].length
89
114
  elsif (match = rest.match(/\A:(#{NAME})/o))
90
115
  flush(parts, text)
91
116
  parts << [:param, match[1].to_sym]
@@ -0,0 +1,133 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'psych'
4
+
5
+ module ApiRecipes
6
+ module Internals
7
+ # Reads YAML that is only data: mappings with text keys, lists, text,
8
+ # numbers, booleans. What lets a small text say more than it shows, or say
9
+ # one thing to a reader and another to the parser, is refused before any
10
+ # object is built: characters that are not printed, anchors and aliases,
11
+ # tags, the merge key, a key given twice, a key that is not text, a second
12
+ # document, a deep nesting.
13
+ module PlainYaml
14
+ MAX_DEPTH = 100
15
+ # Control and format characters, line and paragraph separators, what is
16
+ # not assigned: what a terminal does not print as it is.
17
+ UNPRINTABLE = /[\p{C}\p{Zl}\p{Zp}]/
18
+ # The same in the text of a file, where a new line and a tab are at home:
19
+ # a comment is text that a person reads too, and the parser takes other
20
+ # characters than a new line as the end of a line.
21
+ HIDDEN = /[\p{Zl}\p{Zp}]|[\p{C}&&[^\n\r\t]]|\r(?!\n)/
22
+
23
+ class Refused < Error; end
24
+
25
+ # The events of the parser, checked one by one.
26
+ class Shape < Psych::Handler
27
+ Mapping = Struct.new(:keys, :key_next)
28
+ KINDS = { Integer => 'a number', Float => 'a number', TrueClass => 'a boolean', FalseClass => 'a boolean',
29
+ NilClass => 'nothing' }.freeze
30
+
31
+ def initialize
32
+ super
33
+ @stack = []
34
+ @documents = 0
35
+ @scanner = Psych::ScalarScanner.new(Psych::ClassLoader::Restricted.new([], []))
36
+ end
37
+
38
+ def start_document(*)
39
+ @documents += 1
40
+ refuse('holds more than one document') if @documents > 1
41
+ end
42
+
43
+ def alias(_anchor) = refuse('uses an anchor or an alias')
44
+
45
+ def scalar(value, anchor, tag, _plain, quoted, _style)
46
+ check(anchor, tag)
47
+ node(value, quoted)
48
+ end
49
+
50
+ def start_mapping(anchor, tag, _implicit, _style)
51
+ check(anchor, tag)
52
+ open(Mapping.new({}, true))
53
+ end
54
+
55
+ def start_sequence(anchor, tag, _implicit, _style)
56
+ check(anchor, tag)
57
+ open(:sequence)
58
+ end
59
+
60
+ def end_mapping = @stack.pop
61
+
62
+ def end_sequence = @stack.pop
63
+
64
+ private
65
+
66
+ def refuse(reason) = raise(Refused, reason)
67
+
68
+ def check(anchor, tag)
69
+ refuse('uses an anchor or an alias') if anchor
70
+ refuse('uses a tag') if tag
71
+ end
72
+
73
+ def open(frame)
74
+ node(nil)
75
+ @stack.push(frame)
76
+ refuse("is nested deeper than #{MAX_DEPTH} levels") if @stack.size > MAX_DEPTH
77
+ end
78
+
79
+ # A node in its place: a key of the mapping that holds it, or a value.
80
+ # text is nil for a mapping and a list.
81
+ def node(text, quoted = false)
82
+ parent = @stack.last
83
+ return unless parent.is_a?(Mapping)
84
+
85
+ key = parent.key_next
86
+ parent.key_next = !key
87
+ return unless key
88
+
89
+ refuse('has a key that is not plain text') if text.nil?
90
+ refuse('uses the merge key <<') if text == '<<'
91
+ refuse("the key '#{PlainYaml.label(text)}' is given twice") if parent.keys.key?(text)
92
+ parent.keys[text] = true
93
+ kind = quoted ? nil : kind_of(text)
94
+ refuse("the key '#{PlainYaml.label(text)}' is read as #{kind}, not as text: quote it") if kind
95
+ end
96
+
97
+ # What YAML reads an unquoted key as, when that is not text.
98
+ def kind_of(text)
99
+ value = @scanner.tokenize(text)
100
+ value.is_a?(String) ? nil : KINDS.fetch(value.class, 'something else')
101
+ rescue Psych::DisallowedClass
102
+ 'something else'
103
+ end
104
+ end
105
+
106
+ class << self
107
+ # The data of text, or nil when the text holds none.
108
+ def load(text, max_bytes:)
109
+ raise Refused, "is larger than #{max_bytes} bytes" if text.bytesize > max_bytes
110
+ raise Refused, 'is not valid UTF-8' unless text.encoding == Encoding::UTF_8 && text.valid_encoding?
111
+
112
+ hidden = text.index(HIDDEN)
113
+ if hidden
114
+ raise Refused, "line #{text[0, hidden].count("\n") + 1}: contains a character that is not printed " \
115
+ '(a control or a format character, or a line break that is not a new line)'
116
+ end
117
+
118
+ Psych::Parser.new(Shape.new).parse(text)
119
+ Psych.safe_load(text, aliases: false)
120
+ rescue Psych::SyntaxError => e
121
+ raise Refused, "is not valid YAML (line #{e.line})"
122
+ rescue Psych::DisallowedClass => e
123
+ raise Refused, "has a value that is not plain data (#{e.message[/[A-Z]\w*\z/]}): quote it"
124
+ end
125
+
126
+ # text as it can be shown: one line, at most limit characters.
127
+ def label(text, limit = 40)
128
+ text.to_s.scrub('?').gsub(UNPRINTABLE, '?')[0, limit]
129
+ end
130
+ end
131
+ end
132
+ end
133
+ end