api_recipes 3.0.0.beta3 → 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.
Files changed (35) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +377 -76
  3. data/UPGRADING.md +223 -59
  4. data/lib/api_recipes/cli/calls.rb +27 -0
  5. data/lib/api_recipes/cli/code.rb +153 -0
  6. data/lib/api_recipes/cli/convert/migration.rb +819 -0
  7. data/lib/api_recipes/cli/convert/snippet.rb +67 -0
  8. data/lib/api_recipes/cli/convert.rb +614 -0
  9. data/lib/api_recipes/cli/description.rb +65 -0
  10. data/lib/api_recipes/cli/import/server.rb +20 -9
  11. data/lib/api_recipes/cli/import/writer.rb +16 -4
  12. data/lib/api_recipes/cli/import.rb +23 -9
  13. data/lib/api_recipes/cli/recipes/summary.rb +25 -6
  14. data/lib/api_recipes/cli/recipes.rb +5 -2
  15. data/lib/api_recipes/cli/routes.rb +63 -8
  16. data/lib/api_recipes/cli/tags.rb +19 -0
  17. data/lib/api_recipes/cli/upgrade/fix.rb +206 -0
  18. data/lib/api_recipes/cli/upgrade/project.rb +194 -0
  19. data/lib/api_recipes/cli/upgrade/screen.rb +165 -0
  20. data/lib/api_recipes/cli/upgrade/tree_rules.rb +290 -0
  21. data/lib/api_recipes/cli/upgrade.rb +706 -57
  22. data/lib/api_recipes/cli.rb +171 -17
  23. data/lib/api_recipes/configuration.rb +17 -95
  24. data/lib/api_recipes/endpoint.rb +1 -1
  25. data/lib/api_recipes/internals/compiler.rb +102 -67
  26. data/lib/api_recipes/internals/context.rb +35 -6
  27. data/lib/api_recipes/internals/declaration.rb +17 -15
  28. data/lib/api_recipes/internals/definition.rb +16 -3
  29. data/lib/api_recipes/internals/option_value.rb +92 -0
  30. data/lib/api_recipes/internals/recipe.rb +1 -1
  31. data/lib/api_recipes/internals/recipe_lock.rb +12 -9
  32. data/lib/api_recipes/internals/request.rb +17 -6
  33. data/lib/api_recipes/version.rb +1 -1
  34. data/lib/api_recipes.rb +1 -0
  35. metadata +13 -1
@@ -1,12 +1,20 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require 'optparse'
4
+ require 'fileutils'
4
5
  require 'api_recipes'
5
6
  require 'api_recipes/version'
7
+ require 'api_recipes/cli/code'
8
+ require 'api_recipes/cli/description'
9
+ require 'api_recipes/cli/tags'
10
+ require 'api_recipes/cli/calls'
6
11
  require 'api_recipes/cli/upgrade'
7
12
  require 'api_recipes/cli/import'
8
13
  require 'api_recipes/cli/routes'
9
14
  require 'api_recipes/cli/recipes'
15
+ require 'api_recipes/cli/convert'
16
+ require 'api_recipes/cli/convert/snippet'
17
+ require 'api_recipes/cli/convert/migration'
10
18
 
11
19
  module ApiRecipes
12
20
  # The api_recipes command. It is not loaded by `require 'api_recipes'`.
@@ -15,23 +23,48 @@ module ApiRecipes
15
23
  Usage: api_recipes COMMAND [options]
16
24
 
17
25
  Commands:
18
- upgrade [--config FILE]... [--erb] [PATH]...
19
- Looks in the Ruby files under each PATH for what changed in api_recipes 3.0
20
- and checks each configuration FILE with the 3.0 rules. It never changes a file.
21
- A file that contains ERB is evaluated only with --erb: this runs the code in it.
26
+ upgrade [--config FILE]... [--erb] [--no-code] [PATH]...
27
+ Without arguments, in the root of a project: finds its Ruby files and the files
28
+ that describe an api, and looks for what changed in api_recipes 3.0. It says what
29
+ it checked. With arguments: the Ruby files under each PATH, and each configuration
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
33
+ is checked without running its code, leaving out what its tags give; --erb
34
+ evaluates it instead: this runs the code in it. Where what to write is known it
35
+ gives the code to paste, with the whole block of ApiRecipes.configure; --no-code
36
+ leaves the code out.
22
37
  Exits with 1 if it finds something, 2 if it could not read something, 0 otherwise.
