api_recipes 3.0.0.beta2 → 3.0.0.beta3

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.
@@ -0,0 +1,287 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'fileutils'
4
+ require 'api_recipes/cli/recipes/summary'
5
+ require 'api_recipes/cli/recipes/git'
6
+ require 'api_recipes/cli/recipes/lock_file'
7
+
8
+ module ApiRecipes
9
+ module CLI
10
+ # The commands for portable recipes: check, install and update.
11
+ class Recipes
12
+ DEFAULT_DIRECTORY = 'config/api_recipes'
13
+ DEFAULT_SOURCE = 'https://github.com/madAle/api_recipes-cookbook'
14
+ Recipe = Internals::Recipe
15
+ RecipeLock = Internals::RecipeLock
16
+
17
+ # A recipe about to be installed: where it comes from, for the lock
18
+ # (source and commit, nil for a file) and for the reader (origin).
19
+ Incoming = Data.define(:recipe, :source, :commit, :origin)
20
+
21
+ # The command ends here, with this exit code and this message.
22
+ class Stop < StandardError
23
+ attr_reader :code
24
+
25
+ def initialize(code, message)
26
+ @code = code
27
+ super(message)
28
+ end
29
+ end
30
+
31
+ def initialize(out:, err:, input: nil)
32
+ @out = out
33
+ @err = err
34
+ @input = input
35
+ end
36
+
37
+ # Validates each file as a portable recipe. Without files, compares the
38
+ # recipes of directory with its recipes.lock, as configure does. Returns
39
+ # the exit code: 2 if something could not be read, else 1 if something is
40
+ # not valid or does not match, else 0.
41
+ def check(files, directory: DEFAULT_DIRECTORY)
42
+ return check_directory(directory) if files.empty?
43
+
44
+ files.map { |file| check_file(file) }.max
45
+ end
46
+
47
+ # Installs the recipe called target from the repository at from, at
48
+ # version or at the head; or the file at target, when target is not the
49
+ # name of a recipe. Shows what the recipe does and asks before writing
50
+ # in directory. Returns the exit code: 1 if the recipe is not acceptable,
51
+ # is not found or the answer is no, 2 if the arguments are wrong or
52
+ # something could not be read or written, else 0.
53
+ def install(target, version: nil, from: nil, directory: DEFAULT_DIRECTORY, yes: false)
54
+ guarded do
55
+ incoming = Recipe::NAME.match?(target) ? fetched(target, version, from || DEFAULT_SOURCE, '--from') : local(target, version, from)
56
+ place(incoming, directory, yes, 'Install')
57
+ end
58
+ end
59
+
60
+ # Replaces an installed recipe with the one its repository has now, or
61
+ # has at version, after showing what changes. Same exit codes as install.
62
+ def update(name, version: nil, directory: DEFAULT_DIRECTORY, yes: false)
63
+ guarded do
64
+ raise Stop.new(2, "#{Summary.shown(name, 80)} is not the name of a recipe") unless Recipe::NAME.match?(name)
65
+
66
+ readable!(File.join(directory, RecipeLock::FILE_NAME))
67
+ entry = RecipeLock.read(directory)[name]
68
+ raise Stop.new(1, "#{name} is not installed in #{directory}") if entry.nil?
69
+ if entry.source.nil?
70
+ raise Stop.new(1, "#{name} was installed from a file: install the new file with `api_recipes install FILE`")
71
+ end
72
+
73
+ place(fetched(name, version, entry.source, "#{File.join(directory, RecipeLock::FILE_NAME)}: the source of #{name}"),
74
+ directory, yes, 'Update')
75
+ end
76
+ end
77
+
78
+ private
79
+
80
+ def guarded
81
+ yield
82
+ rescue Stop => e
83
+ @err.puts e.message
84
+ e.code
85
+ rescue ConfigurationError => e
86
+ e.errors.each { |problem| @err.puts problem }
87
+ 1
88
+ rescue Git::NotFound => e
89
+ @err.puts e.message
90
+ 1
91
+ rescue Git::Failure => e
92
+ @err.puts e.message
93
+ 2
94
+ rescue SystemCallError => e
95
+ @err.puts "could not write (#{e.class.name.split('::').last}): check the folder and its recipes.lock"
96
+ 2
97
+ end
98
+
99
+ def fetched(name, version, address, what)
100
+ problem = Git.address_problem(address)
101
+ raise Stop.new(2, "#{what} #{problem}") if problem
102
+ unless version.nil? || (version.length <= Recipe::MAX_VERSION && Recipe::VERSION.match?(version))
103
+ raise Stop.new(2, '--version must be made of digits, letters and dots')
104
+ end
105
+
106
+ # Said before git connects: the address may come from the lock, and
107
+ # git or ssh may ask something on the terminal for it.
108
+ @out.puts "reading #{name} from #{address}"
109
+ @out.flush if @out.respond_to?(:flush)
110
+ found = Git.new(address, ask: terminal?).fetch(name, version)
111
+ recipe = Recipe.parse(found.text, "#{name} in #{address}", file_name: "#{name}#{Recipe::SUFFIX}")
112
+ if version && recipe.version != version
113
+ raise Stop.new(1, "the tag #{name}-#{version} of #{address} holds version #{recipe.version}: nothing was written")
114
+ end
115
+
116
+ Incoming.new(recipe: recipe, source: address, commit: found.commit, origin: "#{address}, commit #{found.commit[0, 12]}")
117
+ end
118
+
119
+ # Whether someone is there to answer: the input of the command is a terminal.
120
+ def terminal? = @input.respond_to?(:tty?) && @input.tty? ? true : false
121
+
122
+ def local(path, version, from)
123
+ raise Stop.new(2, '--from and --version go with the name of a recipe, not with a file') if version || from
124
+ unless File.file?(path) && File.readable?(path)
125
+ shown = Summary.shown(path)
126
+ raise Stop.new(2, "#{shown}: #{File.file?(path) ? 'cannot be read' : (File.exist?(path) ? 'is not a file' : 'no such file')}")
127
+ end
128
+
129
+ Incoming.new(recipe: Recipe.read(path), source: nil, commit: nil, origin: "the file #{Summary.shown(path)}")
130
+ end
131
+
132
+ # Shows the recipe, asks, then writes its file and the lock of directory.
133
+ def place(incoming, directory, yes, action)
134
+ recipe = incoming.recipe
135
+ destination = File.join(directory, "#{recipe.name}#{Recipe::SUFFIX}")
136
+ lock_path = File.join(directory, RecipeLock::FILE_NAME)
137
+ [destination, lock_path].each do |path|
138
+ raise Stop.new(2, "#{path} is a link: api_recipes does not write through links") if File.symlink?(path)
139
+ end
140
+ raise Stop.new(2, "#{directory} is not a folder") if File.exist?(directory) && !File.directory?(directory)
141
+
142
+ [destination, lock_path].each { |path| readable!(path) }
143
+ lock = RecipeLock.read(directory)
144
+ entry = RecipeLock::Entry.new(version: recipe.version, source: incoming.source, commit: incoming.commit,
145
+ sha256: recipe.sha256)
146
+ current = installed_text(destination)
147
+ summary = Summary.new(recipe, origin: incoming.origin)
148
+ if current == recipe.text && lock[recipe.name] == entry
149
+ @out.puts "#{summary.title} is already installed in #{directory}: nothing to do"
150
+ return 0
151
+ end
152
+
153
+ show(summary, destination, current, lock[recipe.name])
154
+ confirm("#{action} #{summary.title} in #{directory}?") unless yes
155
+ FileUtils.mkdir_p(directory)
156
+ write(destination, recipe.text) unless current == recipe.text
157
+ write(lock_path, LockFile.text(lock.entries.merge(recipe.name => entry)))
158
+ @out.puts "#{recipe.name} #{recipe.version} is installed in #{destination}"
159
+ 0
160
+ end
161
+
162
+ def installed_text(destination)
163
+ return nil unless File.exist?(destination)
164
+ raise Stop.new(2, "#{destination} is not a file") unless File.file?(destination)
165
+
166
+ Recipe.read_text(destination).first
167
+ end
168
+
169
+ def show(summary, destination, current, entry)
170
+ summary.lines.each { |line| @out.puts line }
171
+ summary.warnings.each { |warning| @out.puts " warning: #{warning}" }
172
+ return if current.nil? || current == summary.text
173
+
174
+ if entry && entry.sha256 != Recipe.digest(current)
175
+ @out.puts " #{destination} was changed after it was installed: those changes will be lost"
176
+ end
177
+ summary.changes_from(installed_summary(current, destination)).each { |line| @out.puts line }
178
+ end
179
+
180
+ # The summary of the recipe that is installed now; nil when it is not a
181
+ # valid recipe.
182
+ def installed_summary(text, destination)
183
+ Summary.new(Recipe.parse(text, destination))
184
+ rescue ConfigurationError
185
+ nil
186
+ end
187
+
188
+ def confirm(question)
189
+ @out.print "#{question} [y/N] "
190
+ @out.flush if @out.respond_to?(:flush)
191
+ answer = @input&.gets.to_s.strip.downcase
192
+ raise Stop.new(1, 'nothing was written') unless %w[y yes].include?(answer)
193
+ end
194
+
195
+ # The new content takes the place of the file in one step. The bytes are
196
+ # written as they are, on every system: the checksum is of the bytes.
197
+ def write(path, text)
198
+ temporary = "#{path}.#{Process.pid}.tmp"
199
+ file = File.open(temporary, File::WRONLY | File::CREAT | File::EXCL | File::BINARY, 0o644)
200
+ begin
201
+ file.write(text)
202
+ file.close
203
+ File.rename(temporary, path)
204
+ ensure
205
+ file.close unless file.closed?
206
+ File.delete(temporary) if File.exist?(temporary)
207
+ end
208
+ end
209
+
210
+ # A file that is there and cannot be read stops the command with 2.
211
+ def readable!(path)
212
+ raise Stop.new(2, "#{path}: cannot be read") if File.exist?(path) && !File.readable?(path)
213
+ end
214
+
215
+ def check_file(file)
216
+ unless File.file?(file) && File.readable?(file)
217
+ @err.puts "#{file}: #{File.file?(file) ? 'cannot be read' : (File.exist?(file) ? 'is not a file' : 'no such file')}"
218
+ return 2
219
+ end
220
+
221
+ describe(file, Recipe.read(file))
222
+ 0
223
+ rescue ConfigurationError => e
224
+ e.errors.each { |problem| @err.puts problem }
225
+ 1
226
+ end
227
+
228
+ def describe(file, recipe)
229
+ summary = Summary.new(recipe)
230
+ calls = recipe.definition.routes.size
231
+ @out.puts "#{file}: #{summary.title}, #{calls} call#{'s' unless calls == 1}"
232
+ summary.warnings.each { |warning| @err.puts "#{file}: warning: #{warning}" }
233
+ end
234
+
235
+ def check_directory(directory)
236
+ unless File.directory?(directory)
237
+ @err.puts "#{directory}: no such folder"
238
+ return 2
239
+ end
240
+
241
+ readable!(File.join(directory, RecipeLock::FILE_NAME))
242
+ lock = RecipeLock.read(directory)
243
+ names = Dir.children(directory).select { |name| name.end_with?(Recipe::SUFFIX) }.sort
244
+ codes = names.map { |name| check_installed(File.join(directory, name), name.delete_suffix(Recipe::SUFFIX), lock) }
245
+ (lock.entries.keys - names.map { |name| name.delete_suffix(Recipe::SUFFIX) }).sort.each do |name|
246
+ @err.puts "#{lock.path}: #{name} is in the lock, but #{File.join(directory, "#{name}#{Recipe::SUFFIX}")} is missing"
247
+ codes << 1
248
+ end
249
+ @out.puts "no recipes in #{directory}" if codes.empty?
250
+ codes.max || 0
251
+ rescue Stop => e
252
+ @err.puts e.message
253
+ e.code
254
+ rescue ConfigurationError => e
255
+ e.errors.each { |problem| @err.puts problem }
256
+ 1
257
+ rescue SystemCallError => e
258
+ @err.puts "#{directory}: cannot be read (#{e.class.name.split('::').last})"
259
+ 2
260
+ end
261
+
262
+ def check_installed(file, name, lock)
263
+ unless File.readable?(file)
264
+ @err.puts "#{file}: cannot be read"
265
+ return 2
266
+ end
267
+
268
+ text, = Recipe.read_text(file)
269
+ problem = lock.problem_for(name, Recipe.digest(text))
270
+ if problem
271
+ @err.puts "#{file}: #{problem} `api_recipes install #{file}`"
272
+ return 1
273
+ end
274
+
275
+ recipe = Recipe.parse(text, file, file_name: File.basename(file))
276
+ describe(file, recipe)
277
+ return 0 if lock[name].version == recipe.version
278
+
279
+ @err.puts "#{lock.path}: #{name} is version #{lock[name].version} in the lock, but the file says #{recipe.version}"
280
+ 1
281
+ rescue ConfigurationError => e
282
+ e.errors.each { |one| @err.puts one }
283
+ 1
284
+ end
285
+ end
286
+ end
287
+ end
@@ -3,7 +3,8 @@
3
3
  module ApiRecipes
