api_recipes 2.10.4 → 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.
Files changed (36) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +783 -81
  3. data/UPGRADING.md +473 -0
  4. data/exe/api_recipes +6 -0
  5. data/lib/api_recipes/api.rb +71 -49
  6. data/lib/api_recipes/cli/import/document.rb +234 -0
  7. data/lib/api_recipes/cli/import/security.rb +138 -0
  8. data/lib/api_recipes/cli/import/server.rb +166 -0
  9. data/lib/api_recipes/cli/import/tree.rb +288 -0
  10. data/lib/api_recipes/cli/import/writer.rb +127 -0
  11. data/lib/api_recipes/cli/import.rb +129 -0
  12. data/lib/api_recipes/cli/routes.rb +50 -0
  13. data/lib/api_recipes/cli/upgrade.rb +179 -0
  14. data/lib/api_recipes/cli.rb +166 -0
  15. data/lib/api_recipes/configuration.rb +185 -36
  16. data/lib/api_recipes/endpoint.rb +68 -118
  17. data/lib/api_recipes/errors.rb +137 -0
  18. data/lib/api_recipes/internals/compiler.rb +680 -0
  19. data/lib/api_recipes/internals/context.rb +237 -0
  20. data/lib/api_recipes/internals/credential.rb +86 -0
  21. data/lib/api_recipes/internals/declaration.rb +225 -0
  22. data/lib/api_recipes/internals/definition.rb +179 -0
  23. data/lib/api_recipes/internals/handles.rb +81 -0
  24. data/lib/api_recipes/internals/level.rb +192 -0
  25. data/lib/api_recipes/internals/path_template.rb +131 -0
  26. data/lib/api_recipes/internals/registry.rb +146 -0
  27. data/lib/api_recipes/internals/request.rb +285 -0
  28. data/lib/api_recipes/internals/template.rb +73 -0
  29. data/lib/api_recipes/response.rb +90 -9
  30. data/lib/api_recipes/version.rb +3 -1
  31. data/lib/api_recipes.rb +42 -152
  32. metadata +33 -12
  33. data/lib/api_recipes/exceptions.rb +0 -91
  34. data/lib/api_recipes/route.rb +0 -165
  35. data/lib/api_recipes/settings.rb +0 -30
  36. data/lib/api_recipes/utils.rb +0 -195