23
- 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
24
39
  Writes a recipe from the OpenAPI 3.0 or 3.1 description in FILE (YAML or JSON), on
25
40
  STDOUT or in the file given with --output, which must not exist. Warnings and a
26
41
  summary go to STDERR. --only and --except choose the paths: * also crosses slashes.
27
- --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
28
44
  other file is read and the network is not used.
29
45
  Exits with 1 if the description cannot be imported, 2 if the arguments are wrong.
30
- routes [--erb] FILE...
46
+ routes [--erb] [FILE]...
31
47
  Lists the calls that the recipes in each FILE offer, with the verb and the address.
32
- 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.
33
51
  A file called NAME.recipe.yml is read as a portable recipe: as data only.
34
52
  Exits with 1 if a file is not a valid configuration, 2 if it could not read one.
53
+ convert [--name NAME] [--version VERSION] [--calls] [--to DIR] [FILE]
54
+ Moves the api that the configuration FILE of a project describes to a portable
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
57
+ repository starts): installs NAME.recipe.yml in config/api_recipes,
58
+ moves the code of each ERB tag to config.values in the file that calls
59
+ ApiRecipes.configure, removes the old description, and lists every file it
60
+ changed. It changes files only when git can undo it, and all at once or not at
61
+ all: when it cannot, it gives the steps and the code to paste. With --to DIR it
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
63
+ like a credential is never copied into the recipe. --name chooses the api when
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.
66
+ Exits with 1 if FILE cannot become a recipe or the project cannot be changed
67
+ safely, 2 if the arguments are wrong or something could not be read or written.
35
68
  install [--version VERSION] [--from URL] [--to DIR] [--yes] NAME|FILE
36
69
  Installs the portable recipe called NAME from the cookbook
37
70
  (https://github.com/madAle/api_recipes-cookbook) or from the Git repository at URL,
@@ -77,11 +110,13 @@ module ApiRecipes
77
110
  out.puts USAGE
78
111
  0
79
112
  when 'upgrade'
80
- upgrade(args, out, err)
113
+ upgrade(args, out, err, input)
81
114
  when 'import'
82
115
  import(args, out, err)
83
116
  when 'routes'
84
117
  routes(args, out, err)
118
+ when 'convert'
119
+ convert(args, out, err)
85
120
  when 'check'
86
121
  check(args, out, err)
87
122
  when 'install', 'update'
@@ -106,6 +141,8 @@ module ApiRecipes
106
141
  parser.on('--only GLOB') { |glob| options[:only] << glob }
107
142
  parser.on('--except GLOB') { |glob| options[:except] << glob }
108
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 }
109
146
  parser.on('--output FILE') { |file| output = file }
110
147
  paths = parser.parse(args)
111
148
  problem = import_problem(paths, output, options[:name])
@@ -115,6 +152,11 @@ module ApiRecipes
115
152
  end
116
153
 
117
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
118
160
  return 2 unless write_recipe(result.text, output, out, err)
119
161
 
120
162
  result.warnings.each { |warning| err.puts "warning: #{warning}" }
@@ -161,6 +203,66 @@ module ApiRecipes
161
203
  false
162
204
  end
163
205
 
