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
@@ -1,11 +1,17 @@
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'
6
8
  require 'api_recipes/cli/upgrade'
7
9
  require 'api_recipes/cli/import'
8
10
  require 'api_recipes/cli/routes'
11
+ require 'api_recipes/cli/recipes'
12
+ require 'api_recipes/cli/convert'
13
+ require 'api_recipes/cli/convert/snippet'
14
+ require 'api_recipes/cli/convert/migration'
9
15
 
10
16
  module ApiRecipes
11
17
  # The api_recipes command. It is not loaded by `require 'api_recipes'`.
@@ -14,10 +20,15 @@ module ApiRecipes
14
20
  Usage: api_recipes COMMAND [options]
15
21
 
16
22
  Commands:
17
- upgrade [--config FILE]... [--erb] [PATH]...
18
- Looks in the Ruby files under each PATH for what changed in api_recipes 3.0
19
- and checks each configuration FILE with the 3.0 rules. It never changes a file.
20
- A file that contains ERB is evaluated only with --erb: this runs the code in it.
23
+ upgrade [--config FILE]... [--erb] [--no-code] [PATH]...
24
+ Without arguments, in the root of a project: finds its Ruby files and the files
25
+ that describe an api, and looks for what changed in api_recipes 3.0. It says what
26
+ 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
28
+ is checked without running its code, leaving out what its tags give; --erb
29
+ evaluates it instead: this runs the code in it. Where what to write is known it
30
+ gives the code to paste, with the whole block of ApiRecipes.configure; --no-code
31
+ leaves the code out.
21
32
  Exits with 1 if it finds something, 2 if it could not read something, 0 otherwise.
22
33
  import [--name NAME] [--only GLOB]... [--except GLOB]... [--server N] [--output FILE] FILE
23
34
  Writes a recipe from the OpenAPI 3.0 or 3.1 description in FILE (YAML or JSON), on
@@ -29,7 +40,43 @@ module ApiRecipes
29
40
  routes [--erb] FILE...
30
41
  Lists the calls that the recipes in each FILE offer, with the verb and the address.
31
42
  A file that contains ERB is evaluated only with --erb: this runs the code in it.
43
+ A file called NAME.recipe.yml is read as a portable recipe: as data only.
32
44
  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