data/UPGRADING.md ADDED
@@ -0,0 +1,473 @@
1
+ # Upgrading from 2.x to 3.0
2
+
3
+ Version 3.0 keeps the way you use the gem: the YAML files, `ApiRecipes.configure`,
4
+ `api :name` in a class and the chain
5
+ `ApiRecipes.github.users.show('octocat').run` work as before. A YAML file that
6
+ is valid for 2.x needs no change, apart from what part 2 describes: options and
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
9
+ checks more, it refuses more, and a few results are different.
10
+
11
+ This guide has six parts:
12
+
13
+ 1. [Before you start](#1-before-you-start)
14
+ 2. [What stops at once, with a message](#2-what-stops-at-once-with-a-message)
15
+ 3. [What changes without a message](#3-what-changes-without-a-message)
16
+ 4. [What was removed, and what to use instead](#4-what-was-removed-and-what-to-use-instead)
17
+ 5. [What is new](#5-what-is-new)
18
+ 6. [Security](#6-security)
19
+
20
+ Then it explains [the `api_recipes upgrade` command](#the-api_recipes-upgrade-command),
21
+ which looks for these changes in your code. Each part is ordered from what is
22
+ most likely to affect you to what is least likely.
23
+
24
+ The examples that show a result use this configuration:
25
+
26
+ ```yaml
27
+ github:
28
+ host: api.github.com
29
+ endpoints:
30
+ users:
31
+ endpoints:
32
+ show:
33
+ path: /:login
34
+ files:
35
+ path: /:login/files/*path
36
+ repos:
37
+ route: no
38
+ path: /repos/:owner/:repo
39
+ endpoints:
40
+ show:
41
+ path: ''
42
+ with:
43
+ ```
44
+
45
+ ## 1. Before you start
46
+
47
+ - **Stay on 2.x until you are ready.** In your Gemfile, `gem 'api_recipes', '~> 2.10'`
48
+ keeps you on the current line. A pre-release such as `3.0.0.beta1` is never
49
+ picked by that version rule: ask for it by its number.
50
+ - **Ruby 3.3 or higher.** The gem refuses to install on an older Ruby. If you
51
+ cannot upgrade Ruby yet, stay on 2.10.
52
+ - **http.rb 6.** The gem needs `http` 6.0.4 or higher, below 7. http.rb 5 is no
53
+ longer supported.
54
+ - **Run `api_recipes upgrade`** on your code and your configuration files (see
55
+ [below](#the-api_recipes-upgrade-command)). It finds the removed
56
+ `route`, `base_configs`, `ApiRecipes.print_urls`, the removed error classes and
57
+ `Hash` and `Array` methods, and a few lines that deserve a look (manual
58
+ encoding of path parameters, a bare `rescue`, `follow:`). It then lists what it
59
+ cannot find, such as the removed accessors of `Endpoint` and `Api`.
60
+ - **Read your logs after the first run.** The gem now logs warnings, to STDERR, when
61
+ a path parameter value changes meaning and when an endpoint name cannot become
62
+ a method.
63
+
64
+ ## 2. What stops at once, with a message
65
+
66
+ These show up the first time the code runs. The message says what to do.
67
+
68
+ ### The configuration is checked when it is loaded
69
+
70
+ Unknown options, values that are not valid and verbs that do not exist used to be
71
+ accepted without a word. Now `ApiRecipes.configure` raises
72
+ `ApiRecipes::ConfigurationError` and lists every problem in one message:
73
+
74
+ ```
75
+ 4 problems in the configuration
76
+ github: unknown option 'hots'
77
+ github.timeout: must be a positive number
78
+ github.on_bad_code: 'explode' is not one of raise, ignore
79
+ github.endpoints.users.verb: 'yell' is not a verb known to http.rb
80
+ ```
81
+
82
+ Fix them all and run again. A failed `configure` leaves the previous
83
+ configuration in place. Four things are worth knowing:
84
+
85
+ - Keys that start with `x-` are free. Use them for your own notes.
86
+ - A `base_url` with a path placeholder (`:name` or `*name`) is an error. In 2.x
87
+ it silently became a required parameter of every root endpoint. For a value
88
+ that changes, declare a [variable](README.md#variables) and write `{name}`.
89
+ - A word in braces, such as `{id}`, in a value of `default_headers` is now a
90
+ variable, and one that is not declared is an error. To send that text as it
91
+ is, declare a variable whose default is the text and use the variable:
92
+ `variables: { template: { default: '{id}' } }` with the header value
93
+ `'{template}'`. Braces around anything else, such as a JSON value, are sent
94
+ as they are.
95
+ - A file that is missing, empty, not valid YAML or not valid UTF-8 raises
96
+ `ApiRecipes::RecipeFileError`, which names the file. Files are read with
97
+ `YAML.safe_load`: plain values, symbols and aliases are accepted, and nothing
98
+ else. A file called `something.recipe.yml` is refused.
99
+
100
+ ### A class with its own destination needs its own credential
101
+
102
+ In 2.x the credential of `ApiRecipes.github` was copied to every class that
103
+ declared the API, even a class that sent its requests to another host. Now a
104
+ credential is valid only for the origin it was set for (scheme, host and port).
105
+ A class that changes `host`, `protocol` or `port` and sets no credential of its
106
+ own raises:
107
+
108
+ ```
109
+ api 'github': the credential is bound to "https://api.github.com" but the request goes to
110
+ "https://ent.example.test". Set the credential at the level that changes the destination,
111
+ or set it to nil to send none
112
+ ```
113
+
114
+ Set the credential on the class:
115
+
116
+ ```ruby
117
+ class EnterpriseClient
118
+ include ApiRecipes
119
+ api :github, host: 'ent.example.test'
120
+ end
121
+
122
+ EnterpriseClient.github.authorization = "Bearer #{ENV.fetch('ENTERPRISE_TOKEN')}"
123
+ ```
124
+
125
+ ### `nil` or an empty path parameter
126
+
127
+ `show(nil)` and `show('')` built the URL of the parent. They now raise
128
+ `ApiRecipes::InvalidPathParameter`:
129
+
130
+ ```
131
+ invalid value for path parameter 'login' of 'github.users.show': is nil
132
+ ```
133
+
134
+ If you wanted the parent, call the parent endpoint. The values `.` and `..` raise
135
+ too.
136
+
137
+ ### Methods that were removed
138
+
139
+ These raise `NoMethodError` or `NameError`. Part 4 gives the replacement of each:
140
+
141
+ - `endpoint.route` and `endpoint.route.fill(object)`
142
+ - `Endpoint#name`, `#params`, `#children`, `#api`
143
+ - `Api#name`, `#configs`, `#base_configs`, `#object`
144
+ - `ApiRecipes.print_urls` and `ApiRecipes.print_urls = ...`
145
+ - `configuration.setup` and `response.request`
146
+ - `ApiRecipes::RouteNameClashWithExistentMethod`, `ApiRecipes::Route` and
147
+ `ApiRecipes::Settings`
148
+ - the error classes `RouteAndResourceNamesClashError`, `MissingRouteAttribute`,
149
+ `ProvidedObjectNotAsResponseData` and `NoConfigurationGivenForEndpoint`, which
150
+ nothing ever raised: a `rescue` clause that names one raises `NameError`
151
+ - the methods the gem added to `Hash` and `Array`
152
+
153
+ Beware of one case. A name such as `name` or `params`, which used to be an
154
+ accessor, now reaches the endpoint of that name if your configuration has one.
155
+ Otherwise it raises `NoMethodError`.
156
+
157
+ ### The name of an API in a class
158
+
159
+ `api :open`, `api :test`, `api :format` and any other name that is already a method
160
+ of the class, private ones of `Kernel` included, raise
161
+ `ApiRecipes::ApiNameClashError`. 2.x accepted them. Use `as:` to give the method
162
+ another name:
163
+
164
+ ```ruby
165
+ api :format, as: :formats
166
+ ```
167
+
168
+ An API can also be declared only once in a class and its ancestors, modules
169
+ included. A second declaration raises the same error. Declare it once and use
170
+ `with(...)` where you need other options.
171
+
172
+ ### Credentials with a line break
173
+
174
+ A credential with a line break or another control character raises
175
+ `ApiRecipes::InvalidCredential`. The message never contains the value. So does a
176
+ credential that is not a String, such as a Symbol or a number, which 2.x passed
177
+ on to http.rb: convert it with `to_s`.
178
+
179
+ The `headers:` given with a request are checked in the same way before anything
180
+ is sent. They must be a Hash (a list of pairs and `HTTP::Headers` are accepted
181
+ too), and a name or a value with a control character raises
182
+ `ApiRecipes::ConfigurationError`, which names the header and never shows the
183
+ value. A tab inside a value is allowed.
184
+
185
+ ### `follow` with something else than `true`, `false` or a Hash
186
+
187
+ `follow` accepts `true`, `false`, `nil` or a Hash with the keys `strict`,
188
+ `max_hops` and `on_redirect`. Anything else raises
189
+ `ApiRecipes::ConfigurationError` before the request is sent.
190
+
191
+ ## 3. What changes without a message
192
+
193
+ Nothing stops here: the code runs and does something different. Search your code
194
+ for each case.
195
+
196
+ ### Errors can be rescued with a bare `rescue`
197
+
198
+ The errors of 2.x inherited from `Exception`, so a bare `rescue` did not catch
199
+ them. Now they inherit from `ApiRecipes::Error`, a `StandardError`.
200
+
201
+ ```ruby
202
+ begin
203
+ ApiRecipes.github.users.show('octocat').run
204
+ rescue => e # catches ApiRecipes errors now
205
+ notify(e)
206
+ end
207
+ ```
208
+
209
+ A `rescue => e` or `rescue StandardError` around a call now handles a bad status,
210
+ a missing variable and the other errors of the gem as well. Rescue
211
+ `ApiRecipes::ResponseCodeNotAsExpected` by name where you meant it. A `rescue
212
+ Exception` keeps working.
213
+
214
+ ### Path parameters are encoded
215
+
216
+ 2.x inserted a value into the path as it was. Now each value is encoded:
217
+
218
+ ```ruby
219
+ ApiRecipes.github.users.show('a/b').url.to_s
220
+ # => "https://api.github.com/users/a%2Fb"
221
+ ```
222
+
223
+ - **Values you encoded yourself.** Remove the encoding (`ERB::Util.url_encode`,
224
+ `CGI.escape`): `%2F` would be sent as `%252F`. The gem logs a warning, once for
225
+ each endpoint, when a value looks already encoded.
226
+ - **A `/` in a value** that was used to cover several segments is now `%2F`. Write
227
+ the placeholder with a `*` instead: each segment is encoded and the slashes stay.
228
+ The gem logs a warning, once for each endpoint, when a value contains a `/`.
229
+
230
+ ```ruby
231
+ ApiRecipes.github.users.files('octocat', 'docs/readme.md').url.to_s
232
+ # => "https://api.github.com/users/octocat/files/docs/readme.md"
233
+ ```
234
+
235
+ The warnings name the endpoint and never the value. `config.upgrade_warnings = false`
236
+ turns them off. Two more effects: a `:` in a value no longer breaks nested
237
+ endpoints, and a suffix after a placeholder, as in `/:name.json`, is kept.
238
+
239
+ ### Credentials on a class or an instance take effect
240
+
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".
246
+
247
+ ### Logging
248
+
249
+ - The default logger writes to STDERR at warn level. In 2.x it wrote to STDOUT at
250
+ debug level. If you read those lines from STDOUT, set `log_to` and `log_level`.
251
+ - `print_urls` no longer prints with `puts`: it logs each URL at info level. The
252
+ level of the default logger is `log_level`, then `LOG_LEVEL`, then info when
253
+ `print_urls` is on, otherwise warn: a level you chose is never lowered.
254
+ - A debug line per request shows the verb, the URL, the status and the time. It
255
+ never shows a query string, a header, a body or a credential.
256
+
257
+ ### The block of `run`
258
+
259
+ `run` with a block yields the response and now returns the `Response`. In 2.x it
260
+ returned the route, and `route.response` was the response. Code that used the
261
+ returned value must use the response.
262
+
263
+ ```ruby
264
+ ApiRecipes.github.users.show('octocat').run { |response| response.code }.class
265
+ # => "ApiRecipes::Response"
266
+ ```
267
+
268
+ ### `verify_with` and the message of the error
269
+
270
+ The message of `ResponseCodeNotAsExpected` no longer contains the response body.
271
+ Read it from `error.response`:
272
+
273
+ ```ruby
274
+ begin
275
+ ApiRecipes.github.users.show('nobody-here').run
276
+ rescue ApiRecipes::ResponseCodeNotAsExpected => e
277
+ e.response.body.to_s
278
+ end
279
+ ```
280
+
281
+ ### Nested endpoints inherit `verify_with`
282
+
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.
286
+
287
+ ### `apis_configs` after the files
288
+
289
+ In 2.x, assigning `apis_configs` after `apis_files_paths` discarded what the
290
+ files had loaded. Now every source is used, in the order they were assigned, and a
291
+ later source replaces an API with the same name. If you assigned `apis_configs` to
292
+ get rid of the files, do not assign the files.
293
+
294
+ ### Endpoints named like a method
295
+
296
+ An endpoint called `with`, `definition`, `authorization`, `basic_auth` or `variables`
297
+ (on an API), or `run`, `url`, `with` or `definition` (on an endpoint), used to be skipped or to
298
+ replace the method. Now no method is generated for it, a warning is logged when the
299
+ configuration is loaded, and the endpoint is reached with `[]`:
300
+
301
+ ```ruby
302
+ ApiRecipes.github[:with].url.to_s
303
+ # => "https://api.github.com/with"
304
+ ```
305
+
306
+ ### Redirects and credentials
307
+
308
+ With `follow`, a redirect to another origin drops the `Authorization` header, the
309
+ header named by `auth.name`, the `Cookie` header and the credential query
310
+ parameter. In 2.x `follow: true` together with a credential sent the credential
311
+ to the other host. Cookies that a server sets during a chain of redirects are not
312
+ carried to the next hop any more (they were with http.rb 5). A page that sets a
313
+ cookie and redirects to itself now ends in the redirect-loop error of http.rb.
314
+
315
+ ### `fill`
316
+
317
+ `fill` calls only public writers. It used to call private ones, and it swallowed
318
+ every error raised by a writer. Make the setters public, and handle the errors you
319
+ expect. Keys that are not plain attribute names are skipped.
320
+
321
+ ### Constants seen by a class that includes `ApiRecipes`
322
+
323
+ A class that includes `ApiRecipes` finds the constants of the gem before the
324
+ top-level constants of your application. In 2.x those names were `Api`,
325
+ `Endpoint`, `Route`, `Response`, `Settings`, `Configuration` and the error
326
+ classes. In 3.0 `Route` and `Settings` are gone, so a top-level `Route` or
327
+ `Settings` of yours is found again. `Error`, `Internals`, `VERSION` and the new
328
+ error classes (`ConfigurationError`, `CredentialOriginMismatch`,
329
+ `InvalidCredential`, `InvalidPathParameter`, `InvalidUrl`, `InvalidVariable`,
330
+ `MissingVariable`, `RecipeFileError`, `UnknownEndpoint`) are new, and hide a
331
+ top-level constant of yours with the same name. Inside the classes that include
332
+ `ApiRecipes`, write it with a leading `::`, for example `::Error`. The
333
+ [README](README.md#good-to-know) lists all the names.
334
+
335
+ ### Other changes in results
336
+
337
+ - The `Response` answers `respond_to?` for the methods it forwards.
338
+ - Serializing an API, an endpoint or a response (`Marshal.dump`, `YAML.dump`,
339
+ `as_json`) raises `TypeError`. Serialize `response.data` or
340
+ `response.body.to_s`.
341
+ - An object of your class that is restored from a serialized form (`Marshal`,
342
+ YAML) has no credential and inherits none.
343
+ - `response.uri` leaves out the credential query parameter when the API declares
344
+ `auth: { type: 'query' }`.
345
+ - `response.request` was removed, because the request holds the credentials that
346
+ were sent. `response.uri` and the other readers stay, and the http.rb response
347
+ is still `response.original_response`.
348
+ - `response.to_s` returns the body, as the http.rb response does. In 2.x it was
349
+ the default text of the object.
350
+ - A redirect to a host with non-ASCII characters needs the `addressable` gem;
351
+ without it the request raises `ApiRecipes::InvalidUrl`.
352
+
353
+ ## 4. What was removed, and what to use instead
354
+
355
+ | Removed | Use |
356
+ | --- | --- |
357
+ | `endpoint.route`, `endpoint.route.fill(object)` | `response.fill(object)` |
358
+ | `Endpoint#name`, `#params`, `#children`, `#api` | `endpoint.definition` (`name`, `full_name`, `path_params`, `endpoints`, `parent`) |
359
+ | `Api#name`, `#configs`, `#base_configs`, `#object` | `api.definition` (`name`, `host`, `timeout`, `endpoints`...) |
360
+ | the error classes `RouteAndResourceNamesClashError`, `MissingRouteAttribute`, `ProvidedObjectNotAsResponseData`, `NoConfigurationGivenForEndpoint` | nothing: nothing raised them, so remove the `rescue` clause that names one |
361
+ | `ApiRecipes::Route` | nothing: a request is sent with `run` |
362
+ | `ApiRecipes::Settings` | nothing: the defaults are in the [options of the README](README.md#api) |
363
+ | `response.request` | `response.uri`, or `response.original_response` for the http.rb response |
364
+ | `ApiRecipes::RouteNameClashWithExistentMethod` | nothing: a name clash is a warning, and the endpoint is reached with `[]` |
365
+ | `ApiRecipes.print_urls` | `config.print_urls = true` inside `ApiRecipes.configure` |
366
+ | `configuration.setup` | nothing: `configure` loads the configuration |
367
+ | the internal methods of the 2.x core (names with `_aprcps_`, `set_authorization_for_api`, `set_basic_auth_for_api`, `copy_global_authorizations_to_api`) | nothing: they were not part of the public interface |
368
+ | `deep_merge`, `deep_symbolize_keys`, `deep_stringify_keys`, `symbolize_keys`, `stringify_keys`, `extract_options!`, `assert_valid_keys` on `Hash` and `Array` | define them in your code, or load ActiveSupport |
369
+ | the patch that let `URI` accept underscores in a host (uri older than 1.0) | nothing: `host: billing_service` still works |
370
+ | Ruby older than 3.3, http.rb 5 | Ruby 3.3 or higher, http.rb 6 |
371
+
372
+ ```ruby
373
+ ApiRecipes.github.definition.endpoints.keys.inspect
374
+ # => "[:users, :repos, :with]"
375
+
376
+ ApiRecipes.github.users.show('octocat').definition.path_params.inspect
377
+ # => "[:login]"
378
+ ```
379
+
380
+ ## 5. What is new
381
+
382
+ You can adopt these when you are ready. The [README](README.md) describes each one.
383
+
384
+ - **`[]`**: every endpoint is reachable by name,
385
+ `ApiRecipes.github[:users][:show, 'octocat']`, whatever the name.
386
+ - **`with`**: options for one chain or one request, without changing anything
387
+ 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.
392
+ - **`auth`**: says where the credential goes: the `Authorization` header, a header
393
+ of your choice or a query parameter.
394
+ - **`ok_code`** accepts a list of statuses, and `response.success?` tells whether a
395
+ response passed the rule of its endpoint.
396
+ - **`definition`**, `routes` and a safe `inspect` on APIs and endpoints.
397
+ - **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`.
401
+
402
+ ## 6. Security
403
+
404
+ 3.0 changes what the gem does for you. What it does:
405
+
406
+ - Path parameters are encoded, and `nil`, empty, `.` and `..` are refused.
407
+ - Variables are checked where they end up: host, path or header.
408
+ - A credential is sent only to the origin it was set for, and a value with a
409
+ control character is refused.
410
+ - Redirects to another origin drop the credentials and cookies.
411
+ - Logs, error messages of the gem and `inspect` never show a credential, a
412
+ header value, a body or a query string. The `to_h` and the JSON of a
413
+ `definition` hide the values of `default_headers`.
414
+ - An API, an endpoint, a response and a definition refuse `Marshal.dump` and
415
+ `YAML.dump`; the first three refuse JSON too.
416
+ - Configuration files are read with `YAML.safe_load`.
417
+
418
+ What stays with your application:
419
+
420
+ - The gem checks the form of a host, not who owns it. Never pass a value chosen by
421
+ an end user as a whole host (`with(host: ...)`, or a variable that is the entire
422
+ host). Check it against a list of hosts you know.
423
+ - `response.original_response` is the raw http.rb response and gives access to the
424
+ request that was sent, headers included. Do not log or serialize it.
425
+ - ERB in a configuration file runs code: load only files you trust.
426
+
427
+ See [Security in the README](README.md#security) for the same list in its place.
428
+
429
+ ## The `api_recipes upgrade` command
430
+
431
+ The gem installs a command that looks for the changes of this guide. It never
432
+ changes a file.
433
+
434
+ $ api_recipes upgrade app lib --config config/apis/github.yml
435
+
436
+ - Every directory or file you list is searched for Ruby code that stops working
437
+ (marked `[breaks]`) and for lines that deserve a look because their result
438
+ changes (marked `[check]`): a manual encoding of a path parameter, a bare
439
+ `rescue`, `follow:`, `response.request`, the removed `Hash` and `Array`
440
+ methods.
441
+ - With `--config FILE`, each configuration file is checked with the rules of
442
+ 3.0 (marked `[config]`). Use the option once for each file.
443
+ - A file that contains ERB is evaluated only with `--erb`, because that runs the
444
+ code in the file. Without it the file is reported and not read.
445
+ - The command prints the file, the line and what to do, never the text of the
446
+ line, which could hold a secret.
447
+
448
+ ```
449
+ app/client.rb:5: [breaks] endpoint.route was removed: use response.fill or endpoint.definition
450
+ app/client.rb:6: [check] a bare rescue now catches ApiRecipes errors too
451
+ config/apis/github.yml: [config] github: unknown option 'hots'
452
+
453
+ (the list of what the command cannot find)
454
+
455
+ 3 findings
456
+ ```
457
+
458
+ A directory is searched for `*.rb` files only; a file you name is read whatever
459
+ its name. The command then prints the list of changes that a search in the text
460
+ cannot find, which you check by hand (this guide has the details of each), and a
461
+ summary line: `Nothing to change`, `1 finding` or `N findings`. The summary line
462
+ is left out when there is no finding and something could not be read.
463
+
464
+ A file or a directory that could not be read (missing, binary, not valid UTF-8,
465
+ or not readable for lack of permission) is reported on the error stream, as
466
+ `<file>: <reason>`, and is not a finding. The exit code is 1 when there is at
467
+ least one finding, even if something could not be read; otherwise it is 2 when
468
+ something could not be read, and 0 when there is nothing to change. It can run
469
+ in a CI.
470
+
471
+ The command does not rewrite code. What matters most depends on values that exist
472
+ only when the program runs, and an automatic rewrite would give a false sense of
473
+ safety. For those, use the warnings that the gem logs.
data/exe/api_recipes ADDED
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require 'api_recipes'
5
+ require 'api_recipes/cli'
6
+ exit ApiRecipes::CLI.run(ARGV)
@@ -1,71 +1,93 @@
1
+ # frozen_string_literal: true
2
+
1
3
  module ApiRecipes
4
+ # One configured api, as ApiRecipes.github, MyClass.github and
5
+ # client.github return it. The subclass generated for the tree adds a
6
+ # method per root endpoint.
7
+ #
8
+ # Every method of this class is a name an endpoint cannot use as a method:
9
+ # the class has only the public methods below, and inside them the only
10
+ # private methods called are raise and block_given?.
2
11
  class Api
12
+ def initialize(context)
13
+ @context = context
14
+ end
3
15
 
4
- attr_accessor :name, :configs, :authorization, :basic_auth
5
- attr_reader :base_configs, :object
6
-
7
- BASE_CONFIGS_KEYS = [:protocol, :host, :port, :api_version, :timeout, :on_bad_code, :mime_type, :verify_with]
8
-
9
- def initialize(name, configs, object)
10
- @name = name
11
- @configs = ApiRecipes::Settings::DEFAULT.merge configs
12
- @object = object
13
-
14
- # Generate some_api.some_endpoint methods
15
- # e.g. github.users
16
- endpoints = @configs[:endpoints]
17
- if endpoints && endpoints.is_a?(Hash)
18
- endpoints.each do |ep_name, params|
19
- unless respond_to? ep_name
20
- # TODO: store endpoints, routes and routes_urls
21
- define_singleton_method ep_name do |*request_params, &block|
22
- # puts "API params: #{params}"
23
- Endpoint.new api: self, name: ep_name, path: path, params: params, request_params: request_params, &block
24
- end
25
- end
26
- end
27
- end
16
+ # The root endpoint called name. With a block, sends its request at once.
17
+ def [](name, *args, &block)
18
+ endpoint = @context.handles.endpoint(@context, @context.definition, @context.base_path, name, args)
19
+ endpoint.run(&block) if block
20
+ endpoint
28
21
  end
29
22
 
30
- def authorization=(auth)
31
- @authorization = auth
23
+ # A copy with options for the chain that follows it only.
24
+ def with(options) = self.class.new(@context.with(options))
25
+
26
+ def definition = @context.definition
32
27
 
33
- # Check if I'm the global api
34
- if global?
35
- # Set authorization also on every "children" (classes that define the same api)
36
- ApiRecipes.set_authorization_for_api auth, name
28
+ # The credential resolved along the chain; nil for the other kind.
29
+ def authorization
30
+ credential = @context.assigned_credential
31
+ credential && credential.kind == :authorization ? credential.value : nil
32
+ end
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.
36
+ 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: ...)'
37
39
  end
40
+
41
+ credential = Internals::Credential.from(:authorization, value)
42
+ Internals::LevelSet.write(@context.owner, @context.level_key) { |level| level.with(credential: credential) }
38
43
  end
39
44
 
40
- def basic_auth=(auth)
41
- @basic_auth = auth
45
+ def basic_auth
46
+ credential = @context.assigned_credential
47
+ credential && credential.kind == :basic_auth ? credential.value : nil
48
+ end
42
49
 
43
- # Check if I'm the global api
44
- if global?
45
- # Set authorization also on every "children" (classes that define the same api)
46
- ApiRecipes.set_basic_auth_for_api auth, name
50
+ 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: ...)'
47
53
  end
48
- end
49
54
 
50
- def base_configs
51
- @configs.select { |c| BASE_CONFIGS_KEYS.include? c }
55
+ credential = Internals::Credential.from(:basic_auth, value)
56
+ Internals::LevelSet.write(@context.owner, @context.level_key) { |level| level.with(credential: credential) }
52
57
  end
53
58
 
54
- private
59
+ # The variable values of the caller's level.
60
+ def variables
61
+ level = Internals::LevelSet.read(@context.owner, @context.level_key)
62
+ (level && level.variables) || {}
63
+ end
55
64
 
56
- def check_route_name_does_not_clash(route_name)
57
- # Check if a method named route_name has already been defined on this object
58
- if respond_to? route_name
59
- raise RouteNameClashWithExistentMethod.new(@name, route_name)
65
+ # Sets the variable values of the caller's level; nil removes them.
66
+ 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: ...)'
60
69
  end
61
- end
62
70
 
63
- def global?
64
- ApiRecipes._aprcps_global_storage[name] == self
71
+ values = Internals::Registry.variable_values(values)
72
+ problems = Internals::Compiler.unknown_variables(values, @context.definition)
73
+ raise ConfigurationError.new(problems) unless problems.empty?
74
+
75
+ Internals::LevelSet.write(@context.owner, @context.level_key) { |level| level.with(variables: values) }
65
76
  end
66
77
 
67
- def path
68
- "/#{configs[:base_url]}/"
78
+ def inspect
79
+ definition = @context.definition
80
+ list = definition.endpoints.empty? ? '' : " endpoints: #{definition.endpoints.keys.join(', ')}"
81
+ "#<ApiRecipes::Api #{definition.name} #{@context.shown_origin}#{list}>"
69
82
  end
83
+
84
+ # An Api holds options that can contain secrets: it is never serialized.
85
+ def marshal_dump = raise(TypeError, 'an ApiRecipes::Api cannot be serialized')
86
+
87
+ def encode_with(_coder) = raise(TypeError, 'an ApiRecipes::Api cannot be serialized')
88
+
89
+ def as_json(*) = raise(TypeError, 'an ApiRecipes::Api cannot be serialized')
90
+
91
+ def to_json(*) = raise(TypeError, 'an ApiRecipes::Api cannot be serialized')
70
92
  end
71
93
  end