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.
data/UPGRADING.md CHANGED
@@ -5,7 +5,7 @@ Version 3.0 keeps the way you use the gem: the YAML files, `ApiRecipes.configure
5
5
  `ApiRecipes.github.users.show('octocat').run` work as before. A YAML file that
6
6
  is valid for 2.x needs no change, apart from what part 2 describes: options and
7
7
  values that 2.x accepted without checking them, a placeholder in `base_url` and a
8
- `{word}` in a header value. What changes is how the gem behaves around them: it
8
+ `{word}` in a header value or in a path. What changes is how the gem behaves around them: it
9
9
  checks more, it refuses more, and a few results are different.
10
10
 
11
11
  This guide has six parts:
@@ -92,10 +92,15 @@ configuration in place. Four things are worth knowing:
92
92
  `variables: { template: { default: '{id}' } }` with the header value
93
93
  `'{template}'`. Braces around anything else, such as a JSON value, are sent
94
94
  as they are.
95
+ - A word in braces in the `path` of an endpoint, such as `/items/{id}`, is now a
96
+ variable too, and one that is not declared is an error. In 2.x the braces were
97
+ sent as text. If you meant a value that changes at every call, write a
98
+ placeholder, `/items/:id`. To keep the braces as text, write `\{id}`.
95
99
  - A file that is missing, empty, not valid YAML or not valid UTF-8 raises
96
100
  `ApiRecipes::RecipeFileError`, which names the file. Files are read with
97
101
  `YAML.safe_load`: plain values, symbols and aliases are accepted, and nothing
98
- else. A file called `something.recipe.yml` is refused.
102
+ else. A file called `something.recipe.yml` is refused: it is a portable
103
+ recipe, and goes in `recipes_paths`.
99
104
 
100
105
  ### A class with its own destination needs its own credential
101
106
 
@@ -111,17 +116,42 @@ api 'github': the credential is bound to "https://api.github.com" but the reques
111
116
  or set it to nil to send none
112
117
  ```
113
118
 
114
- Set the credential on the class:
119
+ Give the credential where the class declares the API:
115
120
 
116
121
  ```ruby
117
122
  class EnterpriseClient
118
123
  include ApiRecipes
119
- api :github, host: 'ent.example.test'
124
+ api :github, host: 'ent.example.test', authorization: "Bearer #{ENV.fetch('ENTERPRISE_TOKEN')}"
125
+ end
126
+ ```
127
+
128
+ ### Credentials are given when the application starts
129
+
130
+ In 2.x the usual line was `ApiRecipes.github.authorization = '...'`, and code
131
+ that served several users assigned it before each call. What `ApiRecipes.github`
132
+ and a class use is shared by every thread of the process, so a request could
133
+ leave with the token of another user. Now `authorization=`, `basic_auth=` and
134
+ `variables=` raise `ApiRecipes::Error` on `ApiRecipes.github` and on a class,
135
+ and the message says where the value goes:
136
+
137
+ ```ruby
138
+ # the whole application: once, in configure
139
+ ApiRecipes.configure do |config|
140
+ config.values = { github: { authorization: "Bearer #{ENV.fetch('GITHUB_TOKEN')}" } }
120
141
  end
121
142
 
122
- EnterpriseClient.github.authorization = "Bearer #{ENV.fetch('ENTERPRISE_TOKEN')}"
143
+ # one class: where it declares the API
144
+ class AdminClient
145
+ include ApiRecipes
146
+ api :github, authorization: "Bearer #{ENV.fetch('ADMIN_TOKEN')}"
147
+ end
148
+
149
+ # one user, one request: the chain, or an object of its own
150
+ ApiRecipes.github.with(authorization: "Bearer #{user.token}").users.run
123
151
  ```
124
152
 
153
+ The writers still work on an object, as in `client.github.authorization = ...`.
154
+
125
155
  ### `nil` or an empty path parameter
126
156
 
127
157
  `show(nil)` and `show('')` built the URL of the parent. They now raise
@@ -236,13 +266,13 @@ The warnings name the endpoint and never the value. `config.upgrade_warnings = f
236
266
  turns them off. Two more effects: a `:` in a value no longer breaks nested
237
267
  endpoints, and a suffix after a placeholder, as in `/:name.json`, is kept.
238
268
 
239
- ### Credentials on a class or an instance take effect
269
+ ### Credentials on an instance take effect
240
270
 
241
- In 2.x `MyClass.github.authorization = '...'` was lost, because every call
242
- returned a new object. Now it is stored for the class, and an instance can have its
243
- own. If your code assigned one of them and relied on it having no effect, it now
244
- sends a credential. The nearest level wins: the chain (`with`), the object, its
245
- class and ancestors, then `ApiRecipes.github`. Assigning `nil` means "send none".
271
+ In 2.x `client.github.authorization = '...'` was lost, because every call
272
+ returned a new object. Now it is kept for that object. If your code assigned
273
+ one and relied on it having no effect, it now sends a credential. The nearest
274
+ level wins: the chain (`with`), the object, the class that declares the API,
275
+ then the whole application. A credential given as `nil` means "send none".
246
276
 
247
277
  ### Logging
248
278
 
@@ -278,11 +308,15 @@ rescue ApiRecipes::ResponseCodeNotAsExpected => e
278
308
  end
279
309
  ```
280
310
 
281
- ### Nested endpoints inherit `verify_with`
311
+ ### An endpoint looks for its options up the tree
282
312
 