46
+ 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
48
+ repository starts): installs NAME.recipe.yml in config/api_recipes,
49
+ moves the code of each ERB tag to config.values in the file that calls
50
+ ApiRecipes.configure, removes the old description, and lists every file it
51
+ changed. It changes files only when git can undo it, and all at once or not at
52
+ all: when it cannot, it gives the steps and the code to paste. With --to DIR it
53
+ 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
+ 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).
56
+ Exits with 1 if FILE cannot become a recipe or the project cannot be changed
57
+ safely, 2 if the arguments are wrong or something could not be read or written.
58
+ install [--version VERSION] [--from URL] [--to DIR] [--yes] NAME|FILE
59
+ Installs the portable recipe called NAME from the cookbook
60
+ (https://github.com/madAle/api_recipes-cookbook) or from the Git repository at URL,
61
+ an https:// or ssh address (ssh://HOST/PATH, USER@HOST:PATH) that holds
62
+ recipes/NAME.recipe.yml. On a terminal git may ask for the user name and the password
63
+ of an https repository. Without --version
64
+ it takes the recipe at the head of the repository, with it the one at the tag
65
+ NAME-VERSION. Given a FILE, it installs that file. It shows where the requests and
66
+ the credential go, the headers and which calls are not GET, asks, then writes NAME.recipe.yml and
67
+ recipes.lock in DIR (config/api_recipes). --yes installs without asking.
68
+ Exits with 1 if the recipe is not valid, is not found or the answer is no, 2 if the
69
+ arguments are wrong, git failed or something could not be read or written.
70
+ update [--version VERSION] [--dir DIR] [--yes] NAME
71
+ Replaces the recipe NAME installed in DIR with the one its repository has now, or
72
+ has at VERSION, after showing what changes in the address, the credential, the
73
+ headers and the verbs. Same exit codes as install.
74
+ check [--dir DIR] [FILE]...
75
+ Checks that each FILE is a valid portable recipe. Without a FILE, checks that the
76
+ recipes installed in DIR (config/api_recipes) are the ones written in its
77
+ recipes.lock, as ApiRecipes.configure does when the application starts.
78
+ Exits with 1 if something is not valid or does not match, 2 if it could not read
79
+ something.
33
80
 
34
81
  Options:
35
82
  --version print the version
@@ -38,8 +85,13 @@ module ApiRecipes
38
85
 
39
86
  class << self
40
87
  # Returns the exit code.
41
- def run(argv, out: $stdout, err: $stderr)
88
+ def run(argv, out: $stdout, err: $stderr, input: $stdin)
42
89
  command, *args = argv
90
+ unless argv.all?(&:valid_encoding?)
91
+ err.puts 'the arguments must be valid text in the encoding of the terminal'
92
+ return 2
93
+ end
94
+
43
95
  case command
44
96
  when '--version', '-v'
45
97
  out.puts ApiRecipes::VERSION
@@ -53,6 +105,12 @@ module ApiRecipes
53
105
  import(args, out, err)
54
106
  when 'routes'
55
107
  routes(args, out, err)
108
+ when 'convert'
109
+ convert(args, out, err)
110
+ when 'check'
111
+ check(args, out, err)
112
+ when 'install', 'update'
113
+ place(command, args, out, err, input)
56
114
  when nil
57
115
  err.puts USAGE
58
116
  2
@@ -128,6 +186,96 @@ module ApiRecipes
128
186
  false
129
187
  end
130
188
 
189
+ def convert(args, out, err)
190
+ options = {}
191
+ directory = nil
192
+ parser = OptionParser.new
193
+ parser.on('--name NAME') { |name| options[:name] = name }
194
+ parser.on('--version VERSION') { |version| options[:version] = version }
195
+ parser.on('--to DIR') { |dir| directory = dir }
196
+ files = parser.parse(args)
197
+ unless files.size == 1
198
+ err.puts 'convert needs one configuration file'
199
+ return 2
200
+ end
201
+
202
+ result = Convert.new(files.first, **options).call
203
+ # In the root of a project, and told no folder, the project is moved to the recipe.
204
+ return Convert::Migration.new(result, files.first, out: out, err: err).call if directory.nil? && project_root?
205
+
206
+ directory ||= '.'
207
+ file_name = "#{result.name}#{Internals::Recipe::SUFFIX}"
208
+ path = directory == '.' ? file_name : File.join(directory, file_name)
209
+ return 2 unless place_recipe(result.text, directory, path, err)
210
+
211
+ Convert.report(result, files.first, path, out)
212
+ 0
213
+ rescue Convert::Refused => e
214
+ e.reasons.each { |reason| err.puts reason }
215
+ 1
216
+ rescue Convert::Unusable, OptionParser::ParseError => e
217
+ err.puts e.message
218
+ 2
219
+ rescue SystemStackError
220
+ err.puts 'the file is nested too deeply to be read'
221
+ 1
222
+ rescue StandardError => e
223
+ # What the command did not foresee is answered with one line, never
224
+ # with the text of an exception, which could hold a value of the file.
225
+ err.puts "convert failed (#{e.class}): this is a defect of api_recipes, not of the file"
226
+ 1
227
+ end
228
+
229
+ # The current directory is the root of a project: it has a Gemfile, or
230
+ # it is where a git repository starts.
231
+ def project_root? = File.file?('Gemfile') || File.exist?('.git')
232
+
233
+ # The recipe is created in its folder, never replaced.
234
+ def place_recipe(text, directory, path, err)
235
+ FileUtils.mkdir_p(directory)
236
+ File.open(path, File::WRONLY | File::CREAT | File::EXCL) { |file| file.write(text) }
237
+ true
238
+ rescue Errno::EEXIST
239
+ err.puts "#{path} already exists: remove it, or choose another folder with --to"
240
+ false
241
+ rescue SystemCallError => e
242
+ err.puts "#{path}: cannot be written (#{e.class.name.split('::').last})"
243
+ false
244
+ end
245
+
246
+ def check(args, out, err)
247
+ directory = Recipes::DEFAULT_DIRECTORY
248
+ parser = OptionParser.new
249
+ parser.on('--dir DIR') { |dir| directory = dir }
250
+ files = parser.parse(args)
251
+ Recipes.new(out: out, err: err).check(files, directory: directory)
252
+ rescue OptionParser::ParseError => e
253
+ err.puts e.message
254
+ 2
255
+ end
256
+
257
+ def place(command, args, out, err, input)
258
+ options = { directory: Recipes::DEFAULT_DIRECTORY, yes: false }
259
+ parser = OptionParser.new
260
+ parser.on('--version VERSION') { |version| options[:version] = version }
261
+ parser.on('--dir DIR') { |dir| options[:directory] = dir }
262
+ parser.on('--yes') { options[:yes] = true }
263
+ if command == 'install'
264
+ parser.on('--from URL') { |url| options[:from] = url }
265
+ parser.on('--to DIR') { |dir| options[:directory] = dir }
266
+ end
267
+ targets = parser.parse(args)
268
+ unless targets.size == 1
269
+ err.puts command == 'install' ? 'install needs the name of one recipe, or one file' : 'update needs the name of one recipe'
270
+ return 2
271
+ end
272
+
273
+ Recipes.new(out: out, err: err, input: input).public_send(command, targets.first, **options)
274
+ rescue OptionParser::ParseError => e
275
+ err.puts e.message
276
+ 2
277
+ end
278
+
131
279
  def routes(args, out, err)
132
280
  erb = false
133
281
  parser = OptionParser.new
@@ -148,15 +296,20 @@ module ApiRecipes
148
296
  configs = []
149
297
  erb = false
150
298
  parser = OptionParser.new
299
+ code = true
151
300
  parser.on('--config FILE') { |file| configs << file }
152
301
  parser.on('--erb') { erb = true }
302
+ parser.on('--no-code') { code = false }
153
303
  paths = parser.parse(args)
154
- if paths.empty? && configs.empty?
155
- err.puts 'upgrade needs a directory or a file to scan, or --config FILE'
304
+ return Upgrade.new(paths, config: configs, erb: erb, code: code).report(out, err) unless paths.empty? && configs.empty?
305
+
306
+ unless File.file?('Gemfile')
307
+ err.puts 'upgrade without arguments checks the project in the current directory, and there is no Gemfile ' \
308
+ 'here: run it in the root of the project, or name the directories and the files to check'
156
309
  return 2
157
310
  end
158
311
 
159
- Upgrade.new(paths, config: configs, erb: erb).report(out, err)
312
+ Upgrade.for_project(Upgrade::Project.new, erb: erb, code: code).report(out, err)
160
313
  rescue OptionParser::ParseError => e
161
314
  err.puts e.message
162
315
  2
@@ -10,35 +10,52 @@ module ApiRecipes
10
10
 
11
11
  attr_accessor :upgrade_warnings
12
12
  attr_reader :log_to, :log_level, :print_urls
13
- attr_reader :variables
13
+ # What values= was given inside this call of configure, as
14
+ # { api name => Internals::Level }, or nil. A level never shows or
15
+ # serializes its content. Once the configuration is in force the values
16
+ # are those of the registry, and this is nil again.
17
+ attr_reader :value_levels
14
18
 
15
19
  def initialize
16
20
  @sources = []
17
21
  @apis_configs = {}
18
22
  @apis_files_paths = []
19
- @variables = {}
23
+ @recipes_paths = []
24
+ @value_levels = nil
25
+ @draft = false
20
26
  @print_urls = false
21
27
  @upgrade_warnings = true
22
28
  end
23
29
 
24
30
  # configure works on a copy: what a setter or the caller can change in
25
31
  # place (the list of sources, and the Hashes, Arrays and Strings of
26
- # apis_configs, apis_files_paths and variables at every depth) is copied,
27
- # so the original stays as it was. The logger of the application is shared.
32
+ # apis_configs and apis_files_paths at every depth) is copied, so the
33
+ # original stays as it was. The logger of the application is shared. The
34
+ # copy is the draft that configure yields, the only one that takes values.
28
35
  def initialize_copy(source)
29
36
  super
30
37
  @default_logger = nil
31
38
  @sources = @sources.dup
32
39
  @apis_configs = deep_copy(@apis_configs)
33
40
  @apis_files_paths = deep_copy(@apis_files_paths)
34
- @variables = deep_copy(@variables)
41
+ @recipes_paths = deep_copy(@recipes_paths)
42
+ @value_levels = nil
43
+ @draft = true
44
+ end
45
+
46
+ # Called by configure when the draft becomes the configuration in force.
47
+ def close_draft
48
+ @draft = false
49
+ @value_levels = nil
50
+ self
35
51
  end
36
52
 
37
53
  # The descriptions of the apis and the variables can hold secrets (header
38
54
  # values, tenant names): only the names of the apis are shown.
39
55
  def inspect
40
56
  "#<#{self.class.name} apis_configs: #{@apis_configs.keys.inspect} " \
41
- "apis_files_paths: #{@apis_files_paths.size} print_urls: #{@print_urls.inspect}>"
57
+ "apis_files_paths: #{@apis_files_paths.size} recipes_paths: #{@recipes_paths.size} " \
58
+ "print_urls: #{@print_urls.inspect}>"
42
59
  end
43
60
 
44
61
  def to_s = inspect
@@ -52,7 +69,7 @@ module ApiRecipes
52
69
  record_source(:hash)
53
70
  end
54
71
 
55
- attr_reader :apis_configs, :apis_files_paths
72
+ attr_reader :apis_configs, :apis_files_paths, :recipes_paths
56
73
 
57
74
  def apis_files_paths=(paths = [])
58
75
  raise ArgumentError, 'apis_files_paths must be an Array' unless paths.is_a? Array
@@ -61,31 +78,54 @@ module ApiRecipes
61
78
  record_source(:files)
62
79
  end
63
80
 
64
- def variables=(variables)
65
- raise ArgumentError, 'variables must be an Hash' unless variables.is_a? Hash
81
+ # Portable recipes: files written by someone else, installed with the
82
+ # api_recipes command. They are read as data only, never with ERB, and each
83
+ # must match the recipes.lock of its folder.
84
+ def recipes_paths=(paths = [])
85
+ raise ArgumentError, 'recipes_paths must be an Array' unless paths.is_a? Array
86
+
87
+ @recipes_paths = paths
88
+ end
89
+
90
+ # The credential and the variable values of each api, for the whole
91
+ # application: { github: { authorization: '...', variables: { ... } } }.
92
+ # Each api takes authorization or basic_auth, and variables. They are
93
+ # checked and copied here, and replace those given before. It is the only
94
+ # way to give them at this level, and it works only inside the block of
95
+ # configure: see Api#authorization=.
96
+ def values=(values)
97
+ unless @draft
98
+ raise Error, 'values are given inside the block of ApiRecipes.configure, as config.values = { ... }'
99
+ end
100
+ raise ArgumentError, 'values must be an Hash' unless values.is_a? Hash
66
101
 
67
- @variables = variables
102
+ @value_levels = Internals::Registry.value_levels(values)
68
103
  end
69
104
 
70
105
  # Applies the sources in the order they were assigned and returns the
71
- # apis as { name => description }. A later source replaces whole apis.
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.
72
109
  def load
73
110
  apis = {}
74
111
  @sources.each do |kind|
75
112
  if kind == :hash
76
113
  apis.merge!(@apis_configs)
77
114
  else
78
- @apis_files_paths.each { |path| merge_file(apis, path) }
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)) }
79
119
  end
