api_recipes 3.0.0.beta1 → 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.
Files changed (35) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +667 -78
  3. data/UPGRADING.md +67 -22
  4. data/lib/api_recipes/api.rb +14 -10
  5. data/lib/api_recipes/cli/import/document.rb +234 -0
  6. data/lib/api_recipes/cli/import/security.rb +138 -0
  7. data/lib/api_recipes/cli/import/server.rb +166 -0
  8. data/lib/api_recipes/cli/import/tree.rb +288 -0
  9. data/lib/api_recipes/cli/import/writer.rb +127 -0
  10. data/lib/api_recipes/cli/import.rb +129 -0
  11. data/lib/api_recipes/cli/recipes/git.rb +197 -0
  12. data/lib/api_recipes/cli/recipes/lock_file.rb +34 -0
  13. data/lib/api_recipes/cli/recipes/summary.rb +226 -0
  14. data/lib/api_recipes/cli/recipes.rb +287 -0
  15. data/lib/api_recipes/cli/routes.rb +55 -0
  16. data/lib/api_recipes/cli/upgrade.rb +10 -2
  17. data/lib/api_recipes/cli.rb +163 -1
  18. data/lib/api_recipes/configuration.rb +50 -13
  19. data/lib/api_recipes/endpoint.rb +9 -3
  20. data/lib/api_recipes/errors.rb +2 -1
  21. data/lib/api_recipes/internals/compiler.rb +146 -33
  22. data/lib/api_recipes/internals/context.rb +52 -14
  23. data/lib/api_recipes/internals/declaration.rb +18 -18
  24. data/lib/api_recipes/internals/definition.rb +75 -22
  25. data/lib/api_recipes/internals/level.rb +54 -43
  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 +26 -9
  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 +7 -3
  35. metadata +15 -1
@@ -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
@@ -0,0 +1,55 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ApiRecipes
4
+ module CLI
5
+ # The routes command: the calls that the recipes in some files offer, one
6
+ # per line, with the verb and the address. A file called NAME.recipe.yml is
7
+ # a portable recipe, read as data only.
8
+ class Routes
9
+ def initialize(files, erb: false)
10
+ @files = Array(files)
11
+ @erb = erb
12
+ end
13
+
14
+ # Prints the calls on out and the problems on err. Returns the exit code:
15
+ # 2 if a file could not be read, else 1 if a file is not a valid
16
+ # configuration, else 0.
17
+ def report(out, err)
18
+ rows = []
19
+ codes = @files.map { |file| read(file, rows, err) }
20
+ widths = [0, 1].map { |column| rows.map { |row| row[column].length }.max }
21
+ rows.each { |call, verb, url| out.puts "#{call.ljust(widths[0])} #{verb.ljust(widths[1])} #{url}" }
22
+ codes.max || 0
23
+ end
24
+
25
+ private
26
+
27
+ # Adds the calls of file to rows. Returns the exit code for this file.
28
+ def read(file, rows, err)
29
+ unless File.file?(file) && File.readable?(file)
30
+ err.puts "#{file}: #{File.file?(file) ? 'cannot be read' : (File.exist?(file) ? 'is not a file' : 'no such file')}"
31
+ return 2
32
+ end
33
+
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
39
+ Internals::Compiler.compile_all(apis).each_value do |api|
40
+ api.routes.each { |route| rows << [route.call, route.verb.to_s.upcase, route.url] }
41
+ end
42
+ 0
43
+ rescue RecipeFileError => e
44
+ e.errors.each { |problem| err.puts problem }
45
+ 1
46
+ rescue ConfigurationError => e
47
+ e.errors.each { |problem| err.puts "#{file}: #{problem}" }
48
+ 1
49
+ rescue StandardError, ScriptError => e
50
+ err.puts "#{file}: could not be evaluated (#{e.class})"
51
+ 1
52
+ end
53
+ end
54
+ end
55
+ 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'
@@ -4,6 +4,9 @@ require 'optparse'
4
4
  require 'api_recipes'
5
5
  require 'api_recipes/version'
6
6
  require 'api_recipes/cli/upgrade'
7
+ require 'api_recipes/cli/import'
8
+ require 'api_recipes/cli/routes'
9
+ require 'api_recipes/cli/recipes'
7
10
 
8
11
  module ApiRecipes
9
12
  # The api_recipes command. It is not loaded by `require 'api_recipes'`.
@@ -17,6 +20,40 @@ module ApiRecipes
17
20
  and checks each configuration FILE with the 3.0 rules. It never changes a file.
18
21
  A file that contains ERB is evaluated only with --erb: this runs the code in it.
19
22
  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
