api_recipes 3.0.0.beta1 → 3.0.0.beta2

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,129 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'date'
4
+
5
+ module ApiRecipes
6
+ module CLI
7
+ # The import command: writes a recipe from an OpenAPI description. The
8
+ # description is read once, from one local file, and nothing in it is run.
9
+ class Import
10
+ # The description cannot be imported. The message says where and why.
11
+ class Error < ApiRecipes::Error; end
12
+
13
+ Result = Data.define(:text, :warnings, :summary)
14
+ MAX_WARNINGS = 100
15
+
16
+ def initialize(path, name: nil, only: [], except: [], server: 0)
17
+ @path = path
18
+ @name = name
19
+ @only = only
20
+ @except = except
21
+ @server = server
22
+ end
23
+
24
+ # Reads the description and returns the text of the recipe with the
25
+ # warnings and the summary. Raises Error when it cannot be imported:
26
+ # nothing is returned unless the text is a recipe the gem accepts.
27
+ def call
28
+ document = Document.load(@path)
29
+ name, warnings = api_name(document)
30
+ server = Server.read(document, @server)
31
+ security = Security.read(document)
32
+ tree = Tree.build(document, only: @only, except: @except)
33
+ options = server.options.dup
34
+ options[:auth] = security.auth if security.auth
35
+ header = "Generated by api_recipes import from #{document.title} #{document.version}"
36
+ text = Writer.new(name: name, options: options, nodes: tree.nodes, header: header).to_yaml
37
+ verify(text)
38
+ warnings += server.warnings + security.warnings + tree.warnings
39
+ warnings << 'no operation was imported' if tree.operations.zero?
40
+ Result.new(text: text, warnings: shown_warnings(warnings), summary: summary(tree, warnings.size))
41
+ end
42
+
43
+ private
44
+
45
+ # [name, warnings]. The name given with --name, or the title of the
46
+ # description in lower case with underscores, or "api".
47
+ def api_name(document)
48
+ name = @name
49
+ if name.nil?
50
+ name = Import.one_line(document.title).downcase.gsub(/[^a-z0-9]+/, '_').gsub(/\A_+|_+\z/, '')
51
+ name = 'api' if name.empty?
52
+ name = "api_#{name}" if name.match?(/\A\d/)
53
+ end
54
+ unless name.is_a?(String) && Internals::Compiler::METHOD_NAME.match?(name)
55
+ raise Error, '--name: must be the name of a method: letters, digits and _, not starting with a digit'
56
+ end
57
+
58
+ warnings = []
59
+ if Internals::Handles.taken?(ApiRecipes.singleton_class, name.to_sym)
60
+ warnings << "#{Import.shown(name)} is the name of a method of ApiRecipes: reach the api with ApiRecipes[:#{name}]"
61
+ end
62
+ [name, warnings]
63
+ end
64
+
65
+ # A description can be made to produce any number of warnings.
66
+ def shown_warnings(warnings)
67
+ return warnings if warnings.size <= MAX_WARNINGS
68
+
69
+ warnings.first(MAX_WARNINGS) + ["#{warnings.size - MAX_WARNINGS} more warnings were not shown"]
70
+ end
71
+
72
+ # The text must be a recipe that the gem compiles.
73
+ def verify(text)
74
+ apis = Internals::Compiler.normalize(YAML.safe_load(text), :options_map)
75
+ Internals::Compiler.compile_all(apis)
76
+ rescue ConfigurationError => e
77
+ raise Error, "the recipe would not be valid, so nothing was written:\n#{e.errors.map { |problem| " #{problem}" }.join("\n")}"
78
+ end
79
+
80
+ def summary(tree, warnings)
81
+ text = "#{count(tree.operations, 'operation')} imported from #{count(tree.paths, 'path')}"
82
+ text += ", #{tree.skipped} left out by the filters" if tree.skipped.positive?
83
+ text += ", #{count(warnings, 'warning')}" if warnings.positive?
84
+ text
85
+ end
86
+
87
+ def count(number, word) = "#{number} #{word}#{'s' unless number == 1}"
88
+
89
+ # The text of a plain value of the description, or nil for a mapping or
90
+ # a list. Mappings and lists are never turned into text: with YAML
91
+ # aliases a small file can describe a structure too large to print.
92
+ # Every value read from a description goes through this method, shown or
93
+ # one_line, never through to_s or an interpolation.
94
+ def self.text(value)
95
+ case value
96
+ when String then value
97
+ when Symbol, Numeric, true, false, Date, Time then value.to_s
98
+ end
99
+ end
100
+
101
+ # A value of the description as it is shown in a message: one line of
102
+ # printable characters, cut to a length that keeps the message readable.
103
+ def self.shown(value)
104
+ text = self.text(value)
105
+ return value.nil? ? 'nothing' : "a #{value.is_a?(Hash) ? 'mapping' : 'list'}" if text.nil?
106
+
107
+ text = text.scrub('?').gsub(/[^[:print:]]/, '?')
108
+ "'#{text.length > 80 ? "#{text[0, 80]}..." : text}'"
109
+ end
110
+
111
+ # Free text of the description (a title, a description, an operationId)
112
+ # as it may appear in the recipe: one line, without control characters
113
+ # and without the ERB delimiters, which a recipe file would evaluate.
114
+ # Every kind of space and of line separator becomes one space, and so do
115
+ # the characters that are not shown or that change the direction of text.
116
+ def self.one_line(value, limit = 200)
117
+ text = self.text(value).to_s.scrub('?').gsub(/[[:cntrl:][:space:]\p{Cf}\p{Zl}\p{Zp}]+/, ' ')
118
+ text = text.gsub(/<%|%>/, '') while text.match?(/<%|%>/)
119
+ text.strip[0, limit]
120
+ end
121
+ end
122
+ end
123
+ end
124
+
125
+ require 'api_recipes/cli/import/document'
126
+ require 'api_recipes/cli/import/server'
127
+ require 'api_recipes/cli/import/security'
128
+ require 'api_recipes/cli/import/tree'
129
+ require 'api_recipes/cli/import/writer'
@@ -0,0 +1,50 @@
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.
7
+ class Routes
8
+ def initialize(files, erb: false)
9
+ @files = Array(files)
10
+ @erb = erb
11
+ end
12
+
13
+ # Prints the calls on out and the problems on err. Returns the exit code:
14
+ # 2 if a file could not be read, else 1 if a file is not a valid
15
+ # configuration, else 0.
16
+ def report(out, err)
17
+ rows = []
18
+ codes = @files.map { |file| read(file, rows, err) }
19
+ widths = [0, 1].map { |column| rows.map { |row| row[column].length }.max }
20
+ rows.each { |call, verb, url| out.puts "#{call.ljust(widths[0])} #{verb.ljust(widths[1])} #{url}" }
21
+ codes.max || 0
22
+ end
23
+
24
+ private
25
+
26
+ # Adds the calls of file to rows. Returns the exit code for this file.
27
+ def read(file, rows, err)
28
+ unless File.file?(file) && File.readable?(file)
29
+ err.puts "#{file}: #{File.file?(file) ? 'cannot be read' : (File.exist?(file) ? 'is not a file' : 'no such file')}"
30
+ return 2
31
+ end
32
+
33
+ apis = Configuration.new.read_recipe_file(file, erb: @erb)
34
+ Internals::Compiler.compile_all(apis).each_value do |api|
35
+ api.routes.each { |route| rows << [route.call, route.verb.to_s.upcase, route.url] }
36
+ end
37
+ 0
38
+ rescue RecipeFileError => e
39
+ e.errors.each { |problem| err.puts problem }
40
+ 1
41
+ rescue ConfigurationError => e
42
+ e.errors.each { |problem| err.puts "#{file}: #{problem}" }
43
+ 1
44
+ rescue StandardError, ScriptError => e
45
+ err.puts "#{file}: could not be evaluated (#{e.class})"
46
+ 1
47
+ end
48
+ end
49
+ end
50
+ end
@@ -4,6 +4,8 @@ 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'
7
9
 