80
120
  end
81
- apis
121
+ apis.merge(Internals::Recipe.load_all(@recipes_paths, taken: apis.keys))
82
122
  end
83
123
 
84
124
  # Reads one file with the rules of apis_files_paths and returns the apis as
85
125
  # { name => description }. ERB is evaluated only with erb: true; without it a
86
126
  # file that contains ERB is refused and nothing in it is run.
87
- def read_recipe_file(path, erb: true)
88
- read_file(path, erb: erb)
127
+ def read_recipe_file(path, erb: true, &without_erb)
128
+ read_file(path, erb: erb, &without_erb)
89
129
  end
90
130
 
91
131
  def logger=(logger)
@@ -139,15 +179,18 @@ module ApiRecipes
139
179
 
140
180
  full_path = File.expand_path(path)
141
181
  if shared_recipe?(full_path)
142
- raise RecipeFileError.new(path, 'shared recipe files (.recipe.yml) are not supported by this version')
182
+ raise RecipeFileError.new(path, 'is a portable recipe (.recipe.yml): give it to recipes_paths, which reads it as data only')
143
183
  end
144
184
 
145
185
  text = read_text(path, full_path)
146
186
  if erb
147
187
  text = ERB.new(text).result
148
188
  elsif text.include?('<%')
149
- raise RecipeFileError.new(path, 'contains ERB: run again with --erb to evaluate it ' \
150
- '(this executes the code in the file)')
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)
151
194
  end