283
- A nested endpoint written without options, under a parent with `verify_with`, did
284
- not inherit the verification in 2.x. Now every nested endpoint does, unless it
285
- sets its own.
313
+ In 2.x an endpoint took `timeout`, `on_bad_code` and `mime_type` from the API,
314
+ whatever the endpoint that contained it said, and one written without options
315
+ did not take `verify_with` from its parent. Now an endpoint that does not set
316
+ one of these four options looks for it in the endpoints that contain it, from
317
+ the nearest, then in the API, and takes the first value it finds. Look at the
318
+ endpoints that set one of them and also contain other endpoints: those now
319
+ find it there. `ok_code` is read only on its endpoint.
286
320
 
287
321
  ### `apis_configs` after the files
288
322
 
@@ -385,19 +419,30 @@ You can adopt these when you are ready. The [README](README.md) describes each o
385
419
  `ApiRecipes.github[:users][:show, 'octocat']`, whatever the name.
386
420
  - **`with`**: options for one chain or one request, without changing anything
387
421
  stored: `ApiRecipes.github.with(host: 'github.example.com')`.
388
- - **Credentials along a chain**: the chain, the object, the class and its
389
- ancestors, then `ApiRecipes.github`. A credential is bound to its origin.
390
- - **`variables`**: `{name}` placeholders in `host`, `base_url` and the values of
391
- `default_headers`, with values given at any of those levels.
422
+ - **Credentials along a chain**: the chain, the object, the class that declares
423
+ the API, then the whole application. A credential is bound to its origin.
424
+ - **`variables`**: `{name}` placeholders in `host`, `base_url`, the `path` of an
425
+ endpoint and the values of `default_headers` and `default_params`, with
426
+ values given at any of those levels.
427
+ - **`default_params`**: query parameters sent with every request, as
428
+ `default_headers` does for headers. Both can be written on an endpoint, for
429
+ that endpoint and the ones below it.
430
+ - **`resource`**: `resource: true` on an endpoint adds `show`, `create`,
431
+ `update`, `replace` and `delete` under it.
392
432
  - **`auth`**: says where the credential goes: the `Authorization` header, a header
393
433
  of your choice or a query parameter.
394
434
  - **`ok_code`** accepts a list of statuses, and `response.success?` tells whether a
395
435
  response passed the rule of its endpoint.
396
436
  - **`definition`**, `routes` and a safe `inspect` on APIs and endpoints.
397
437
  - **Validated configuration**, with every problem reported at once.
398
- - **`config.variables`**, **`config.upgrade_warnings`** and the logging options
399
- described above.
400
- - **The `api_recipes` command**, with `upgrade`.
438
+ - **`config.values`**, which gives each API its credential and the values of
439
+ its variables for the whole application, **`config.upgrade_warnings`** and
440
+ the logging options described above.
441
+ - **The `api_recipes` command**, with `upgrade`, `import`, `routes`, `install`,
442
+ `update` and `check`.
443
+ - **Portable recipes**: recipes written by others, installed with
444
+ `api_recipes install` and loaded with `config.recipes_paths`. See
445
+ [Portable recipes](README.md#portable-recipes) in the README.
401
446
 
402
447
  ## 6. Security
403
448
 
@@ -31,11 +31,15 @@ module ApiRecipes
31
31
  credential && credential.kind == :authorization ? credential.value : nil
32
32
  end
33
33
 
34
- # Sets the credential of the caller's level; nil means "send none". The
35
- # writers refuse an api returned by with: its options belong to its chain.
34
+ # Sets the credential of an object; nil means "send none". Only an object
35
+ # has writers: what the whole application or a class uses is shared by
36
+ # every thread, so it is given where the application starts, to
37
+ # ApiRecipes.configure (config.values) or to `api` in the class. The
38
+ # writers also refuse an api returned by with: its options belong to its
39
+ # chain.
36
40
  def authorization=(value)
37
- unless @context.overrides.empty?
38
- raise Error, 'an api returned by with cannot set authorization for the caller: use with(authorization: ...)'
41
+ if Module === @context.owner || !@context.overrides.empty?
42
+ raise Error, Internals::LevelSet.refusal(:authorization, @context.owner, @context.definition.name, @context.overrides.empty?)
39
43
  end
40
44
 
41
45
  credential = Internals::Credential.from(:authorization, value)
@@ -48,8 +52,8 @@ module ApiRecipes
48
52
  end
49
53
 
50
54
  def basic_auth=(value)
51
- unless @context.overrides.empty?
52
- raise Error, 'an api returned by with cannot set basic_auth for the caller: use with(basic_auth: ...)'
55
+ if Module === @context.owner || !@context.overrides.empty?
56
+ raise Error, Internals::LevelSet.refusal(:basic_auth, @context.owner, @context.definition.name, @context.overrides.empty?)
53
57
  end
54
58
 
55
59
  credential = Internals::Credential.from(:basic_auth, value)
@@ -58,14 +62,14 @@ module ApiRecipes
58
62
 
59
63
  # The variable values of the caller's level.
60
64
  def variables
61
- level = Internals::LevelSet.read(@context.owner, @context.level_key)
65
+ level = @context.own_level
62
66
  (level && level.variables) || {}
63
67
  end
64
68
 
65
- # Sets the variable values of the caller's level; nil removes them.
69
+ # Sets the variable values of an object; nil removes them. See authorization=.
66
70
  def variables=(values)
67
- unless @context.overrides.empty?
68
- raise Error, 'an api returned by with cannot set variables for the caller: use with(variables: ...)'
71
+ if Module === @context.owner || !@context.overrides.empty?
72
+ raise Error, Internals::LevelSet.refusal(:variables, @context.owner, @context.definition.name, @context.overrides.empty?)
69
73
  end
70
74
 
71
75
  values = Internals::Registry.variable_values(values)
@@ -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