4
4
  module CLI
5
5
  # The routes command: the calls that the recipes in some files offer, one
6
- # per line, with the verb and the address.
6
+ # per line, with the verb and the address. A file called NAME.recipe.yml is
7
+ # a portable recipe, read as data only.
7
8
  class Routes
8
9
  def initialize(files, erb: false)
9
10
  @files = Array(files)
@@ -30,7 +31,11 @@ module ApiRecipes
30
31
  return 2
31
32
  end
32
33
 
33
- apis = Configuration.new.read_recipe_file(file, erb: @erb)
34
+ apis = if file.end_with?(Internals::Recipe::SUFFIX)
35
+ Internals::Recipe.read(file, compile: false).apis
36
+ else
37
+ Configuration.new.read_recipe_file(file, erb: @erb)
38
+ end
34
39
  Internals::Compiler.compile_all(apis).each_value do |api|
35
40
  api.routes.each { |route| rows << [route.call, route.verb.to_s.upcase, route.url] }
36
41
  end
@@ -25,6 +25,12 @@ module ApiRecipes
25
25
  Rule.new(:breaks, /ApiRecipes\.print_urls/, 'use config.print_urls inside ApiRecipes.configure'),
26
26
  Rule.new(:breaks, /_aprcps_|set_authorization_for_api|set_basic_auth_for_api|copy_global_authorizations_to_api/,
27
27
  'internal method removed'),