152
195
  data = begin
153
196
  YAML.safe_load(text, permitted_classes: [Symbol], aliases: true)
@@ -172,6 +215,13 @@ module ApiRecipes
172
215
  raise RecipeFileError.new(path, "cannot read file (#{e.class.name.split('::').last})")
173
216
  end
174
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
+
175
225
  # @private
176
226
  def shared_recipe?(full_path)
177
227
  names = [full_path]
@@ -14,7 +14,9 @@ module ApiRecipes
14
14
 
15
15
  # args: the path values, then optionally a Hash of options for http.rb.
16
16
  # overrides: the options given to with, for this request only.
17
- def initialize(context, definition, parent_path, args, overrides = nil)
17
+ # path: the path already built, for the copy that with returns: the
18
+ # variables of a path are read once, when the chain passes there.
19
+ def initialize(context, definition, parent_path, args, overrides = nil, path = nil)
18
20
  @context = context
19
21
  @definition = definition
20
22
  @parent_path = parent_path
@@ -26,7 +28,11 @@ module ApiRecipes
26
28
  count = @options ? args.size - 1 : args.size
27
29
  raise PathParamsMismatch.new(definition.full_path, params, args.first(count)) unless count == params.size
28
30
 
29
- own = definition.template.expand(args, endpoint: definition.full_name, &UPGRADE_WARNING)
31
+ if path
32
+ @path = path
33
+ return
34
+ end
35
+ own = definition.template.expand(args, endpoint: definition.full_name, context: context, &UPGRADE_WARNING)
30
36
  if own.empty?