206
+ def convert(args, out, err)
207
+ options = {}
208
+ directory = nil
209
+ parser = OptionParser.new
210
+ parser.on('--name NAME') { |name| options[:name] = name }
211
+ parser.on('--version VERSION') { |version| options[:version] = version }
212
+ parser.on('--calls') { options[:calls] = true }
213
+ parser.on('--to DIR') { |dir| directory = dir }
214
+ files = parser.parse(args)
215
+ return convert_all(options, out, err) if files.empty? && directory.nil? && options[:name].nil? && project_root?
216
+
217
+ unless files.size == 1
218
+ err.puts 'convert needs one configuration file, or none in the root of a project: it then converts every api the project describes'
219
+ return 2
220
+ end
221
+
222
+ result = Convert.new(files.first, **options).call
223
+ # In the root of a project, and told no folder, the project is moved to the recipe.
224
+ return Convert::Migration.new(result, files.first, out: out, err: err).call if directory.nil? && project_root?
225
+
226
+ directory ||= '.'
227
+ file_name = "#{result.name}#{Internals::Recipe::SUFFIX}"
228
+ path = directory == '.' ? file_name : File.join(directory, file_name)
229
+ return 2 unless place_recipe(result.text, directory, path, err)
230
+
231
+ Convert.report(result, files.first, path, out)
232
+ 0
233
+ rescue Convert::Refused => e
234
+ e.reasons.each { |reason| err.puts reason }
235
+ 1
236
+ rescue Convert::Unusable, OptionParser::ParseError => e
237
+ err.puts e.message
238
+ 2
239
+ rescue SystemStackError
240
+ err.puts 'the file is nested too deeply to be read'
241
+ 1
242
+ rescue StandardError => e
243
+ # What the command did not foresee is answered with one line, never
244
+ # with the text of an exception, which could hold a value of the file.
245
+ err.puts "convert failed (#{e.class}): this is a defect of api_recipes, not of the file"
246
+ 1
247
+ end
248
+
249
+ # The current directory is the root of a project: it has a Gemfile, or
250
+ # it is where a git repository starts.
251
+ def project_root? = File.file?('Gemfile') || File.exist?('.git')
252
+
253
+ # The recipe is created in its folder, never replaced.
254
+ def place_recipe(text, directory, path, err)
255
+ FileUtils.mkdir_p(directory)
256
+ File.open(path, File::WRONLY | File::CREAT | File::EXCL) { |file| file.write(text) }
257
+ true
258
+ rescue Errno::EEXIST
259
+ err.puts "#{path} already exists: remove it, or choose another folder with --to"
260
+ false
261
+ rescue SystemCallError => e
262
+ err.puts "#{path}: cannot be written (#{e.class.name.split('::').last})"
263
+ false
264
+ end
265
+
164
266
  def check(args, out, err)
165
267
  directory = Recipes::DEFAULT_DIRECTORY
166
268
  parser = OptionParser.new
@@ -194,35 +296,87 @@ module ApiRecipes
194
296
  2
195
297
  end
196
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
+
197
339
  def routes(args, out, err)
198
340
  erb = false
199
341
  parser = OptionParser.new
200
342
  parser.on('--erb') { erb = true }
201
343
  files = parser.parse(args)
202
- if files.empty?
203
- 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'
204
349
  return 2
205
350
  end
206
-
207
- 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)
208
357
  rescue OptionParser::ParseError => e
209
358
  err.puts e.message
210
359
  2
211
360
  end
212
361
 
213
- def upgrade(args, out, err)
362
+ def upgrade(args, out, err, input)
214
363
  configs = []
215
364
  erb = false
216
365
  parser = OptionParser.new
366
+ code = true
217
367
  parser.on('--config FILE') { |file| configs << file }
218
368
  parser.on('--erb') { erb = true }
369
+ parser.on('--no-code') { code = false }
219
370
  paths = parser.parse(args)
220
- if paths.empty? && configs.empty?
221
- err.puts 'upgrade needs a directory or a file to scan, or --config FILE'
371
+ return Upgrade.new(paths, config: configs, erb: erb, code: code).report(out, err, input: input) unless paths.empty? && configs.empty?
372
+
373
+ unless File.file?('Gemfile')
374
+ err.puts 'upgrade without arguments checks the project in the current directory, and there is no Gemfile ' \
375
+ 'here: run it in the root of the project, or name the directories and the files to check'
222
376
  return 2
223
377
  end
224
378
 
225
- Upgrade.new(paths, config: configs, erb: erb).report(out, err)
379
+ Upgrade.for_project(Upgrade::Project.new, erb: erb, code: code).report(out, err, input: input)
226
380
  rescue OptionParser::ParseError => e
