api_recipes 3.0.0.beta4 → 3.0.0.beta6

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 (37) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +340 -107
  3. data/UPGRADING.md +197 -49
  4. data/lib/api_recipes/cli/calls.rb +27 -0
  5. data/lib/api_recipes/cli/convert/migration.rb +201 -6
  6. data/lib/api_recipes/cli/convert.rb +130 -23
  7. data/lib/api_recipes/cli/description.rb +65 -0
  8. data/lib/api_recipes/cli/import/server.rb +20 -9
  9. data/lib/api_recipes/cli/import/writer.rb +16 -4
  10. data/lib/api_recipes/cli/import.rb +23 -9
  11. data/lib/api_recipes/cli/recipes/summary.rb +7 -5
  12. data/lib/api_recipes/cli/recipes.rb +5 -2
  13. data/lib/api_recipes/cli/routes.rb +62 -7
  14. data/lib/api_recipes/cli/tags.rb +19 -0
  15. data/lib/api_recipes/cli/upgrade/fix.rb +206 -0
  16. data/lib/api_recipes/cli/upgrade/screen.rb +165 -0
  17. data/lib/api_recipes/cli/upgrade/tree_rules.rb +290 -0
  18. data/lib/api_recipes/cli/upgrade.rb +385 -63
  19. data/lib/api_recipes/cli.rb +84 -17
  20. data/lib/api_recipes/configuration.rb +17 -108
  21. data/lib/api_recipes/errors.rb +20 -3
  22. data/lib/api_recipes/internals/compiler.rb +77 -70
  23. data/lib/api_recipes/internals/context.rb +7 -2
  24. data/lib/api_recipes/internals/declaration.rb +17 -15
  25. data/lib/api_recipes/internals/definition.rb +15 -2
  26. data/lib/api_recipes/internals/level.rb +6 -1
  27. data/lib/api_recipes/internals/origins.rb +70 -0
  28. data/lib/api_recipes/internals/path_template.rb +23 -6
  29. data/lib/api_recipes/internals/recipe.rb +31 -5
  30. data/lib/api_recipes/internals/recipe_lock.rb +12 -9
  31. data/lib/api_recipes/internals/registry.rb +21 -10
  32. data/lib/api_recipes/internals/request.rb +2 -2
  33. data/lib/api_recipes/internals/template.rb +32 -2
  34. data/lib/api_recipes/response.rb +125 -6
  35. data/lib/api_recipes/version.rb +1 -1
  36. data/lib/api_recipes.rb +1 -0
  37. metadata +8 -1
@@ -5,6 +5,9 @@ require 'fileutils'
5
5
  require 'api_recipes'
6
6
  require 'api_recipes/version'
7
7
  require 'api_recipes/cli/code'
8
+ require 'api_recipes/cli/description'
9
+ require 'api_recipes/cli/tags'
10
+ require 'api_recipes/cli/calls'
8
11
  require 'api_recipes/cli/upgrade'
9
12
  require 'api_recipes/cli/import'
10
13
  require 'api_recipes/cli/routes'
@@ -24,27 +27,33 @@ module ApiRecipes
24
27
  Without arguments, in the root of a project: finds its Ruby files and the files
25
28
  that describe an api, and looks for what changed in api_recipes 3.0. It says what
26
29
  it checked. With arguments: the Ruby files under each PATH, and each configuration
27
- FILE checked with the 3.0 rules. It never changes a file. A file that contains ERB
30
+ FILE checked with the 3.0 rules. On a terminal it offers to make the changes it is
31
+ sure of, one at a time: it shows each as a diff and changes a file only when the
32
+ answer is y. Away from a terminal it never changes a file. A file that contains ERB
28
33
  is checked without running its code, leaving out what its tags give; --erb
29
34
  evaluates it instead: this runs the code in it. Where what to write is known it
30
35
  gives the code to paste, with the whole block of ApiRecipes.configure; --no-code
31
36
  leaves the code out.
32
37
  Exits with 1 if it finds something, 2 if it could not read something, 0 otherwise.