31
37
  # A root endpoint with an empty path is the address of the api, which
32
38
  # ends with a slash; a nested one is the address of its parent.
@@ -69,13 +75,13 @@ module ApiRecipes
69
75
  options.each { |key, value| merged.delete(key.to_sym) if value.nil? }
70
76
  overrides = merged.freeze
71
77
  end
72
- self.class.new(@context, @definition, @parent_path, @args, overrides)
78
+ self.class.new(@context, @definition, @parent_path, @args, overrides, @path)
73
79
  end
74
80
 
75
81
  attr_reader :definition
76
82
 
77
83
  def inspect
78
- "#<ApiRecipes::Endpoint #{@definition.full_name} #{@definition.verb.to_s.upcase} " \
84
+ "#<ApiRecipes::Endpoint #{@definition.full_name} #{@context.shown_verb(@definition.verb)} " \
79
85
  "#{@context.shown_origin}#{@path}>"
80
86
  end
81
87
 
@@ -17,9 +17,10 @@ module ApiRecipes
17
17
  class RecipeFileError < ConfigurationError
18
18
  attr_reader :path
19
19
 
20
+ # reason: one reason, or several.
20
21
  def initialize(path, reason)
21
22
  @path = path
22
- super(["#{path}: #{reason}"])
23
+ super(Array(reason).map { |one| "#{path}: #{one}" })
23
24
  end
24
25
  end
25
26