8
10
  module ApiRecipes
9
11
  # The api_recipes command. It is not loaded by `require 'api_recipes'`.
@@ -17,6 +19,17 @@ module ApiRecipes
17
19
  and checks each configuration FILE with the 3.0 rules. It never changes a file.
18
20
  A file that contains ERB is evaluated only with --erb: this runs the code in it.
19
21
  Exits with 1 if it finds something, 2 if it could not read something, 0 otherwise.
22
+ import [--name NAME] [--only GLOB]... [--except GLOB]... [--server N] [--output FILE] FILE
23
+ Writes a recipe from the OpenAPI 3.0 or 3.1 description in FILE (YAML or JSON), on
24
+ STDOUT or in the file given with --output, which must not exist. Warnings and a
25
+ summary go to STDERR. --only and --except choose the paths: * also crosses slashes.
26
+ --server chooses the entry of servers, counted from 0. Nothing in FILE is run, no
27
+ other file is read and the network is not used.
28
+ Exits with 1 if the description cannot be imported, 2 if the arguments are wrong.
29
+ routes [--erb] FILE...
30
+ Lists the calls that the recipes in each FILE offer, with the verb and the address.
31
+ A file that contains ERB is evaluated only with --erb: this runs the code in it.
32
+ Exits with 1 if a file is not a valid configuration, 2 if it could not read one.
20
33
 
21
34
  Options:
22
35
  --version print the version
@@ -36,6 +49,10 @@ module ApiRecipes
36
49
  0
37
50
  when 'upgrade'