33
- import [--name NAME] [--only GLOB]... [--except GLOB]... [--server N] [--output FILE] FILE
38
+ import [--name NAME] [--version VERSION] [--only GLOB]... [--except GLOB]... [--server N] [--calls] [--output FILE] FILE
34
39
  Writes a recipe from the OpenAPI 3.0 or 3.1 description in FILE (YAML or JSON), on
35
40
  STDOUT or in the file given with --output, which must not exist. Warnings and a
36
41
  summary go to STDERR. --only and --except choose the paths: * also crosses slashes.
37
- --server chooses the entry of servers, counted from 0. Nothing in FILE is run, no
42
+ --server chooses the entry of servers, counted from 0. --calls writes under each
43
+ endpoint how it is called in Ruby. Nothing in FILE is run, no
38
44
  other file is read and the network is not used.
39
45
  Exits with 1 if the description cannot be imported, 2 if the arguments are wrong.
40
- routes [--erb] FILE...
46
+ routes [--erb] [FILE]...
41
47
  Lists the calls that the recipes in each FILE offer, with the verb and the address.
42
- A file that contains ERB is evaluated only with --erb: this runs the code in it.
48
+ Without a FILE, in the root of a project: the calls of every file that describes
49
+ an api and of every installed recipe. What an ERB tag gives is shown as {erb},
50
+ without running the tag; --erb evaluates the file: this runs the code in it.
43
51
  A file called NAME.recipe.yml is read as a portable recipe: as data only.
44
52
  Exits with 1 if a file is not a valid configuration, 2 if it could not read one.
45
- convert [--name NAME] [--version VERSION] [--to DIR] FILE
53
+ convert [--name NAME] [--version VERSION] [--calls] [--to DIR] [FILE]
46
54
  Moves the api that the configuration FILE of a project describes to a portable