24
+ Writes a recipe from the OpenAPI 3.0 or 3.1 description in FILE (YAML or JSON), on
25
+ STDOUT or in the file given with --output, which must not exist. Warnings and a
26
+ 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
28
+ other file is read and the network is not used.
29
+ Exits with 1 if the description cannot be imported, 2 if the arguments are wrong.
30
+ routes [--erb] FILE...
31
+ 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.
33
+ A file called NAME.recipe.yml is read as a portable recipe: as data only.
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.
20
57
 
21
58
  Options:
22
59
  --version print the version
@@ -25,8 +62,13 @@ module ApiRecipes
25
62
 
26
63
  class << self
27
64
  # Returns the exit code.
28
- def run(argv, out: $stdout, err: $stderr)
65
+ def run(argv, out: $stdout, err: $stderr, input: $stdin)
29
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
+
30
72
  case command
31
73
  when '--version', '-v'
32
74
  out.puts ApiRecipes::VERSION
@@ -36,6 +78,14 @@ module ApiRecipes
36
78
  0
37
79
  when 'upgrade'
38
80
  upgrade(args, out, err)
81
+ when 'import'
82
+ import(args, out, err)
83
+ when 'routes'
84
+ routes(args, out, err)
85
+ when 'check'
86
+ check(args, out, err)
87
+ when 'install', 'update'
88
+ place(command, args, out, err, input)
39
89
  when nil
40
90
  err.puts USAGE
41
91
  2
@@ -48,6 +98,118 @@ module ApiRecipes
48
98
 
49
99
  private
50
100
 
101
+ def import(args, out, err)
102
+ options = { only: [], except: [] }
103
+ output = nil
104
+ parser = OptionParser.new
105
+ parser.on('--name NAME') { |name| options[:name] = name }
106
+ parser.on('--only GLOB') { |glob| options[:only] << glob }
107
+ parser.on('--except GLOB') { |glob| options[:except] << glob }
108
+ parser.on('--server N', Integer) { |number| options[:server] = number }
109
+ parser.on('--output FILE') { |file| output = file }
110
+ paths = parser.parse(args)
111
+ problem = import_problem(paths, output, options[:name])
112
+ if problem
113
+ err.puts problem
114
+ return 2
115
+ end
116
+
117
+ result = Import.new(paths.first, **options).call
118
+ return 2 unless write_recipe(result.text, output, out, err)
119
+
120
+ result.warnings.each { |warning| err.puts "warning: #{warning}" }
121
+ err.puts result.summary
122
+ 0
123
+ rescue Import::Error => e
124
+ err.puts e.message
125
+ 1
126
+ rescue OptionParser::ParseError => e
127
+ err.puts e.message
128
+ 2
129
+ rescue StandardError => e
130
+ # The description is someone else's: what the importer did not foresee
131
+ # is answered with one line, never with the text of an exception.
132
+ err.puts "import failed (#{e.class}): this is a defect of api_recipes, not of the description"
133
+ 1
134
+ end
135
+
136
+ def import_problem(paths, output, name)
137
+ return 'import needs one OpenAPI file' unless paths.size == 1
138
+ unless name.nil? || Internals::Compiler::METHOD_NAME.match?(name)
139
+ return '--name: must be the name of a method: letters, digits and _, not starting with a digit'
140
+ end
141
+ return "#{paths.first}: no such file" unless File.exist?(paths.first)
142
+ return "#{paths.first}: is not a file that can be read" unless File.file?(paths.first) && File.readable?(paths.first)
143
+ return "#{output} already exists: remove it or choose another name" if output && File.exist?(output)
144
+
145
+ nil
146
+ end
147
+
148
+ # The file of --output is created, never replaced.
149
+ def write_recipe(text, output, out, err)
150
+ if output
151
+ File.open(output, File::WRONLY | File::CREAT | File::EXCL) { |file| file.write(text) }
152
+ else
153
+ out.write(text)
154
+ end
155
+ true
156
+ rescue Errno::EPIPE
157
+ # The reader of STDOUT went away, as in `api_recipes import ... | head`.
158
+ true
159
+ rescue SystemCallError => e
160
+ err.puts "#{output || 'the recipe'}: cannot be written (#{e.class.name.split('::').last})"
161
+ false
162
+ end
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
+
197
+ def routes(args, out, err)
198
+ erb = false
199
+ parser = OptionParser.new
200
+ parser.on('--erb') { erb = true }
201
+ files = parser.parse(args)
202
+ if files.empty?
203
+ err.puts 'routes needs at least one configuration file'
204
+ return 2
205
+ end
206
+
207
+ Routes.new(files, erb: erb).report(out, err)
208
+ rescue OptionParser::ParseError => e
209
+ err.puts e.message
210
+ 2
211
+ end
212
+
51
213
  def upgrade(args, out, err)
52
214
  configs = []
53
215
  erb = false