38
51
  upgrade(args, out, err)
52
+ when 'import'
53
+ import(args, out, err)
54
+ when 'routes'
55
+ routes(args, out, err)
39
56
  when nil
40
57
  err.puts USAGE
41
58
  2
@@ -48,6 +65,85 @@ module ApiRecipes
48
65
 
49
66
  private
50
67
 
68
+ def import(args, out, err)
69
+ options = { only: [], except: [] }
70
+ output = nil
71
+ parser = OptionParser.new
72
+ parser.on('--name NAME') { |name| options[:name] = name }
73
+ parser.on('--only GLOB') { |glob| options[:only] << glob }
74
+ parser.on('--except GLOB') { |glob| options[:except] << glob }
75
+ parser.on('--server N', Integer) { |number| options[:server] = number }
76
+ parser.on('--output FILE') { |file| output = file }
77
+ paths = parser.parse(args)
78
+ problem = import_problem(paths, output, options[:name])
79
+ if problem
80
+ err.puts problem
81
+ return 2
82
+ end
83
+
84
+ result = Import.new(paths.first, **options).call
85
+ return 2 unless write_recipe(result.text, output, out, err)
86
+
87
+ result.warnings.each { |warning| err.puts "warning: #{warning}" }
88
+ err.puts result.summary
89
+ 0
90
+ rescue Import::Error => e
91
+ err.puts e.message
92
+ 1
93
+ rescue OptionParser::ParseError => e
94
+ err.puts e.message
95
+ 2
96
+ rescue StandardError => e
97
+ # The description is someone else's: what the importer did not foresee
98
+ # is answered with one line, never with the text of an exception.
99
+ err.puts "import failed (#{e.class}): this is a defect of api_recipes, not of the description"
100
+ 1
101
+ end
102
+
103
+ def import_problem(paths, output, name)
104
+ return 'import needs one OpenAPI file' unless paths.size == 1
105
+ unless name.nil? || Internals::Compiler::METHOD_NAME.match?(name)
106
+ return '--name: must be the name of a method: letters, digits and _, not starting with a digit'
107
+ end
108
+ return "#{paths.first}: no such file" unless File.exist?(paths.first)
109
+ return "#{paths.first}: is not a file that can be read" unless File.file?(paths.first) && File.readable?(paths.first)
110
+ return "#{output} already exists: remove it or choose another name" if output && File.exist?(output)
111
+
112
+ nil
113
+ end
114
+
115
+ # The file of --output is created, never replaced.
116
+ def write_recipe(text, output, out, err)
117
+ if output
118
+ File.open(output, File::WRONLY | File::CREAT | File::EXCL) { |file| file.write(text) }
119
+ else
120
+ out.write(text)
121
+ end
122
+ true
123
+ rescue Errno::EPIPE
124
+ # The reader of STDOUT went away, as in `api_recipes import ... | head`.
125
+ true
126
+ rescue SystemCallError => e
127
+ err.puts "#{output || 'the recipe'}: cannot be written (#{e.class.name.split('::').last})"
128
+ false
129
+ end
130
+
131
+ def routes(args, out, err)
132
+ erb = false
133
+ parser = OptionParser.new
134
+ parser.on('--erb') { erb = true }
135
+ files = parser.parse(args)
136
+ if files.empty?
137
+ err.puts 'routes needs at least one configuration file'
138
+ return 2
139
+ end
140
+
141
+ Routes.new(files, erb: erb).report(out, err)
142
+ rescue OptionParser::ParseError => e
143
+ err.puts e.message
144
+ 2
145
+ end
146
+
51
147
  def upgrade(args, out, err)
52
148
  configs = []
53
149
  erb = false
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module ApiRecipes
4
- VERSION = '3.0.0.beta1'
4
+ VERSION = '3.0.0.beta2'
5
5
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: api_recipes
3
3
  version: !ruby/object:Gem::Version
4
- version: 3.0.0.beta1
4
+ version: 3.0.0.beta2
5
5
  platform: ruby
6
6
  authors:
7
7
  - Alessandro Verlato
@@ -57,6 +57,13 @@ files:
57
57
  - lib/api_recipes.rb
58
58
  - lib/api_recipes/api.rb
59
59
  - lib/api_recipes/cli.rb
60
+ - lib/api_recipes/cli/import.rb
61
+ - lib/api_recipes/cli/import/document.rb
62
+ - lib/api_recipes/cli/import/security.rb
63
+ - lib/api_recipes/cli/import/server.rb
64
+ - lib/api_recipes/cli/import/tree.rb
65
+ - lib/api_recipes/cli/import/writer.rb
66
+ - lib/api_recipes/cli/routes.rb
60
67
  - lib/api_recipes/cli/upgrade.rb
61
68
  - lib/api_recipes/configuration.rb
62
69
  - lib/api_recipes/endpoint.rb