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,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,197 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'open3'
4
+ require 'tmpdir'
5
+
6
+ module ApiRecipes
7
+ module CLI
8
+ class Recipes
9
+ # Reads the file of one recipe from a Git repository. Nothing is checked
10
+ # out: the commit is fetched into an empty repository in a temporary
11
+ # folder, and the file is read from there after checking that it is a
12
+ # regular file. git is run without a shell, and may only use https and
13
+ # ssh.
14
+ class Git
15
+ PROTOCOLS = %w[https ssh].freeze
16
+ FOLDER = 'recipes'
17
+ FILE_MODES = %w[100644 100755].freeze
18
+ ADDRESS = %r{\A(?<scheme>[a-z]+)://(?<host>[A-Za-z0-9.-]*)(?::[0-9]{1,5})?(?<path>/[A-Za-z0-9._~+/-]*)?\z}
19
+ WITH_USER = %r{\Ahttps://[^/]*@}
20
+ # The two ways git writes an ssh address: ssh://[user@]host[:port]/path
21
+ # and user@host:path. The user, the host and the path never start with
22
+ # a hyphen, which ssh or git would read as an option, and hold no
23
+ # character that a shell or the ssh configuration of the user could
24
+ # expand. The short form needs its user: host:path alone is also how a
25
+ # mistyped https:/ address and a Windows path look. Its path does not
26
+ # start with //, which would make it look like a URL.
27
+ SSH_USER = '[A-Za-z0-9_][A-Za-z0-9._-]*'
28
+ SSH_HOST = '[A-Za-z0-9][A-Za-z0-9.-]*'
29
+ SSH_URL = %r{\Assh://(?:#{SSH_USER}@)?#{SSH_HOST}(?::[0-9]{1,5})?/[A-Za-z0-9._~+/-]*\z}
30
+ SSH_SHORT = %r{\A#{SSH_USER}@#{SSH_HOST}:(?!//)[A-Za-z0-9._~/][A-Za-z0-9._~+/-]*\z}
31
+ WITH_PASSWORD = %r{\Assh://[^/@]*:[^/@]*@}
32
+ ACCEPTED = 'must start with https:// or ssh://, or be written as user@host:path'
33
+ UNREAD = 'fatal: Could not read from remote repository.'
34
+ MAX_ADDRESS = 2000
35
+ COMMIT = /\A(?:\h{40}|\h{64})\z/
36
+ # git reads pathspecs as they are written, answers in English, and
37
+ # does not take a repository from the environment.
38
+ ENVIRONMENT = { 'GIT_LITERAL_PATHSPECS' => '1', 'LC_ALL' => 'C',
39
+ 'GIT_DIR' => nil, 'GIT_WORK_TREE' => nil, 'GIT_INDEX_FILE' => nil, 'GIT_NAMESPACE' => nil,
40
+ 'GIT_OBJECT_DIRECTORY' => nil, 'GIT_ALTERNATE_OBJECT_DIRECTORIES' => nil,
41
+ 'GIT_COMMON_DIR' => nil }.freeze
42
+
43
+ # git is missing or could not do its work.
44
+ class Failure < Error; end
45
+
46
+ # The repository was read, and the recipe is not there.
47
+ class NotFound < Error; end
48
+
49
+ Found = Data.define(:text, :commit)
50
+
51
+ # Why the address cannot be used, or nil. An https address with a
52
+ # user name or a password is refused, and so is an ssh one with a
53
+ # password: they would end up in recipes.lock. The user of an ssh
54
+ # address is not a secret and is part of it.
55
+ def self.address_problem(address)
56
+ return 'must be text' unless address.is_a?(String)
57
+ return "must be at most #{MAX_ADDRESS} characters" if address.length > MAX_ADDRESS
58
+ return nil if ssh?(address)
59
+ return 'must not contain a password: ssh takes what it needs from its keys and its agent' if WITH_PASSWORD.match?(address)
60
+ if WITH_USER.match?(address)
61
+ return 'must not contain a user name or a password: git takes them from its own configuration'
62
+ end
63
+
64
+ match = ADDRESS.match(address)
65
+ return ACCEPTED unless match && match[:scheme] != 'ssh' && PROTOCOLS.include?(match[:scheme])
66
+ return 'must name a host' if match[:host].empty? && match[:scheme] != 'file'
67
+
68
+ nil
69
+ end
70
+
71
+ # Whether the address is one of the two ssh forms, and ssh may be used.
72
+ def self.ssh?(address)
73
+ PROTOCOLS.include?('ssh') && (SSH_URL.match?(address) || SSH_SHORT.match?(address))
74
+ end
75
+
76
+ # ask: whether git may ask on the terminal for the user name and the
77
+ # password of an https repository, as it does for a clone. Without it
78
+ # git asks nothing. What ssh asks is its own business: see hint.
79
+ def initialize(address, ask: false)
80
+ problem = self.class.address_problem(address)
81
+ raise Failure, "the address of the repository #{problem}" if problem
82
+
83
+ @address = address
84
+ @ask = ask ? true : false
85
+ end
86
+
87
+ # The recipe called name: at the tag name-version, or at the head of
88
+ # the repository when version is nil.
89
+ def fetch(name, version = nil)
90
+ unless Recipe::NAME.match?(name) && (version.nil? || Recipe::VERSION.match?(version))
91
+ raise ArgumentError, 'not the name or the version of a recipe'
92
+ end
93
+
94
+ Dir.mktmpdir('api_recipes') do |directory|
95
+ git('init', '--bare', '--quiet', '--template=', directory)
96
+ fetch_commit(directory, name, version)
97
+ commit = git("--git-dir=#{directory}", 'rev-parse', '--verify', '--quiet', 'FETCH_HEAD^{commit}').strip
98
+ raise Failure, "git did not say which commit of #{@address} it read" unless COMMIT.match?(commit)
99
+
100
+ Found.new(text: file(directory, commit, name), commit: commit)
101
+ end
102
+ end
103
+
104
+ private
105
+
106
+ def fetch_commit(directory, name, version)
107
+ ref = version ? "refs/tags/#{name}-#{version}" : 'HEAD'
108
+ _out, err, status = run("--git-dir=#{directory}", *transport, 'fetch', '--depth', '1', '--no-tags',
109
+ '--no-recurse-submodules', '--quiet', '--', @address, ref)
110
+ return if status.success?
111
+
112
+ if version && err.include?("couldn't find remote ref")
113
+ raise NotFound, "version #{version} of #{name} is not in #{@address}: there is no tag #{name}-#{version}"
114
+ end
115
+ raise Failure, "git could not read #{@address}: #{reason(err)}#{hint(err)}"
116
+ end
117
+
118
+ # What to do about a failure that has a known cause, or nothing. The
119
+ # cause is read in the lines that git and ssh write themselves, each
120
+ # from its start: the text of a server is not enough to choose one.
121
+ def hint(err)
122
+ said = err.to_s.dup.force_encoding(Encoding::UTF_8).scrub('?')
123
+ if said.match?(/^fatal: transport '[^'\n]*' not allowed$/)
124
+ " (git may use only #{PROTOCOLS.join(' and ')} here: check url.*.insteadOf in your git configuration)"
125
+ elsif said.match?(/^fatal: could not read Username for /)
126
+ ' (a private repository needs credentials that git already has for its host, such as a credential ' \
127
+ 'helper: without a terminal the command cannot ask for them)'
128
+ elsif said.match?(/^fatal: Authentication failed for /)
129
+ ' (the repository refused the user name or the password that git gave it)'
130
+ elsif said.match?(/^@? *WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!/)
131
+ ' (ssh says that the key of this host is not the one it knows: another machine may be answering in ' \
132
+ 'its place. Find out why before you connect again)'
133
+ elsif said.match?(/^Host key verification failed\./)
134
+ ' (ssh does not know this host: connect to it once with ssh, or add its key to known_hosts)'
135
+ elsif said.match?(/^[^\n]*: Permission denied \(/)
136
+ ' (ssh has no key that this host accepts for the repository: check the key and the agent with ssh -T)'
137
+ else
138
+ ''
139
+ end
140
+ end
141
+
142
+ # Only the protocols of PROTOCOLS, whatever the configuration of git
143
+ # says; no redirect to another address; objects checked on arrival.
144
+ def transport
145
+ allowed = PROTOCOLS.flat_map { |protocol| ['-c', "protocol.#{protocol}.allow=always"] }
146
+ ['-c', 'protocol.allow=never', *allowed, '-c', 'http.followRedirects=false', '-c', 'transfer.fsckObjects=true',
147
+ '-c', 'http.lowSpeedLimit=1000', '-c', 'http.lowSpeedTime=30']
148
+ end
149
+
150
+ def file(directory, commit, name)
151
+ path = "#{FOLDER}/#{name}#{Recipe::SUFFIX}"
152
+ entry = git("--git-dir=#{directory}", 'ls-tree', '-z', commit, '--', path).split("\0").first
153
+ raise NotFound, "#{name} is not in #{@address}: there is no #{path}" if entry.nil?
154
+
155
+ mode, type, id = entry.split("\t", 2).first.split
156
+ unless FILE_MODES.include?(mode) && type == 'blob' && COMMIT.match?(id.to_s)
157
+ raise NotFound, "#{path} in #{@address} is not a regular file (it is a link, a folder or a submodule): it was not read"
158
+ end
159
+ size = git("--git-dir=#{directory}", 'cat-file', '-s', id).strip
160
+ unless size.match?(/\A[0-9]{1,12}\z/) && size.to_i <= Recipe::MAX_BYTES
161
+ raise NotFound, "#{path} in #{@address} is larger than #{Recipe::MAX_BYTES} bytes: it was not read"
162
+ end
163
+
164
+ git("--git-dir=#{directory}", 'cat-file', 'blob', id).force_encoding(Encoding::UTF_8)
165
+ end
166
+
167
+ # The output of a git command that must succeed.
168
+ def git(*arguments)
169
+ out, err, status = run(*arguments)
170
+ raise Failure, "git failed (#{arguments.find { |argument| !argument.start_with?('-') }}): #{reason(err)}" unless status.success?
171
+
172
+ out
173
+ end
174
+
175
+ def run(*arguments)
176
+ environment = ENVIRONMENT.merge('GIT_ALLOW_PROTOCOL' => PROTOCOLS.join(':'))
177
+ environment['GIT_TERMINAL_PROMPT'] = '0' unless @ask
178
+ Open3.capture3(environment, 'git', *arguments, stdin_data: '', binmode: true)
179
+ rescue Errno::ENOENT
180
+ raise Failure, 'git was not found: install git, or install the recipe from a file'
181
+ end
182
+
183
+ # Why git failed, as one line that can be printed: the line where it
184
+ # says fatal or error, or the last one. When git only says that it
185
+ # could not read the repository, the line before says why.
186
+ def reason(text)
187
+ lines = text.to_s.dup.force_encoding(Encoding::UTF_8).scrub('?').lines.map(&:strip).reject(&:empty?)
188
+ index = lines.rindex { |one| one.start_with?('fatal:', 'error:') } || (lines.size - 1)
189
+ return 'it gave no reason' if index.negative?
190
+
191
+ index -= 1 if lines[index] == UNREAD && index.positive?
192
+ Summary.shown(lines[index])
193
+ end
194
+ end
195
+ end
196
+ end
197
+ end
@@ -0,0 +1,34 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ApiRecipes
4
+ module CLI
5
+ class Recipes
6
+ # Writes the recipes.lock of a folder.
7
+ module LockFile
8
+ HEADER = "# Written by api_recipes. Do not edit: change it with `api_recipes install` and `api_recipes update`.\n"
9
+ KEYS = %i[version source commit sha256].freeze
10
+
11
+ class << self
12
+ # The text of a lock with these entries: { name => Entry }. Every
13
+ # value is written between single quotes, and the text is read back
14
+ # before it is returned.
15
+ def text(entries)
16
+ lines = entries.sort.flat_map do |name, entry|
17
+ [" #{quote(name)}:"] + KEYS.filter_map { |key| " #{key}: #{quote(entry.public_send(key))}" if entry.public_send(key) }
18
+ end
19
+ text = "#{HEADER}format: #{Internals::RecipeLock::FORMAT}\nrecipes:\n#{lines.join("\n")}\n"
20
+ data = Internals::PlainYaml.load(text, max_bytes: Internals::Recipe::MAX_BYTES)
21
+ expected = entries.to_h { |name, entry| [name, entry.to_h.compact.transform_keys(&:to_s)] }
22
+ raise Error, 'internal error: recipes.lock does not read back as it was written' unless (data['recipes'] || {}) == expected
23
+
24
+ text
25
+ end
26
+
27
+ private
28
+
29
+ def quote(value) = "'#{value.to_s.gsub("'", "''")}'"
30
+ end
31
+ end
32
+ end
33
+ end
34
+ end
@@ -0,0 +1,226 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ApiRecipes
4
+ module CLI
5
+ class Recipes
6
+ # What a recipe does, in the lines shown before it is installed: where
7
+ # the requests go, where the credential goes, what is sent with every
8
+ # request, which calls change something. Every text that comes from the
9
+ # recipe goes through shown, and a text that is cut says so: nothing is
10
+ # left out without a sign.
11
+ class Summary
12
+ LABEL_WIDTH = 15
13
+ # The characters shown of a name or a value in a row, of a row, and of
14
+ # a text shown whole: more than a name or a value of a recipe can have.
15
+ PART = 100
16
+ ROW = 500
17
+ WHOLE = 5_000
18
+
19
+ # A header or a parameter sent with every request. where: the name of
20
+ # the endpoint that adds it, nil for the api; below: whether that
21
+ # endpoint has others below it, which take it too.
22
+ Sent = Data.define(:name, :value, :where, :below) do
23
+ def key = [name, where]
24
+ end
25
+
26
+ # value as it can be printed: one line, without control and format
27
+ # characters, with one space where it has several, at most limit
28
+ # characters.
29
+ def self.shown(value, limit = 200)
30
+ Internals::PlainYaml.label(value.to_s.scrub('?').gsub(/\p{Z}+/, ' '), limit)
31
+ end
32
+
33
+ # origin: where the recipe comes from, in words that are already safe.
34
+ def initialize(recipe, origin: nil)
35
+ @recipe = recipe
36
+ @api = recipe.definition
37
+ @origin = origin
38
+ end
39
+
40
+ def title = "#{@recipe.name} #{@recipe.version}"
41
+
42
+ def text = @recipe.text
43
+
44
+ def lines
45
+ meta = @api.recipe
46
+ rows = [['summary', meta[:summary]], ['homepage', meta[:homepage]], ['from', @origin], ['address', address]]
47
+ rows << ['with defaults', filled_address] unless filled_address == address
48
+ rows << ['credential', credential]
49
+ [title] + rows.reject { |_, text| text.nil? }.flat_map { |label, text| rows_for(label, [text], WHOLE) } +
50
+ rows_for('headers', headers) + rows_for('params', params) + rows_for('variables', variables) + calls
51
+ end
52
+
53
+ # What whoever installs the recipe should know before using it.
54
+ def warnings
55
+ found = []
56
+ auth = @api.auth || {}
57
+ if auth[:type] == :query
58
+ found << "the credential travels in the address, as the query parameter #{clip(auth[:name], PART)}: " \
59
+ 'addresses are written in logs and kept by proxies'
60
+ end
61
+ found << 'the protocol is http: a credential you assign travels without encryption' if @api.protocol == 'http'
62
+ found
63
+ end
64
+
65
+ # The address as the recipe writes it, with its {variables}.
66
+ def address(fill = false)
67
+ host = fill ? filled(@api.host) : @api.host
68
+ base = @api.base_url.to_s
69
+ base = filled(base) if fill
70
+ path = "/#{base}".gsub(%r{/+}, '/').chomp('/')
71
+ "#{@api.protocol}://#{host}#{":#{@api.port}" if @api.port}#{path}"
72
+ end
73
+
74
+ # The same address with the default of each variable that has one.
75
+ def filled_address = address(true)
76
+
77
+ # Where a credential that the application assigns goes. A recipe that
78
+ # declares none does not stop it.
79
+ def credential
80
+ auth = @api.auth || {}
81
+ case auth[:type]
82
+ when :none then 'none declared: a credential you assign still goes in the Authorization header'
83
+ when :header then "in the header #{auth[:name]}"
84
+ when :query then "in the query string, as the parameter #{auth[:name]}"
85
+ else 'in the Authorization header'
86
+ end
87
+ end
88
+
89
+ # The headers sent with every request, as "Name: value", then those
90
+ # that an endpoint adds, with the endpoint.
91
+ def headers = sent(:headers).map { |one| sent_row(one) }
92
+
93
+ # The query parameters sent with every request, in the same form.
94
+ def params = sent(:params).map { |one| sent_row(one) }
95
+
96
+ # The headers (:headers) or the parameters (:params) of the api and
97
+ # of its endpoints, as they are written.
98
+ def sent(kind)
99
+ key = kind == :headers ? :default_headers : :default_params
100
+ found = @api.public_send(key).map { |name, value| Sent.new(name.to_s, value.to_s, nil, false) }
101
+ each_endpoint do |node|
102
+ (node.own(key) || {}).each do |name, value|
103
+ found << Sent.new(name.to_s, value.to_s, node.full_name, !node.endpoints.empty?)
104
+ end
105
+ end
106
+ found
107
+ end
108
+
109
+ # Each call that is not a GET, as [verb, call, path].
110
+ def changing_calls
111
+ origin = "#{@api.protocol}://#{@api.host}#{":#{@api.port}" if @api.port}"
112
+ @api.routes.reject { |route| route.verb == :get }.map do |route|
113
+ [route.verb.to_s.upcase, route.call, route.url.delete_prefix(origin)]
114
+ end
115
+ end
116
+
117
+ # Each call as { call => verb }.
118
+ def verbs = @api.routes.to_h { |route| [route.call, route.verb.to_s.upcase] }
119
+
120
+ # What this recipe changes in the recipe installed now, whose summary
121
+ # is previous (nil when it is not a valid recipe): the address, the
122
+ # credential, the headers, the parameters and the verbs.
123
+ def changes_from(previous)
124
+ return [' it replaces a file that is not a valid recipe'] if previous.nil?
125
+
126
+ found = [%w[address address], ['with defaults', 'filled_address'], %w[credential credential]].filter_map do |label, reader|
127
+ before = previous.public_send(reader)
128
+ after = public_send(reader)
129
+ " #{label}: #{clip(before, WHOLE)} -> #{clip(after, WHOLE)}" unless before == after
130
+ end
131
+ found.concat(sent_changes('header', previous.sent(:headers), sent(:headers)))
132
+ found.concat(sent_changes('parameter', previous.sent(:params), sent(:params)))
133
+ found.concat(verb_changes(previous.verbs))
134
+ found << ' no change in the address, the credential, the headers, the parameters or the verbs' if found.empty?
135
+ [" changes from #{clip(previous.title, PART)}:"] + found
136
+ end
137
+
138
+ private
139
+
140
+ # text as it can be printed, with at most limit characters; when it
141
+ # has more, the ones shown are followed by how many it has.
142
+ def clip(text, limit)
143
+ whole = self.class.shown(text, WHOLE + 1)
144
+ whole.length > limit ? "#{whole[0, limit]}... (#{whole.length > WHOLE ? "more than #{WHOLE}" : whole.length} characters)" : whole
145
+ end
146
+
147
+ def sent_row(one) = "#{clip(one.name, PART)}: #{clip(one.value, PART)}#{place(one, PART)}"
148
+
149
+ def place(one, limit)
150
+ one.where ? " (#{clip(one.where, limit)}#{' and below' if one.below})" : ''
151
+ end
152
+
153
+ # What changes between two lists of headers or of parameters, a line
154
+ # for each one, compared as they are written and shown whole.
155
+ def sent_changes(word, before, after)
156
+ old = before.to_h { |one| [one.key, one] }
157
+ found = after.filter_map do |one|
158
+ was = old[one.key]
159
+ if was.nil?
160
+ " new #{word}: #{clip(one.name, WHOLE)}: #{clip(one.value, WHOLE)}#{place(one, WHOLE)}"
161
+ elsif was.value != one.value
162
+ " #{word} #{clip(one.name, WHOLE)}#{place(one, WHOLE)}: #{clip(was.value, WHOLE)} -> #{clip(one.value, WHOLE)}"
163
+ end
164
+ end
165
+ kept = after.to_h { |one| [one.key, true] }
166
+ found + before.reject { |one| kept.key?(one.key) }.map do |one|
167
+ " #{word} no longer sent: #{clip(one.name, WHOLE)}#{place(one, WHOLE)}"
168
+ end
169
+ end
170
+
171
+ def each_endpoint(level = @api.endpoints, &block)
172
+ level.each_value do |node|
173
+ block.call(node)
174
+ each_endpoint(node.endpoints, &block)
175
+ end
176
+ end
177
+
178
+ # One row for each item: the label beside the first, the others below it.
179
+ def rows_for(label, items, limit = ROW)
180
+ items.each_with_index.map do |item, index|
181
+ " #{(index.zero? ? "#{label}:" : '').ljust(LABEL_WIDTH)}#{clip(item, limit)}"
182
+ end
183
+ end
184
+
185
+ def verb_changes(before)
186
+ after = verbs
187
+ found = after.filter_map do |call, verb|
188
+ if !before.key?(call)
189
+ " new call that is not a GET: #{verb} #{clip(call, WHOLE)}" unless verb == 'GET'
190
+ elsif before[call] != verb
191
+ " #{clip(call, WHOLE)}: #{before[call]} -> #{verb}"
192
+ end
193
+ end
194
+ added = (after.keys - before.keys).size
195
+ removed = (before.keys - after.keys).size
196
+ found << " calls: #{added} added, #{removed} removed" unless added.zero? && removed.zero?
197
+ found
198
+ end
199
+
200
+ def filled(text)
201
+ defaults = @api.variables.transform_values { |spec| spec[:default] }.compact
202
+ text.gsub(Internals::Template::VARIABLE) { defaults.fetch(Regexp.last_match(1).to_sym, Regexp.last_match(0)) }
203
+ end
204
+
205
+ # One line for each variable: its default, or that it must be set.
206
+ def variables
207
+ @api.variables.map do |name, spec|
208
+ state = spec[:default] ? "default #{clip(spec[:default], 60)}" : 'to be set'
209
+ "#{clip(name, PART)}: #{state}#{", #{clip(spec[:description], PART)}" if spec[:description]}"
210
+ end
211
+ end
212
+
213
+ def calls
214
+ total = @api.routes.size
215
+ changing = changing_calls
216
+ return rows_for('calls', ["#{total}, all GET"]) if changing.empty?
217
+
218
+ changing = changing.map { |verb, call, path| [verb, clip(call, ROW), clip(path, WHOLE)] }
219
+ widths = [0, 1].map { |column| changing.map { |call| call[column].length }.max }
220
+ rows_for('calls', ["#{total}, of which #{changing.size} #{changing.size == 1 ? 'is' : 'are'} not GET:"]) +
221
+ changing.map { |verb, call, path| " #{verb.ljust(widths[0])} #{call.ljust(widths[1])} #{path}" }
222
+ end
223
+ end
224
+ end
225
+ end
226
+ end