28
+ Rule.new(:breaks, /\bApiRecipes((\.|::)\w+|\[[^\]]*\])\.(authorization|basic_auth)\s*(\|\|)?=(?![=~])/,
29
+ 'a credential of the whole application is given to ApiRecipes.configure, as ' \
30
+ 'config.values = { name: { authorization: ... } }: this writer now raises'),
31
+ Rule.new(:check, /(?<!\bApiRecipes)\.\w+\.(authorization|basic_auth)\s*(\|\|)?=(?![=~])/,
32
+ 'authorization= and basic_auth= now work on an object only: on a class they raise, ' \
33
+ 'give the credential to `api :name, authorization: ...`, or to with(...) for one request'),
28
34
  Rule.new(:check, /url_encode|CGI\.escape|encode_www_form_component/,
29
35
  'path parameters are now encoded by ApiRecipes: remove manual encoding of values passed to endpoints'),
30
36
  Rule.new(:check, /\brescue\s*(=>.*)?$|rescue StandardError/,
@@ -43,11 +49,12 @@ module ApiRecipes
43
49
  'a / inside a path parameter to cover several segments: use *name or two placeholders',
44
50
  'debug logs or print_urls output read from STDOUT: set log_to and log_level',
45
51
  'a bare rescue around a call: it now catches the errors of the gem too',
46
- 'credentials assigned on a class or an instance: they now take effect',
52
+ 'credentials assigned on an instance: they now take effect',
53
+ 'a credential assigned through a variable that holds the api of the module or of a class (api = ApiRecipes.github, then api.authorization = ...), inside the body of a class (github.authorization = ...), with send, or on a statement split over two lines: the writer raises, give it to config.values or to `api :name, authorization: ...`',
47
54
  'the response body read from the message of a verify_with error: read it from error.response',
48
55
  'a block passed to run whose return value is used: it is now the Response',
49
56
  'apis_configs assigned after the files to discard them: do not assign the files',
50
- 'a nested endpoint without options under a parent with verify_with: it now inherits the verification',
57
+ 'timeout, on_bad_code, mime_type or verify_with on an endpoint that contains other endpoints: one that does not set the option now finds it there, before the api',
51
58
  'an endpoint called with, definition, authorization, basic_auth or variables (on an api), or run, url, with or definition (on an endpoint): reach it with []; the warning at configuration reports it',
52
59
  'fill with private setters, or code that relies on swallowed errors: make the setters public, handle the errors',
53
60
  'follow: true together with a credential: the credential no longer follows to another host',
@@ -63,6 +70,7 @@ module ApiRecipes
63
70
  'response.to_s returns the body, as the http.rb response does: it was the default text of the object',
64
71
  'a credential that is not a String, such as a Symbol or a number: it raises InvalidCredential, convert it with to_s',
65
72
  'a {word} in a value of default_headers in a configuration given as a Hash: it is now a variable and must be declared',
73
+ 'a {word} in the path of an endpoint in a configuration given as a Hash: it is now a variable and must be declared; to keep the braces as text write \\{word}',
66
74
  'respond_to? on a response now tells the truth: it answers true for the methods the response forwards and false for the others',
67
75
  'serializing an Api, an Endpoint or a Response raises TypeError: serialize response.data or response.body.to_s',
68
76
  'a class that includes ApiRecipes and uses a top-level constant named Error, Internals, VERSION or like a new error class of the gem (such as ConfigurationError or InvalidUrl): it now finds the gem\'s constant first, write ::Name in that class; Route and Settings no longer exist, so a top-level Route or Settings is found again'
@@ -6,6 +6,7 @@ require 'api_recipes/version'
6
6
  require 'api_recipes/cli/upgrade'
7
7
  require 'api_recipes/cli/import'
8
8
  require 'api_recipes/cli/routes'
9
+ require 'api_recipes/cli/recipes'
9
10
 
10
11
  module ApiRecipes
11
12
  # The api_recipes command. It is not loaded by `require 'api_recipes'`.
@@ -29,7 +30,30 @@ module ApiRecipes
29
30
  routes [--erb] FILE...
30
31
  Lists the calls that the recipes in each FILE offer, with the verb and the address.
31
32
  A file that contains ERB is evaluated only with --erb: this runs the code in it.
33
+ A file called NAME.recipe.yml is read as a portable recipe: as data only.
32
34
  Exits with 1 if a file is not a valid configuration, 2 if it could not read one.
35
+ install [--version VERSION] [--from URL] [--to DIR] [--yes] NAME|FILE
36
+ Installs the portable recipe called NAME from the cookbook
37
+ (https://github.com/madAle/api_recipes-cookbook) or from the Git repository at URL,
38
+ an https:// or ssh address (ssh://HOST/PATH, USER@HOST:PATH) that holds
39
+ recipes/NAME.recipe.yml. On a terminal git may ask for the user name and the password
40
+ of an https repository. Without --version
41
+ it takes the recipe at the head of the repository, with it the one at the tag
42
+ NAME-VERSION. Given a FILE, it installs that file. It shows where the requests and
43
+ the credential go, the headers and which calls are not GET, asks, then writes NAME.recipe.yml and
44
+ recipes.lock in DIR (config/api_recipes). --yes installs without asking.
45
+ Exits with 1 if the recipe is not valid, is not found or the answer is no, 2 if the
46
+ arguments are wrong, git failed or something could not be read or written.
47
+ update [--version VERSION] [--dir DIR] [--yes] NAME
48
+ Replaces the recipe NAME installed in DIR with the one its repository has now, or
49
+ has at VERSION, after showing what changes in the address, the credential, the
50
+ headers and the verbs. Same exit codes as install.
51
+ check [--dir DIR] [FILE]...
52
+ Checks that each FILE is a valid portable recipe. Without a FILE, checks that the
53
+ recipes installed in DIR (config/api_recipes) are the ones written in its
54
+ recipes.lock, as ApiRecipes.configure does when the application starts.
55
+ Exits with 1 if something is not valid or does not match, 2 if it could not read
56
+ something.
33
57
 
34
58
  Options:
35
59
  --version print the version
@@ -38,8 +62,13 @@ module ApiRecipes
38
62
 
39
63
  class << self
40
64
  # Returns the exit code.
41
- def run(argv, out: $stdout, err: $stderr)
65
+ def run(argv, out: $stdout, err: $stderr, input: $stdin)
42
66
  command, *args = argv
67
+ unless argv.all?(&:valid_encoding?)
68
+ err.puts 'the arguments must be valid text in the encoding of the terminal'
69
+ return 2
70
+ end
71
+
43
72
  case command
44
73
  when '--version', '-v'
45
74
  out.puts ApiRecipes::VERSION
@@ -53,6 +82,10 @@ module ApiRecipes
53
82
  import(args, out, err)
54
83
  when 'routes'
55
84
  routes(args, out, err)
85
+ when 'check'
86
+ check(args, out, err)
87
+ when 'install', 'update'
88
+ place(command, args, out, err, input)
56
89
  when nil
57
90
  err.puts USAGE
58
91
  2
@@ -128,6 +161,39 @@ module ApiRecipes
128
161
  false
129
162
  end
130
163
 
164
+ def check(args, out, err)
165
+ directory = Recipes::DEFAULT_DIRECTORY
166
+ parser = OptionParser.new
167
+ parser.on('--dir DIR') { |dir| directory = dir }
168
+ files = parser.parse(args)
169
+ Recipes.new(out: out, err: err).check(files, directory: directory)
170
+ rescue OptionParser::ParseError => e
171
+ err.puts e.message
172
+ 2
173
+ end
174
+
175
+ def place(command, args, out, err, input)
176
+ options = { directory: Recipes::DEFAULT_DIRECTORY, yes: false }
177
+ parser = OptionParser.new
178
+ parser.on('--version VERSION') { |version| options[:version] = version }
179
+ parser.on('--dir DIR') { |dir| options[:directory] = dir }
180
+ parser.on('--yes') { options[:yes] = true }
181
+ if command == 'install'
182
+ parser.on('--from URL') { |url| options[:from] = url }
183
+ parser.on('--to DIR') { |dir| options[:directory] = dir }
184
+ end
185
+ targets = parser.parse(args)
186
+ unless targets.size == 1
187
+ err.puts command == 'install' ? 'install needs the name of one recipe, or one file' : 'update needs the name of one recipe'
188
+ return 2
189
+ end
190
+
191
+ Recipes.new(out: out, err: err, input: input).public_send(command, targets.first, **options)
192
+ rescue OptionParser::ParseError => e
193
+ err.puts e.message
194
+ 2
195
+ end
196
+
131
197
  def routes(args, out, err)
132
198
  erb = false
133
199
  parser = OptionParser.new
@@ -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,14 +78,34 @@ 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|
@@ -78,7 +115,7 @@ module ApiRecipes
78
115
  @apis_files_paths.each { |path| merge_file(apis, path) }
79
116
  end
80
117
  end
81
- apis
118
+ apis.merge(Internals::Recipe.load_all(@recipes_paths, taken: apis.keys))
82
119
  end
83
120
 
84
121
  # Reads one file with the rules of apis_files_paths and returns the apis as
@@ -139,7 +176,7 @@ module ApiRecipes
139
176
 
140
177
  full_path = File.expand_path(path)
141
178
  if shared_recipe?(full_path)
142
- raise RecipeFileError.new(path, 'shared recipe files (.recipe.yml) are not supported by this version')
179
+ raise RecipeFileError.new(path, 'is a portable recipe (.recipe.yml): give it to recipes_paths, which reads it as data only')
143
180
  end
144
181
 
145
182
  text = read_text(path, 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,7 +75,7 @@ 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
@@ -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