47
- recipe. In the root of a project (a folder with a Gemfile, or where a git
55
+ recipe. Without FILE, in the root of a project: every api that a file of the
56
+ project describes, one after the other. In the root of a project (a folder with a Gemfile, or where a git
48
57
  repository starts): installs NAME.recipe.yml in config/api_recipes,
49
58
  moves the code of each ERB tag to config.values in the file that calls
50
59
  ApiRecipes.configure, removes the old description, and lists every file it
@@ -52,7 +61,8 @@ module ApiRecipes
52
61
  all: when it cannot, it gives the steps and the code to paste. With --to DIR it
53
62
  writes the recipe alone in DIR and leaves the project as it is. Nothing in FILE is run: a tag becomes a variable. A header or a parameter named
54
63
  like a credential is never copied into the recipe. --name chooses the api when
55
- FILE describes several; --version is the version of the recipe (1.0.0).
64
+ FILE describes several; --version is the version of the recipe (1.0.0); --calls
65
+ writes beside each endpoint how it is called in Ruby.
56
66
  Exits with 1 if FILE cannot become a recipe or the project cannot be changed
57
67
  safely, 2 if the arguments are wrong or something could not be read or written.
58
68
  install [--version VERSION] [--from URL] [--to DIR] [--yes] NAME|FILE
@@ -100,7 +110,7 @@ module ApiRecipes
100
110
  out.puts USAGE
101
111
  0
102
112
  when 'upgrade'
103
- upgrade(args, out, err)
113
+ upgrade(args, out, err, input)
104
114
  when 'import'
105
115
  import(args, out, err)
106
116
  when 'routes'
@@ -131,6 +141,8 @@ module ApiRecipes
131
141
  parser.on('--only GLOB') { |glob| options[:only] << glob }
132
142
  parser.on('--except GLOB') { |glob| options[:except] << glob }
133
143
  parser.on('--server N', Integer) { |number| options[:server] = number }
144
+ parser.on('--version VERSION') { |version| options[:version] = version }
145
+ parser.on('--calls') { options[:calls] = true }
134
146
  parser.on('--output FILE') { |file| output = file }
135
147
  paths = parser.parse(args)
136
148
  problem = import_problem(paths, output, options[:name])
@@ -140,6 +152,11 @@ module ApiRecipes
140
152
  end
141
153
 
142
154
  result = Import.new(paths.first, **options).call
155
+ expected = "#{result.name}#{Internals::Recipe::SUFFIX}"
156
+ if output&.end_with?(Internals::Recipe::SUFFIX) && File.basename(output) != expected
157
+ err.puts "--output: a recipe called #{result.name} is read from a file called #{expected}, not #{Recipes::Summary.shown(File.basename(output), 100)}"
158
+ return 2
159
+ end
143
160
  return 2 unless write_recipe(result.text, output, out, err)
144
161
 
145
162
  result.warnings.each { |warning| err.puts "warning: #{warning}" }
@@ -192,10 +209,13 @@ module ApiRecipes
192
209
  parser = OptionParser.new
193
210
  parser.on('--name NAME') { |name| options[:name] = name }
194
211
  parser.on('--version VERSION') { |version| options[:version] = version }
212
+ parser.on('--calls') { options[:calls] = true }
195
213
  parser.on('--to DIR') { |dir| directory = dir }
196
214
  files = parser.parse(args)
215
+ return convert_all(options, out, err) if files.empty? && directory.nil? && options[:name].nil? && project_root?
216
+
197
217
  unless files.size == 1
198
- err.puts 'convert needs one configuration file'
218
+ err.puts 'convert needs one configuration file, or none in the root of a project: it then converts every api the project describes'
199
219
  return 2
200
220
  end
201
221
 
@@ -276,23 +296,70 @@ module ApiRecipes
276
296
  2
277
297
  end
278
298
 
299
+ # Every api that a file of the project describes moves to a portable
300
+ # recipe, one at a time. Returns the highest exit code.
301
+ def convert_all(options, out, err)
302
+ described = Upgrade::Project.new.config_files.reject { |file| file.end_with?(Internals::Recipe::SUFFIX) }
303
+ if described.empty?
304
+ out.puts 'No file of this project describes an api: there is nothing to convert'
305
+ return 0
306
+ end
307
+
308
+ written = {}
309
+ codes = described.sort.flat_map do |file|
310
+ names = begin
311
+ Convert.shape(File.read(file)).keys
312
+ rescue Convert::Refused, Psych::Exception, SystemCallError
313
+ [nil]
314
+ end
315
+ names.map { |name| convert_one(file, names.size > 1 ? name : nil, options, written, out, err) }
316
+ end
317
+ codes.max
318
+ end
319
+
320
+ def convert_one(file, name, options, written, out, err)
321
+ out.puts
322
+ result = Convert.new(file, **options, name: name).call
323
+ Convert::Migration.new(result, file, out: out, err: err, written: written).call
324
+ rescue Convert::Refused => e
325
+ err.puts "#{Recipes::Summary.shown(file, 300)} was not converted:"
326
+ e.reasons.each { |reason| err.puts " - #{reason}" }
327
+ 1
328
+ rescue Convert::Unusable => e
329
+ err.puts e.message
330
+ 2
331
+ rescue SystemStackError
332
+ err.puts "#{Recipes::Summary.shown(file, 300)}: is nested too deeply to be read"
333
+ 1
334
+ rescue StandardError => e
335
+ err.puts "convert failed (#{e.class}): this is a defect of api_recipes, not of the file"
336
+ 1
337
+ end
338
+
279
339
  def routes(args, out, err)
280
340
  erb = false
281
341
  parser = OptionParser.new
282
342
  parser.on('--erb') { erb = true }
283
343
  files = parser.parse(args)
284
- if files.empty?
285
- err.puts 'routes needs at least one configuration file'
344
+ return Routes.new(files, erb: erb).report(out, err) unless files.empty?
345
+
346
+ # No file given: the apis of the project in the current directory.
347
+ unless project_root?
348
+ err.puts 'routes needs at least one configuration file, or to be run in the root of a project'
286
349
  return 2
287
350
  end
288
-
289
- Routes.new(files, erb: erb).report(out, err)
351
+ found = Upgrade::Project.new.config_files
352
+ if found.empty?
353
+ err.puts 'no file that describes an api was found in this project: name the files to read'
354
+ return 1
355
+ end
356
+ Routes.new(found, erb: erb, project: true).report(out, err)
290
357
  rescue OptionParser::ParseError => e
291
358
  err.puts e.message
292
359
  2
293
360
  end
294
361
 
295
- def upgrade(args, out, err)
362
+ def upgrade(args, out, err, input)
296
363
  configs = []
297
364
  erb = false
298
365
  parser = OptionParser.new
@@ -301,7 +368,7 @@ module ApiRecipes
301
368
  parser.on('--erb') { erb = true }
302
369
  parser.on('--no-code') { code = false }
303
370
  paths = parser.parse(args)
304
- return Upgrade.new(paths, config: configs, erb: erb, code: code).report(out, err) unless paths.empty? && configs.empty?
371
+ return Upgrade.new(paths, config: configs, erb: erb, code: code).report(out, err, input: input) unless paths.empty? && configs.empty?
305
372
 
306
373
  unless File.file?('Gemfile')
307
374
  err.puts 'upgrade without arguments checks the project in the current directory, and there is no Gemfile ' \
@@ -309,7 +376,7 @@ module ApiRecipes
309
376
  return 2
310
377
  end
311
378
 
312
- Upgrade.for_project(Upgrade::Project.new, erb: erb, code: code).report(out, err)
379
+ Upgrade.for_project(Upgrade::Project.new, erb: erb, code: code).report(out, err, input: input)
313
380
  rescue OptionParser::ParseError => e
314
381
  err.puts e.message
315
382
  2
@@ -1,7 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require 'yaml'
4
- require 'erb'
5
4
  require 'logger'
6
5
  require 'pathname'
7
6
 
@@ -17,9 +16,7 @@ module ApiRecipes
17
16
  attr_reader :value_levels
18
17
 
19
18
  def initialize
20
- @sources = []
21
19
  @apis_configs = {}
22
- @apis_files_paths = []
23
20
  @recipes_paths = []
24
21
  @value_levels = nil
25
22
  @draft = false
@@ -28,16 +25,14 @@ module ApiRecipes
28
25
  end
29
26
 
30
27
  # configure works on a copy: what a setter or the caller can change in
31
- # place (the list of sources, and the Hashes, Arrays and Strings of
32
- # apis_configs and apis_files_paths at every depth) is copied, so the
28
+ # place (the Hashes, Arrays and Strings of apis_configs and of
29
+ # recipes_paths at every depth) is copied, so the
33
30
  # original stays as it was. The logger of the application is shared. The
34
31
  # copy is the draft that configure yields, the only one that takes values.
35
32
  def initialize_copy(source)
36
33
  super
37
34
  @default_logger = nil
38
- @sources = @sources.dup
39
35
  @apis_configs = deep_copy(@apis_configs)
40
- @apis_files_paths = deep_copy(@apis_files_paths)
41
36
  @recipes_paths = deep_copy(@recipes_paths)
42
37
  @value_levels = nil
43
38
  @draft = true
@@ -54,7 +49,7 @@ module ApiRecipes
54
49
  # values, tenant names): only the names of the apis are shown.
55
50
  def inspect
56
51
  "#<#{self.class.name} apis_configs: #{@apis_configs.keys.inspect} " \
57
- "apis_files_paths: #{@apis_files_paths.size} recipes_paths: #{@recipes_paths.size} " \
52
+ "recipes_paths: #{@recipes_paths.size} " \
58
53
  "print_urls: #{@print_urls.inspect}>"
59
54
  end
60
55
 
@@ -66,18 +61,22 @@ module ApiRecipes
66
61
  raise ArgumentError, 'apis_configs must be an Hash' unless configs.is_a? Hash
67
62
 
68
63
  @apis_configs = Internals::Compiler.normalize(configs, :options_map)
69
- record_source(:hash)
70
64
  end
71
65
 
72
- attr_reader :apis_configs, :apis_files_paths, :recipes_paths
66
+ attr_reader :apis_configs, :recipes_paths
73
67
 
74
- def apis_files_paths=(paths = [])
75
- raise ArgumentError, 'apis_files_paths must be an Array' unless paths.is_a? Array
68
+ # 2.x loaded files of the project, YAML with ERB, through this option.
69
+ # An api is now described by a portable recipe, or by apis_configs.
70
+ REMOVED_FILES = 'apis_files_paths was removed in 3.0: an api is described by a portable recipe, loaded with recipes_paths. ' \
71
+ 'Run `api_recipes convert` in the root of the project: it moves every description to a recipe and ' \
72
+ 'changes this configuration'
76
73
 
77
- @apis_files_paths = paths
78
- record_source(:files)
74
+ def apis_files_paths=(*)
75
+ raise Error, REMOVED_FILES
79
76
  end
80
77
 
78
+ def apis_files_paths = raise(Error, REMOVED_FILES)
79
+
81
80
  # Portable recipes: files written by someone else, installed with the
82
81
  # api_recipes command. They are read as data only, never with ERB, and each
83
82
  # must match the recipes.lock of its folder.
@@ -102,32 +101,14 @@ module ApiRecipes
102
101
  @value_levels = Internals::Registry.value_levels(values)
103
102
  end
104
103
 
105
- # Applies the sources in the order they were assigned and returns the
106
- # apis as { name => description }. A later source replaces whole apis. The
107
- # recipes of recipes_paths come last and replace nothing: a name that
108
- # another source defines is an error.
104
+ # Returns the apis as { name => description }: those of apis_configs,
105
+ # then the recipes of recipes_paths, which replace nothing: a name that
106
+ # apis_configs defines is an error.
109
107
  def load
110
- apis = {}
111
- @sources.each do |kind|
112
- if kind == :hash
113
- apis.merge!(@apis_configs)
114
- else
115
- recipes = @recipes_paths.map { |path| expanded(path) }
116
- # A recipe that recipes_paths loads is left to it: a pattern such as
117
- # config/apis/*.yml* can match both kinds of file in one folder.
118
- @apis_files_paths.each { |path| merge_file(apis, path) unless recipes.include?(expanded(path)) }
119
- end
120
- end
108
+ apis = {}.merge(@apis_configs)
121
109
  apis.merge(Internals::Recipe.load_all(@recipes_paths, taken: apis.keys))
122
110
  end
123
111
 
124
- # Reads one file with the rules of apis_files_paths and returns the apis as
125
- # { name => description }. ERB is evaluated only with erb: true; without it a
126
- # file that contains ERB is refused and nothing in it is run.
127
- def read_recipe_file(path, erb: true, &without_erb)
128
- read_file(path, erb: erb, &without_erb)
129
- end
130
-
131
112
  def logger=(logger)
132
113
  @logger = logger
133
114
  end
@@ -157,78 +138,6 @@ module ApiRecipes
157
138
 
158
139
  private
159
140
 
160
- # @private
161
- def record_source(kind)
162
- @sources.delete(kind)
163
- @sources << kind
164
- end
165
-
166
- # @private
167
- def merge_file(apis, path)
168
- read_file(path).each do |api, params|
169
- logger.debug "File at #{path} overrides config for '#{api}' API" if apis.key?(api)
170
- apis[api] = params
171
- end
172
- end
173
-
174
- # @private
175
- def read_file(path, erb: true)
176
- unless (path.is_a?(String) || path.is_a?(Pathname)) && !path.to_s.include?("\0")
177
- raise ConfigurationError.new(['apis_files_paths: every path must be a String or a Pathname, without null bytes'])
178
- end
179
-
180
- full_path = File.expand_path(path)
181
- if shared_recipe?(full_path)
182
- raise RecipeFileError.new(path, 'is a portable recipe (.recipe.yml): give it to recipes_paths, which reads it as data only')
183
- end
184
-
185
- text = read_text(path, full_path)
186
- if erb
187
- text = ERB.new(text).result
188
- elsif text.include?('<%')
189
- unless block_given?
190
- raise RecipeFileError.new(path, 'contains ERB: run again with --erb to evaluate it ' \
191
- '(this executes the code in the file)')
192
- end
193
- text = yield(text)
194
- end
195
- data = begin
196
- YAML.safe_load(text, permitted_classes: [Symbol], aliases: true)
197
- rescue Psych::Exception => e
198
- raise RecipeFileError.new(path, "invalid YAML: #{e.message}")
199
- end
200
- raise RecipeFileError.new(path, 'file is empty') if data.nil?
201
- raise RecipeFileError.new(path, 'must contain a mapping of api names') unless data.is_a?(Hash)
202
-
203
- Internals::Compiler.normalize(data, :options_map)
204
- end
205
-
206
- # @private
207
- def read_text(path, full_path)
208
- text = File.read(full_path, encoding: 'UTF-8')
209
- raise RecipeFileError.new(path, 'file is not valid UTF-8') unless text.valid_encoding?
210
-
211
- text
212
- rescue Errno::ENOENT
213
- raise RecipeFileError.new(path, 'file not found')
214
- rescue SystemCallError => e
215
- raise RecipeFileError.new(path, "cannot read file (#{e.class.name.split('::').last})")
216
- end
217
-
218
- # @private
219
- def expanded(path)
220
- path.is_a?(String) || path.is_a?(Pathname) ? File.expand_path(path) : nil
221
- rescue ArgumentError
222
- nil
223
- end
224
-
225
- # @private
226
- def shared_recipe?(full_path)
227
- names = [full_path]
228
- names << File.realpath(full_path) if File.exist?(full_path)
229
- names.any? { |name| name.downcase.end_with?('.recipe.yml') }
230
- end
231
-
232
141
  # @private
233
142
  # A copy of value whose Hashes, Arrays and unfrozen Strings are new
234
143
  # objects; any other object is the same. A Hash or Array met twice, or
@@ -67,16 +67,19 @@ module ApiRecipes
67
67
  end
68
68
 
69
69
  class CredentialOriginMismatch < Error
70
- def initialize(api, credential_origin, request_origin)
70
+ # application: the credential is the one of config.values, the only one
71
+ # that credential_origins can send to other origins.
72
+ def initialize(api, credential_origin, request_origin, application: false)
73
+ remedy = application ? ', or name that origin in credential_origins, next to the credential in config.values' : ''
71
74
  if credential_origin
72
75
  super("api '#{api}': the credential is bound to #{credential_origin.inspect} but the request goes to " \
73
76
  "#{request_origin.inspect}. Set the credential at the level that changes the destination, " \
74
- 'or set it to nil to send none')
77
+ "or set it to nil to send none#{remedy}")
75
78
  else
76
79
  super("api '#{api}': the origin of the credential cannot be determined at the level that holds it " \
77
80
  '(for example, a variable of the host has no value there), so it is not sent to ' \
78
81
  "#{request_origin.inspect}. Set the credential at the level that sets the destination, " \
79
- 'or give the level that holds it the values its host needs')
82
+ "or give the level that holds it the values its host needs#{remedy}")
80
83
  end
81
84
  end
82
85
  end
@@ -122,6 +125,20 @@ module ApiRecipes
122
125
  end
123
126
  end
124
127
 
128
+ # Raised by Response#data for a body it cannot read. The message has the
129
+ # route, the status and the content type: never the body, which is on
130
+ # response.body.
131
+ class UnreadableResponse < Error
132
+ attr_reader :path, :response
133
+
134
+ def initialize(path, response, reason, advice)
135
+ @path = path
136
+ @response = response
137
+ route = path ? " on route '#{path}'" : ''
138
+ super("cannot read the data of the response#{route} (#{response.code}): #{reason}. #{advice}")
139
+ end
140
+ end
141
+
125
142
  class ApiConfigIsNotAnHash < Error
126
143
  def initialize(endpoint)
127
144
  message = "provided config for endpoint '#{endpoint}' must be an Hash"