api_recipes 3.0.0.beta2 → 3.0.0.beta4
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.
- checksums.yaml +4 -4
- data/README.md +704 -81
- data/UPGRADING.md +149 -46
- data/lib/api_recipes/api.rb +14 -10
- data/lib/api_recipes/cli/code.rb +153 -0
- data/lib/api_recipes/cli/convert/migration.rb +624 -0
- data/lib/api_recipes/cli/convert/snippet.rb +67 -0
- data/lib/api_recipes/cli/convert.rb +533 -0
- data/lib/api_recipes/cli/recipes/git.rb +197 -0
- data/lib/api_recipes/cli/recipes/lock_file.rb +34 -0
- data/lib/api_recipes/cli/recipes/summary.rb +245 -0
- data/lib/api_recipes/cli/recipes.rb +287 -0
- data/lib/api_recipes/cli/routes.rb +8 -3
- data/lib/api_recipes/cli/upgrade/project.rb +194 -0
- data/lib/api_recipes/cli/upgrade.rb +361 -24
- data/lib/api_recipes/cli.rb +161 -8
- data/lib/api_recipes/configuration.rb +68 -18
- data/lib/api_recipes/endpoint.rb +10 -4
- data/lib/api_recipes/errors.rb +2 -1
- data/lib/api_recipes/internals/compiler.rb +174 -33
- data/lib/api_recipes/internals/context.rb +87 -20
- data/lib/api_recipes/internals/declaration.rb +18 -18
- data/lib/api_recipes/internals/definition.rb +76 -23
- data/lib/api_recipes/internals/level.rb +54 -43
- data/lib/api_recipes/internals/option_value.rb +92 -0
- data/lib/api_recipes/internals/path_template.rb +29 -4
- data/lib/api_recipes/internals/plain_yaml.rb +133 -0
- data/lib/api_recipes/internals/recipe.rb +297 -0
- data/lib/api_recipes/internals/recipe_lock.rb +115 -0
- data/lib/api_recipes/internals/registry.rb +61 -15
- data/lib/api_recipes/internals/request.rb +42 -14
- data/lib/api_recipes/internals/template.rb +17 -5
- data/lib/api_recipes/version.rb +1 -1
- data/lib/api_recipes.rb +8 -3
- metadata +14 -1
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:
|
|
@@ -51,8 +51,9 @@ github:
|
|
|
51
51
|
cannot upgrade Ruby yet, stay on 2.10.
|
|
52
52
|
- **http.rb 6.** The gem needs `http` 6.0.4 or higher, below 7. http.rb 5 is no
|
|
53
53
|
longer supported.
|
|
54
|
-
- **Run `api_recipes upgrade`**
|
|
55
|
-
[below](#the-api_recipes-upgrade-command)). It finds
|
|
54
|
+
- **Run `api_recipes upgrade`** in the root of your project (see
|
|
55
|
+
[below](#the-api_recipes-upgrade-command)). It finds your code and your
|
|
56
|
+
configuration files by itself, then the removed
|
|
56
57
|
`route`, `base_configs`, `ApiRecipes.print_urls`, the removed error classes and
|
|
57
58
|
`Hash` and `Array` methods, and a few lines that deserve a look (manual
|
|
58
59
|
encoding of path parameters, a bare `rescue`, `follow:`). It then lists what it
|
|
@@ -92,10 +93,15 @@ configuration in place. Four things are worth knowing:
|
|
|
92
93
|
`variables: { template: { default: '{id}' } }` with the header value
|
|
93
94
|
`'{template}'`. Braces around anything else, such as a JSON value, are sent
|
|
94
95
|
as they are.
|
|
96
|
+
- A word in braces in the `path` of an endpoint, such as `/items/{id}`, is now a
|
|
97
|
+
variable too, and one that is not declared is an error. In 2.x the braces were
|
|
98
|
+
sent as text. If you meant a value that changes at every call, write a
|
|
99
|
+
placeholder, `/items/:id`. To keep the braces as text, write `\{id}`.
|
|
95
100
|
- A file that is missing, empty, not valid YAML or not valid UTF-8 raises
|
|
96
101
|
`ApiRecipes::RecipeFileError`, which names the file. Files are read with
|
|
97
102
|
`YAML.safe_load`: plain values, symbols and aliases are accepted, and nothing
|
|
98
|
-
else. A file called `something.recipe.yml` is refused
|
|
103
|
+
else. A file called `something.recipe.yml` is refused: it is a portable
|
|
104
|
+
recipe, and goes in `recipes_paths`.
|
|
99
105
|
|
|
100
106
|
### A class with its own destination needs its own credential
|
|
101
107
|
|
|
@@ -111,17 +117,42 @@ api 'github': the credential is bound to "https://api.github.com" but the reques
|
|
|
111
117
|
or set it to nil to send none
|
|
112
118
|
```
|
|
113
119
|
|
|
114
|
-
|
|
120
|
+
Give the credential where the class declares the API:
|
|
115
121
|
|
|
116
122
|
```ruby
|
|
117
123
|
class EnterpriseClient
|
|
118
124
|
include ApiRecipes
|
|
119
|
-
api :github, host: 'ent.example.test'
|
|
125
|
+
api :github, host: 'ent.example.test', authorization: "Bearer #{ENV.fetch('ENTERPRISE_TOKEN')}"
|
|
126
|
+
end
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
### Credentials are given when the application starts
|
|
130
|
+
|
|
131
|
+
In 2.x the usual line was `ApiRecipes.github.authorization = '...'`, and code
|
|
132
|
+
that served several users assigned it before each call. What `ApiRecipes.github`
|
|
133
|
+
and a class use is shared by every thread of the process, so a request could
|
|
134
|
+
leave with the token of another user. Now `authorization=`, `basic_auth=` and
|
|
135
|
+
`variables=` raise `ApiRecipes::Error` on `ApiRecipes.github` and on a class,
|
|
136
|
+
and the message says where the value goes:
|
|
137
|
+
|
|
138
|
+
```ruby
|
|
139
|
+
# the whole application: once, in configure
|
|
140
|
+
ApiRecipes.configure do |config|
|
|
141
|
+
config.values = { github: { authorization: "Bearer #{ENV.fetch('GITHUB_TOKEN')}" } }
|
|
120
142
|
end
|
|
121
143
|
|
|
122
|
-
|
|
144
|
+
# one class: where it declares the API
|
|
145
|
+
class AdminClient
|
|
146
|
+
include ApiRecipes
|
|
147
|
+
api :github, authorization: "Bearer #{ENV.fetch('ADMIN_TOKEN')}"
|
|
148
|
+
end
|
|
149
|
+
|
|
150
|
+
# one user, one request: the chain, or an object of its own
|
|
151
|
+
ApiRecipes.github.with(authorization: "Bearer #{user.token}").users.run
|
|
123
152
|
```
|
|
124
153
|
|
|
154
|
+
The writers still work on an object, as in `client.github.authorization = ...`.
|
|
155
|
+
|
|
125
156
|
### `nil` or an empty path parameter
|
|
126
157
|
|
|
127
158
|
`show(nil)` and `show('')` built the URL of the parent. They now raise
|
|
@@ -236,13 +267,13 @@ The warnings name the endpoint and never the value. `config.upgrade_warnings = f
|
|
|
236
267
|
turns them off. Two more effects: a `:` in a value no longer breaks nested
|
|
237
268
|
endpoints, and a suffix after a placeholder, as in `/:name.json`, is kept.
|
|
238
269
|
|
|
239
|
-
### Credentials on
|
|
270
|
+
### Credentials on an instance take effect
|
|
240
271
|
|
|
241
|
-
In 2.x `
|
|
242
|
-
returned a new object. Now it is
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
272
|
+
In 2.x `client.github.authorization = '...'` was lost, because every call
|
|
273
|
+
returned a new object. Now it is kept for that object. If your code assigned
|
|
274
|
+
one and relied on it having no effect, it now sends a credential. The nearest
|
|
275
|
+
level wins: the chain (`with`), the object, the class that declares the API,
|
|
276
|
+
then the whole application. A credential given as `nil` means "send none".
|
|
246
277
|
|
|
247
278
|
### Logging
|
|
248
279
|
|
|
@@ -278,11 +309,15 @@ rescue ApiRecipes::ResponseCodeNotAsExpected => e
|
|
|
278
309
|
end
|
|
279
310
|
```
|
|
280
311
|
|
|
281
|
-
###
|
|
312
|
+
### An endpoint looks for its options up the tree
|
|
282
313
|
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
314
|
+
In 2.x an endpoint took `timeout`, `on_bad_code` and `mime_type` from the API,
|
|
315
|
+
whatever the endpoint that contained it said, and one written without options
|
|
316
|
+
did not take `verify_with` from its parent. Now an endpoint that does not set
|
|
317
|
+
one of these four options looks for it in the endpoints that contain it, from
|
|
318
|
+
the nearest, then in the API, and takes the first value it finds. Look at the
|
|
319
|
+
endpoints that set one of them and also contain other endpoints: those now
|
|
320
|
+
find it there. `ok_code` is read only on its endpoint.
|
|
286
321
|
|
|
287
322
|
### `apis_configs` after the files
|
|
288
323
|
|
|
@@ -385,19 +420,31 @@ You can adopt these when you are ready. The [README](README.md) describes each o
|
|
|
385
420
|
`ApiRecipes.github[:users][:show, 'octocat']`, whatever the name.
|
|
386
421
|
- **`with`**: options for one chain or one request, without changing anything
|
|
387
422
|
stored: `ApiRecipes.github.with(host: 'github.example.com')`.
|
|
388
|
-
- **Credentials along a chain**: the chain, the object, the class
|
|
389
|
-
|
|
390
|
-
- **`variables`**: `{name}` placeholders in `host`, `base_url
|
|
391
|
-
|
|
423
|
+
- **Credentials along a chain**: the chain, the object, the class that declares
|
|
424
|
+
the API, then the whole application. A credential is bound to its origin.
|
|
425
|
+
- **`variables`**: `{name}` placeholders in `host`, `base_url`, the `path` of an
|
|
426
|
+
endpoint, the values of `default_headers` and `default_params`, and in
|
|
427
|
+
`protocol`, `port`, `timeout`, `on_bad_code`, `mime_type`, `verb` and
|
|
428
|
+
`ok_code`, with values given at any of those levels.
|
|
429
|
+
- **`default_params`**: query parameters sent with every request, as
|
|
430
|
+
`default_headers` does for headers. Both can be written on an endpoint, for
|
|
431
|
+
that endpoint and the ones below it.
|
|
432
|
+
- **`resource`**: `resource: true` on an endpoint adds `show`, `create`,
|
|
433
|
+
`update`, `replace` and `delete` under it.
|
|
392
434
|
- **`auth`**: says where the credential goes: the `Authorization` header, a header
|
|
393
435
|
of your choice or a query parameter.
|
|
394
436
|
- **`ok_code`** accepts a list of statuses, and `response.success?` tells whether a
|
|
395
437
|
response passed the rule of its endpoint.
|
|
396
438
|
- **`definition`**, `routes` and a safe `inspect` on APIs and endpoints.
|
|
397
439
|
- **Validated configuration**, with every problem reported at once.
|
|
398
|
-
- **`config.
|
|
399
|
-
|
|
400
|
-
|
|
440
|
+
- **`config.values`**, which gives each API its credential and the values of
|
|
441
|
+
its variables for the whole application, **`config.upgrade_warnings`** and
|
|
442
|
+
the logging options described above.
|
|
443
|
+
- **The `api_recipes` command**, with `upgrade`, `import`, `routes`, `install`,
|
|
444
|
+
`update` and `check`.
|
|
445
|
+
- **Portable recipes**: recipes written by others, installed with
|
|
446
|
+
`api_recipes install` and loaded with `config.recipes_paths`. See
|
|
447
|
+
[Portable recipes](README.md#portable-recipes) in the README.
|
|
401
448
|
|
|
402
449
|
## 6. Security
|
|
403
450
|
|
|
@@ -429,37 +476,92 @@ See [Security in the README](README.md#security) for the same list in its place.
|
|
|
429
476
|
## The `api_recipes upgrade` command
|
|
430
477
|
|
|
431
478
|
The gem installs a command that looks for the changes of this guide. It never
|
|
432
|
-
changes a file.
|
|
433
|
-
|
|
434
|
-
$ api_recipes upgrade
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
`
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
- The
|
|
446
|
-
|
|
479
|
+
changes a file. Run it in the root of your project, with no argument:
|
|
480
|
+
|
|
481
|
+
$ bundle exec api_recipes upgrade
|
|
482
|
+
|
|
483
|
+
It finds by itself what to check, and says what it checked:
|
|
484
|
+
|
|
485
|
+
- **The Ruby files of the project**, `*.rb` and `*.rake`. It leaves out the
|
|
486
|
+
folders `vendor`, `node_modules`, `tmp`, `log`, `coverage`, `public` and
|
|
487
|
+
`storage` at the top of the project, `node_modules` wherever it is, what
|
|
488
|
+
starts with a dot, and every symbolic link. Code that stops working is marked
|
|
489
|
+
`[breaks]`; a line that deserves a look because its result changes is marked
|
|
490
|
+
`[check]`: a manual encoding of a path parameter, a bare `rescue`, `follow:`,
|
|
491
|
+
`response.request`, the removed `Hash` and `Array` methods.
|
|
492
|
+
- **The files that describe an API**: the YAML files (`.yml`, `.yaml`, also
|
|
493
|
+
followed by `.erb`) where a name has `endpoints`, each with its options or
|
|
494
|
+
with none, and the files called `NAME.recipe.yml`. Those under `spec`, `test`
|
|
495
|
+
and `features` are fixtures and are left out. Each is checked with the rules
|
|
496
|
+
of 3.0 (marked `[config]`).
|
|
497
|
+
- **Less noise.** A bare `rescue` or a call to `CGI.escape` is in every
|
|
498
|
+
application. The checks that also match code that has nothing to do with the
|
|
499
|
+
gem are applied only to the files whose code names `ApiRecipes` or calls one
|
|
500
|
+
of your APIs by its name, and the one about the `Hash` methods is left out
|
|
501
|
+
when the project has ActiveSupport.
|
|
502
|
+
- **A file that contains ERB is checked without running its code.** The value
|
|
503
|
+
that a `<%= ... %>` tag gives is not checked, and the command says how many
|
|
504
|
+
it left out; the other values are. A file where a tag gives a name, a
|
|
505
|
+
mapping or whole lines, or where a `<% ... %>` tag decides which lines exist,
|
|
506
|
+
is not guessed: the command says so, and reads it only with `--erb`, which
|
|
507
|
+
evaluates the file. That runs the code in it, and outside your application a
|
|
508
|
+
value read from the environment may be missing.
|
|
509
|
+
- **It gives the code to paste** where what to write is known. The values
|
|
510
|
+
that lines such as `ApiRecipes.print_urls = ...` and
|
|
511
|
+
`ApiRecipes.github.authorization = ...` gave when the application started
|
|
512
|
+
are put together in the whole block of `ApiRecipes.configure`, to paste over
|
|
513
|
+
the one that is there, with the file and its lines. Where what to write
|
|
514
|
+
depends on the code around it, the replacement is shown under the finding.
|
|
515
|
+
The code holds what the line assigned, the value of a credential too, so
|
|
516
|
+
that it works when pasted: `--no-code` leaves it out, as in a CI whose
|
|
517
|
+
output is kept. A line is never printed as it is, and the command copies
|
|
518
|
+
only what it is sure of: one whole expression, with no `if`, `unless`,
|
|
519
|
+
`rescue`, `and` or `or` after it, on a line that is always run.
|
|
447
520
|
|
|
448
521
|
```
|
|
449
522
|
app/client.rb:5: [breaks] endpoint.route was removed: use response.fill or endpoint.definition
|
|
450
523
|
app/client.rb:6: [check] a bare rescue now catches ApiRecipes errors too
|
|
451
524
|
config/apis/github.yml: [config] github: unknown option 'hots'
|
|
452
525
|
|
|
526
|
+
Checked 214 Ruby files, 6 of them use api_recipes
|
|
527
|
+
Checked 2 configuration files: config/apis/billing.yml, config/apis/github.yml
|
|
528
|
+
app/models/shop.rb:4: declares the api 'shopify', and no configuration file found here describes it
|
|
529
|
+
config/apis/billing.yml: 2 values come from ERB and were not checked
|
|
530
|
+
|
|
531
|
+
Code to paste
|
|
532
|
+
|
|
533
|
+
In config/initializers/api_recipes.rb, replace the block of ApiRecipes.configure (lines 1 to 3) with:
|
|
534
|
+
|
|
535
|
+
ApiRecipes.configure do |config|
|
|
536
|
+
config.apis_files_paths = Dir['config/apis/*.yml']
|
|
537
|
+
config.values = {
|
|
538
|
+
github: { authorization: "Bearer #{ENV['GITHUB_TOKEN']}" }
|
|
539
|
+
}
|
|
540
|
+
end
|
|
541
|
+
|
|
542
|
+
Then remove the lines that gave these values: config/initializers/github.rb:1
|
|
543
|
+
|
|
453
544
|
(the list of what the command cannot find)
|
|
454
545
|
|
|
455
546
|
3 findings
|
|
456
547
|
```
|
|
457
548
|
|
|
458
|
-
|
|
459
|
-
|
|
549
|
+
The line about `api :shopify` is said of a declaration in the code when no file
|
|
550
|
+
found in the project describes that API and the code never assigns
|
|
551
|
+
`apis_configs`: look for where its description comes from.
|
|
552
|
+
|
|
553
|
+
To check something else, name it: every directory is searched for `*.rb` and
|
|
554
|
+
`*.rake` files, a file you name is read whatever its name, and `--config FILE`,
|
|
555
|
+
once for each file, checks a description. Every check then applies to every
|
|
556
|
+
file.
|
|
557
|
+
|
|
558
|
+
$ api_recipes upgrade app lib --config config/apis/github.yml
|
|
559
|
+
|
|
560
|
+
The command then prints the list of changes that a search in the text
|
|
460
561
|
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`.
|
|
462
|
-
|
|
562
|
+
summary line: `Nothing to change`, `1 finding` or `N findings`. When it found
|
|
563
|
+
no description of an API it says so instead of `Nothing to change`. The summary
|
|
564
|
+
line is left out when there is no finding and something could not be read.
|
|
463
565
|
|
|
464
566
|
A file or a directory that could not be read (missing, binary, not valid UTF-8,
|
|
465
567
|
or not readable for lack of permission) is reported on the error stream, as
|
|
@@ -468,6 +570,7 @@ least one finding, even if something could not be read; otherwise it is 2 when
|
|
|
468
570
|
something could not be read, and 0 when there is nothing to change. It can run
|
|
469
571
|
in a CI.
|
|
470
572
|
|
|
471
|
-
The command does not rewrite code
|
|
472
|
-
|
|
473
|
-
|
|
573
|
+
The command does not rewrite code: it gives the code to paste where it is sure
|
|
574
|
+
of it. What matters most depends on values that exist only when the program
|
|
575
|
+
runs, and an automatic rewrite would give a false sense of safety. For those,
|
|
576
|
+
use the warnings that the gem logs.
|
data/lib/api_recipes/api.rb
CHANGED
|
@@ -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
|
|
35
|
-
# writers
|
|
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
|
-
|
|
38
|
-
raise Error,
|
|
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
|
-
|
|
52
|
-
raise Error,
|
|
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 =
|
|
65
|
+
level = @context.own_level
|
|
62
66
|
(level && level.variables) || {}
|
|
63
67
|
end
|
|
64
68
|
|
|
65
|
-
# Sets the variable values of
|
|
69
|
+
# Sets the variable values of an object; nil removes them. See authorization=.
|
|
66
70
|
def variables=(values)
|
|
67
|
-
|
|
68
|
-
raise Error,
|
|
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,153 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module ApiRecipes
|
|
4
|
+
module CLI
|
|
5
|
+
# The code a command gives to paste: how it is shown, and the block of
|
|
6
|
+
# ApiRecipes.configure of a file, which a command gives whole.
|
|
7
|
+
module Code
|
|
8
|
+
# What a terminal would obey, or would show in another order.
|
|
9
|
+
UNSAFE = /[^[:print:]\n\t]|[---]/
|
|
10
|
+
|
|
11
|
+
# Colours for the code shown on a terminal. The text it is given holds
|
|
12
|
+
# nothing a terminal obeys.
|
|
13
|
+
module Paint
|
|
14
|
+
RUBY = /('(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*")|(#[^\n]*)|(\b[a-z_]\w*:(?!:))|((?<![:\w]):[a-z_]\w*)|(\b[A-Z]\w*)|(\b(?:nil|true|false|do|end)\b)/
|
|
15
|
+
|
|
16
|
+
def self.ruby(line)
|
|
17
|
+
line.gsub(RUBY) do
|
|
18
|
+
match = Regexp.last_match
|
|
19
|
+
code = if match[1] then 32
|
|
20
|
+
elsif match[2] then 2
|
|
21
|
+
elsif match[3] || match[4] then 36
|
|
22
|
+
elsif match[5] then 33
|
|
23
|
+
else 35
|
|
24
|
+
end
|
|
25
|
+
"\e[#{code}m#{match[0]}\e[0m"
|
|
26
|
+
end
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
def self.shell(line) = line.sub(/\A(\S+(?: exec \S+)?)/) { "\e[1m#{Regexp.last_match(1)}\e[0m" }
|
|
30
|
+
|
|
31
|
+
# Whether out is a terminal that takes colours.
|
|
32
|
+
def self.on?(out) = out.respond_to?(:tty?) && out.tty? && !ENV.key?('NO_COLOR')
|
|
33
|
+
end
|
|
34
|
+
|
|
35
|
+
# Prints a block of code, indented, in colours on a terminal.
|
|
36
|
+
def self.show(out, lines, kind = :ruby)
|
|
37
|
+
paint = Paint.on?(out)
|
|
38
|
+
out.puts
|
|
39
|
+
lines.each { |line| out.puts(line.empty? ? '' : " #{paint ? Paint.public_send(kind, line) : line}") }
|
|
40
|
+
out.puts
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
# Ruby read as a tree, never run. nil when the text is not valid Ruby.
|
|
44
|
+
def self.tree(text)
|
|
45
|
+
require 'prism'
|
|
46
|
+
result = Prism.parse(text)
|
|
47
|
+
result.success? ? result.value : nil
|
|
48
|
+
end
|
|
49
|
+
|
|
50
|
+
# Every node of a tree for which the block is true.
|
|
51
|
+
def self.nodes(node, found = [], &wanted)
|
|
52
|
+
return found if node.nil?
|
|
53
|
+
|
|
54
|
+
found << node if wanted.call(node)
|
|
55
|
+
node.compact_child_nodes.each { |child| nodes(child, found, &wanted) }
|
|
56
|
+
found
|
|
57
|
+
end
|
|
58
|
+
|
|
59
|
+
# text with each [from, to, replacement] applied; from and to count
|
|
60
|
+
# bytes, as the tree does.
|
|
61
|
+
def self.edited(text, edits)
|
|
62
|
+
bytes = text.b
|
|
63
|
+
edits.sort_by { |from, _, _| -from }.each { |from, to, replacement| bytes[from...to] = replacement.b }
|
|
64
|
+
bytes.force_encoding(Encoding::UTF_8)
|
|
65
|
+
end
|
|
66
|
+
|
|
67
|
+
# The one call `ApiRecipes.configure do |config| ... end` of a text, read
|
|
68
|
+
# from its tree: a comment or a string that looks like one is not one.
|
|
69
|
+
class ConfigureBlock
|
|
70
|
+
# first, last: the lines of the call and of the end of its block,
|
|
71
|
+
# counted from 1. problem: why the block cannot be edited, or nil.
|
|
72
|
+
attr_reader :config, :first, :last, :problem, :call
|
|
73
|
+
|
|
74
|
+
# nil unless text is valid Ruby with exactly one such call.
|
|
75
|
+
def self.in(text)
|
|
76
|
+
tree = text && Code.tree(text)
|
|
77
|
+
calls = tree ? Code.nodes(tree) { |node| configure?(node) } : []
|
|
78
|
+
calls.size == 1 ? new(text, calls.first) : nil
|
|
79
|
+
end
|
|
80
|
+
|
|
81
|
+
def self.configure?(node)
|
|
82
|
+
node.is_a?(Prism::CallNode) && node.name == :configure && node.receiver.is_a?(Prism::ConstantReadNode) &&
|
|
83
|
+
node.receiver.name == :ApiRecipes
|
|
84
|
+
end
|
|
85
|
+
|
|
86
|
+
def initialize(text, call)
|
|
87
|
+
@text = text
|
|
88
|
+
@lines = text.lines
|
|
89
|
+
@call = call
|
|
90
|
+
block = call.block
|
|
91
|
+
parameters = block.is_a?(Prism::BlockNode) && block.parameters.is_a?(Prism::BlockParametersNode) ? block.parameters.parameters : nil
|
|
92
|
+
names = parameters ? parameters.requireds : []
|
|
93
|
+
@first = call.location.start_line
|
|
94
|
+
@last = block.is_a?(Prism::BlockNode) ? block.closing_loc.start_line : @first
|
|
95
|
+
@config = names.size == 1 && names.first.respond_to?(:name) ? names.first.name.to_s : nil
|
|
96
|
+
@statements = block.is_a?(Prism::BlockNode) && block.body.is_a?(Prism::StatementsNode) ? block.body.body : []
|
|
97
|
+
@problem = problem_of(block)
|
|
98
|
+
end
|
|
99
|
+
|
|
100
|
+
# The statements of the block that assign config.name.
|
|
101
|
+
def assignments(name)
|
|
102
|
+
@statements.select do |node|
|
|
103
|
+
node.is_a?(Prism::CallNode) && node.name == :"#{name}=" && node.receiver.is_a?(Prism::LocalVariableReadNode) &&
|
|
104
|
+
node.receiver.name.to_s == @config
|
|
105
|
+
end
|
|
106
|
+
end
|
|
107
|
+
|
|
108
|
+
# Whether config.name is assigned anywhere in the block, also where
|
|
109
|
+
# the block does not always run it.
|
|
110
|
+
def assigned_anywhere?(name)
|
|
111
|
+
Code.nodes(@call.block) { |node| node.is_a?(Prism::CallNode) && node.name == :"#{name}=" }.any?
|
|
112
|
+
end
|
|
113
|
+
|
|
114
|
+
# The lines where the statements of the block start.
|
|
115
|
+
def statement_lines = @statements.map { |node| node.location.start_line }
|
|
116
|
+
|
|
117
|
+
# The line that assigns config.name, counted from 1, or nil.
|
|
118
|
+
def line_of(name) = assignments(name).first&.location&.start_line
|
|
119
|
+
|
|
120
|
+
# The indentation of the statements of the block.
|
|
121
|
+
def indent
|
|
122
|
+
line = @statements.empty? ? nil : @lines[@statements.first.location.start_line - 1]
|
|
123
|
+
line ? line[/\A[ \t]*/] : "#{@lines[@last - 1][/\A[ \t]*/]} "
|
|
124
|
+
end
|
|
125
|
+
|
|
126
|
+
# Where a new statement goes: the byte at which the line of the end
|
|
127
|
+
# of the block starts.
|
|
128
|
+
def end_offset = @call.block.closing_loc.start_offset - @call.block.closing_loc.start_column
|
|
129
|
+
|
|
130
|
+
# The whole call as lines of text, without the lines numbered in
|
|
131
|
+
# without and with added before its end, indented as the block is.
|
|
132
|
+
def lines(added = [], without: [])
|
|
133
|
+
kept = (@first...@last - 1).reject { |index| without.include?(index + 1) }.map { |index| @lines[index].chomp }
|
|
134
|
+
[@lines[@first - 1].chomp, *kept, *added.map { |line| line.empty? ? '' : "#{indent}#{line}" }, @lines[@last - 1].chomp]
|
|
135
|
+
end
|
|
136
|
+
|
|
137
|
+
private
|
|
138
|
+
|
|
139
|
+
def problem_of(block)
|
|
140
|
+
return 'is not given a block with do and end' unless block.is_a?(Prism::BlockNode)
|
|
141
|
+
return 'does not take its one parameter, as in `do |config|`' unless @config
|
|
142
|
+
return 'is written on one line' if @first == @last
|
|
143
|
+
return 'has a rescue or an ensure' unless block.body.nil? || block.body.is_a?(Prism::StatementsNode)
|
|
144
|
+
early = Code.nodes(block) { |node| [Prism::NextNode, Prism::BreakNode, Prism::ReturnNode].any? { |kind| node.is_a?(kind) } }
|
|
145
|
+
return 'can end before its last line, with next, break or return' unless early.empty?
|
|
146
|
+
return 'does not end with a line of its own' unless @lines[@last - 1].strip.match?(/\A(end|\})\z/)
|
|
147
|
+
|
|
148
|
+
nil
|
|
149
|
+
end
|
|
150
|
+
end
|
|
151
|
+
end
|
|
152
|
+
end
|
|
153
|
+
end
|