227
381
  err.puts e.message
228
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,29 +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
- @apis_files_paths.each { |path| merge_file(apis, path) }
116
- end
117
- end
108
+ apis = {}.merge(@apis_configs)
118
109
  apis.merge(Internals::Recipe.load_all(@recipes_paths, taken: apis.keys))
119
110
  end
120
111
 
121
- # Reads one file with the rules of apis_files_paths and returns the apis as
122
- # { name => description }. ERB is evaluated only with erb: true; without it a
123
- # file that contains ERB is refused and nothing in it is run.
124
- def read_recipe_file(path, erb: true)
125
- read_file(path, erb: erb)
126
- end
127
-
128
112
  def logger=(logger)
129
113
  @logger = logger
130
114
  end
@@ -154,68 +138,6 @@ module ApiRecipes
154
138
 
155
139
  private
156
140
 
157
- # @private
158
- def record_source(kind)
159
- @sources.delete(kind)
160
- @sources << kind
161
- end
162
-
163
- # @private
164
- def merge_file(apis, path)
165
- read_file(path).each do |api, params|
166
- logger.debug "File at #{path} overrides config for '#{api}' API" if apis.key?(api)
167
- apis[api] = params
168
- end
169
- end
170
-
171
- # @private
172
- def read_file(path, erb: true)
173
- unless (path.is_a?(String) || path.is_a?(Pathname)) && !path.to_s.include?("\0")
174
- raise ConfigurationError.new(['apis_files_paths: every path must be a String or a Pathname, without null bytes'])
175
- end
176
-
177
- full_path = File.expand_path(path)
178
- if shared_recipe?(full_path)
179
- raise RecipeFileError.new(path, 'is a portable recipe (.recipe.yml): give it to recipes_paths, which reads it as data only')
180
- end
181
-
182
- text = read_text(path, full_path)
183
- if erb
184
- text = ERB.new(text).result
185
- elsif text.include?('<%')
186
- raise RecipeFileError.new(path, 'contains ERB: run again with --erb to evaluate it ' \
187
- '(this executes the code in the file)')
188
- end
189
- data = begin
190
- YAML.safe_load(text, permitted_classes: [Symbol], aliases: true)
191
- rescue Psych::Exception => e
192
- raise RecipeFileError.new(path, "invalid YAML: #{e.message}")
193
- end
194
- raise RecipeFileError.new(path, 'file is empty') if data.nil?
195
- raise RecipeFileError.new(path, 'must contain a mapping of api names') unless data.is_a?(Hash)
196
-
197
- Internals::Compiler.normalize(data, :options_map)
198
- end
199
-
200
- # @private
201
- def read_text(path, full_path)
202
- text = File.read(full_path, encoding: 'UTF-8')
203
- raise RecipeFileError.new(path, 'file is not valid UTF-8') unless text.valid_encoding?
204
-
205
- text
206
- rescue Errno::ENOENT
207
- raise RecipeFileError.new(path, 'file not found')
208
- rescue SystemCallError => e
209
- raise RecipeFileError.new(path, "cannot read file (#{e.class.name.split('::').last})")
210
- end
211
-
212
- # @private
213
- def shared_recipe?(full_path)
214
- names = [full_path]
215
- names << File.realpath(full_path) if File.exist?(full_path)
216
- names.any? { |name| name.downcase.end_with?('.recipe.yml') }
217
- end
218
-
219
141
  # @private
220
142
  # A copy of value whose Hashes, Arrays and unfrozen Strings are new
221
143
  # objects; any other object is the same. A Hash or Array met twice, or
@@ -81,7 +81,7 @@ module ApiRecipes
81
81
  attr_reader :definition
82
82
 
83
83
  def inspect
84
- "#<ApiRecipes::Endpoint #{@definition.full_name} #{@definition.verb.to_s.upcase} " \
84
+ "#<ApiRecipes::Endpoint #{@definition.full_name} #{@context.shown_verb(@definition.verb)} " \
85
85
  "#{@context.shown_origin}#{@path}>"
86
86
  end
87
87