api_recipes 3.0.0.beta3 → 3.0.0.beta5

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 +377 -76
  3. data/UPGRADING.md +223 -59
  4. data/lib/api_recipes/cli/calls.rb +27 -0
  5. data/lib/api_recipes/cli/code.rb +153 -0
  6. data/lib/api_recipes/cli/convert/migration.rb +819 -0
  7. data/lib/api_recipes/cli/convert/snippet.rb +67 -0
  8. data/lib/api_recipes/cli/convert.rb +614 -0
  9. data/lib/api_recipes/cli/description.rb +65 -0
  10. data/lib/api_recipes/cli/import/server.rb +20 -9
  11. data/lib/api_recipes/cli/import/writer.rb +16 -4
  12. data/lib/api_recipes/cli/import.rb +23 -9
  13. data/lib/api_recipes/cli/recipes/summary.rb +25 -6
  14. data/lib/api_recipes/cli/recipes.rb +5 -2
  15. data/lib/api_recipes/cli/routes.rb +63 -8
  16. data/lib/api_recipes/cli/tags.rb +19 -0
  17. data/lib/api_recipes/cli/upgrade/fix.rb +206 -0
  18. data/lib/api_recipes/cli/upgrade/project.rb +194 -0
  19. data/lib/api_recipes/cli/upgrade/screen.rb +165 -0
  20. data/lib/api_recipes/cli/upgrade/tree_rules.rb +290 -0
  21. data/lib/api_recipes/cli/upgrade.rb +706 -57
  22. data/lib/api_recipes/cli.rb +171 -17
  23. data/lib/api_recipes/configuration.rb +17 -95
  24. data/lib/api_recipes/endpoint.rb +1 -1
  25. data/lib/api_recipes/internals/compiler.rb +102 -67
  26. data/lib/api_recipes/internals/context.rb +35 -6
  27. data/lib/api_recipes/internals/declaration.rb +17 -15
  28. data/lib/api_recipes/internals/definition.rb +16 -3
  29. data/lib/api_recipes/internals/option_value.rb +92 -0
  30. data/lib/api_recipes/internals/recipe.rb +1 -1
  31. data/lib/api_recipes/internals/recipe_lock.rb +12 -9
  32. data/lib/api_recipes/internals/request.rb +17 -6
  33. data/lib/api_recipes/version.rb +1 -1
  34. data/lib/api_recipes.rb +1 -0
  35. metadata +13 -1
data/UPGRADING.md CHANGED
@@ -1,12 +1,11 @@
1
1
  # Upgrading from 2.x to 3.0
2
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 or in a path. What changes is how the gem behaves around them: it
9
- checks more, it refuses more, and a few results are different.
3
+ Version 3.0 keeps the way you use the gem: `ApiRecipes.configure`, `api :name`
4
+ in a class and the chain `ApiRecipes.github.users.show('octocat').run` work as
5
+ before. The YAML description of an API becomes a portable recipe, with the same
6
+ options and endpoints: `api_recipes convert` moves every description of a
7
+ project to one, as part 2 describes. What changes is how the gem behaves around
8
+ them: it checks more, it refuses more, and a few results are different.
10
9
 
11
10
  This guide has six parts:
12
11
 
@@ -51,8 +50,9 @@ github:
51
50
  cannot upgrade Ruby yet, stay on 2.10.
52
51
  - **http.rb 6.** The gem needs `http` 6.0.4 or higher, below 7. http.rb 5 is no
53
52
  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
53
+ - **Run `api_recipes upgrade`** in the root of your project (see
54
+ [below](#the-api_recipes-upgrade-command)). It finds your code and your
55
+ configuration files by itself, then the removed
56
56
  `route`, `base_configs`, `ApiRecipes.print_urls`, the removed error classes and
57
57
  `Hash` and `Array` methods, and a few lines that deserve a look (manual
58
58
  encoding of path parameters, a bare `rescue`, `follow:`). It then lists what it
@@ -86,21 +86,46 @@ configuration in place. Four things are worth knowing:
86
86
  - A `base_url` with a path placeholder (`:name` or `*name`) is an error. In 2.x
87
87
  it silently became a required parameter of every root endpoint. For a value
88
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:
89
+ - A word in braces, such as `{id}`, in a value of `default_headers` or of
90
+ `default_params`, in the `base_url` or in the `path` of an endpoint is now a
91
+ variable, which a request asks a value for. In 2.x it was sent as text.
92
+ `api_recipes convert` keeps it text: it writes `\{id}` in a path and in the
93
+ `base_url`, and for a header or a parameter it declares a variable whose
94
+ default is the text and uses the variable, as in
92
95
  `variables: { template: { default: '{id}' } }` with the header value
93
96
  `'{template}'`. Braces around anything else, such as a JSON value, are sent
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}`.
99
- - A file that is missing, empty, not valid YAML or not valid UTF-8 raises
100
- `ApiRecipes::RecipeFileError`, which names the file. Files are read with
101
- `YAML.safe_load`: plain values, symbols and aliases are accepted, and nothing
102
- else. A file called `something.recipe.yml` is refused: it is a portable
103
- recipe, and goes in `recipes_paths`.
97
+ as they are. In a path, if you meant a value that changes at every call,
98
+ write a placeholder, `/items/:id`.
99
+ - A recipe that is missing, not valid YAML, not valid UTF-8 or not a recipe
100
+ raises `ApiRecipes::RecipeFileError`, which names the file. A recipe is
101
+ plain YAML: anchors, aliases, tags and the merge key are refused.
102
+
103
+ ### An API is described by a portable recipe
104
+
105
+ 2.x loaded the files of `apis_files_paths`: YAML that the gem evaluated with
106
+ ERB. 3.0 loads only portable recipes, files called `NAME.recipe.yml` that
107
+ hold data and no code, and `apis_configs`. Assigning `apis_files_paths` raises
108
+ `ApiRecipes::Error`, and the message names the command to run:
109
+
110
+ $ bundle exec api_recipes convert
111
+
112
+ In the root of the project, with no argument, it moves every API that a file
113
+ describes to a recipe in `config/api_recipes`, one after the other:
114
+
115
+ - what an `<%= ... %>` tag gave becomes a variable of the recipe, and the code
116
+ of the tag moves, as it is written, to `config.values` in the file that
117
+ calls `ApiRecipes.configure`;
118
+ - `config.recipes_paths` is added, and `config.apis_files_paths` goes with the
119
+ last description;
120
+ - the old file is deleted, and every change is listed.
121
+
122
+ `api_recipes upgrade`, run without arguments in the root of the project,
123
+ offers the same move on a terminal, one API at a time, and shows the files it
124
+ creates, edits and deletes before it asks. A file
125
+ where ERB decides the structure, with `<% if %>` or a tag that gives a name,
126
+ cannot be converted by the command: it says so, and that description is
127
+ rewritten by hand as a recipe. The whole of what `convert` does is in the
128
+ README, under "From a file of your project".
104
129
 
105
130
  ### A class with its own destination needs its own credential
106
131
 
@@ -318,13 +343,6 @@ the nearest, then in the API, and takes the first value it finds. Look at the
318
343
  endpoints that set one of them and also contain other endpoints: those now
319
344
  find it there. `ok_code` is read only on its endpoint.
320
345
 
321
- ### `apis_configs` after the files
322
-
323
- In 2.x, assigning `apis_configs` after `apis_files_paths` discarded what the
324
- files had loaded. Now every source is used, in the order they were assigned, and a
325
- later source replaces an API with the same name. If you assigned `apis_configs` to
326
- get rid of the files, do not assign the files.
327
-
328
346
  ### Endpoints named like a method
329
347
 
330
348
  An endpoint called `with`, `definition`, `authorization`, `basic_auth` or `variables`
@@ -422,11 +440,13 @@ You can adopt these when you are ready. The [README](README.md) describes each o
422
440
  - **Credentials along a chain**: the chain, the object, the class that declares
423
441
  the API, then the whole application. A credential is bound to its origin.
424
442
  - **`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.
443
+ endpoint, the values of `default_headers` and `default_params`, and in
444
+ `protocol`, `port`, `timeout`, `on_bad_code`, `mime_type`, `verb` and
445
+ `ok_code`, with values given at any of those levels.
427
446
  - **`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.
447
+ `default_headers` does for headers. Both can be written on an endpoint: a
448
+ request looks for them on its endpoint, then on each endpoint that contains
449
+ it, then on the API.
430
450
  - **`resource`**: `resource: true` on an endpoint adds `show`, `create`,
431
451
  `update`, `replace` and `delete` under it.
432
452
  - **`auth`**: says where the credential goes: the `Authorization` header, a header
@@ -458,7 +478,8 @@ You can adopt these when you are ready. The [README](README.md) describes each o
458
478
  `definition` hide the values of `default_headers`.
459
479
  - An API, an endpoint, a response and a definition refuse `Marshal.dump` and
460
480
  `YAML.dump`; the first three refuse JSON too.
461
- - Configuration files are read with `YAML.safe_load`.
481
+ - A recipe is read as plain YAML, without anchors, aliases or tags, and is
482
+ never evaluated with ERB.
462
483
 
463
484
  What stays with your application:
464
485
 
@@ -467,44 +488,186 @@ What stays with your application:
467
488
  host). Check it against a list of hosts you know.
468
489
  - `response.original_response` is the raw http.rb response and gives access to the
469
490
  request that was sent, headers included. Do not log or serialize it.
470
- - ERB in a configuration file runs code: load only files you trust.
491
+ - The gem evaluates no ERB. `api_recipes upgrade --erb` and
492
+ `api_recipes routes --erb` do, on the files of a 2.x project that you name:
493
+ that runs the code in them.
471
494
 
472
495
  See [Security in the README](README.md#security) for the same list in its place.
473
496
 
474
497
  ## The `api_recipes upgrade` command
475
498
 
476
- The gem installs a command that looks for the changes of this guide. It never
477
- changes a file.
499
+ The gem installs a command that looks for the changes of this guide. It changes
500
+ a file only when you say yes to a change it shows you. Run it in the root of
501
+ your project, with no argument:
502
+
503
+ $ bundle exec api_recipes upgrade
504
+
505
+ It finds by itself what to check, and says what it checked:
506
+
507
+ - **The Ruby files of the project**, `*.rb` and `*.rake`. It leaves out the
508
+ folders `vendor`, `node_modules`, `tmp`, `log`, `coverage`, `public` and
509
+ `storage` at the top of the project, `node_modules` wherever it is, what
510
+ starts with a dot, and every symbolic link. Code that stops working is marked
511
+ `[breaks]`; a line that deserves a look because its result changes is marked
512
+ `[check]`: a manual encoding of a path parameter, a bare `rescue`, `follow:`,
513
+ `response.request`, the removed `Hash` and `Array` methods.
514
+ - **What a line alone does not tell.** The command also reads each Ruby file
515
+ as a tree, without running it, and finds: a credential assigned in the body
516
+ of a class, through a variable, over two lines or with `send`; a credential
517
+ that is not text; `api :format` and the other names that are already
518
+ methods; a class that gives an API its own `host`, `protocol` or `port`
519
+ and no credential; `apis_configs` assigned after the files; a block passed
520
+ to `run` whose value is used; `request`, `to_s` and `respond_to?` called on
521
+ what `run` returned, whatever the variable is called; and `Error`,
522
+ `VERSION` or the name of an error of the gem written alone in a class that
523
+ includes `ApiRecipes`. A file that is not valid Ruby is read line by line
524
+ only.
525
+ - **The files that describe an API**: the YAML files (`.yml`, `.yaml`, also
526
+ followed by `.erb`) where a name has `endpoints`, each with its options or
527
+ with none, and the files called `NAME.recipe.yml`. Those under `spec`, `test`
528
+ and `features` are fixtures and are left out. Each is checked with the rules
529
+ of 3.0 (marked `[config]`). Two changes that give no error are marked
530
+ `[check]`: `timeout`, `on_bad_code`, `mime_type` or `verify_with` set on an
531
+ endpoint whose inner endpoints do not set it, which now find it there, and
532
+ an endpoint whose name is a method of the object that would have it.
533
+ - **Less noise.** A bare `rescue` or a call to `CGI.escape` is in every
534
+ application. The checks that also match code that has nothing to do with the
535
+ gem are applied only to the files whose code names `ApiRecipes` or calls one
536
+ of your APIs by its name, and the one about the `Hash` methods is left out
537
+ when the project has ActiveSupport.
538
+ - **A file that contains ERB is checked without running its code.** The value
539
+ that a `<%= ... %>` tag gives is not checked, and the command says how many
540
+ it left out; the other values are. A file where a tag gives a name, a
541
+ mapping or whole lines, or where a `<% ... %>` tag decides which lines exist,
542
+ is not guessed: the command says so, and reads it only with `--erb`, which
543
+ evaluates the file. That runs the code in it, and outside your application a
544
+ value read from the environment may be missing.
545
+ - **It gives the code to paste** where what to write is known. The values
546
+ that lines such as `ApiRecipes.print_urls = ...` and
547
+ `ApiRecipes.github.authorization = ...` gave when the application started
548
+ are put together in the whole block of `ApiRecipes.configure`, to paste over
549
+ the one that is there, with the file and its lines. Where what to write
550
+ depends on the code around it, the replacement is shown under the finding.
551
+ The code holds what the line assigned, the value of a credential too, so
552
+ that it works when pasted: `--no-code` leaves it out, as in a CI whose
553
+ output is kept. A line is never printed as it is, and the command copies
554
+ only what it is sure of: one whole expression, with no `if`, `unless`,
555
+ `rescue`, `and` or `or` after it, on a line that is always run.
556
+
557
+ What needs an answer comes last, where the terminal stops: what was checked,
558
+ the changes the command cannot find, the findings, and what to do.
478
559
 
479
- $ api_recipes upgrade app lib --config config/apis/github.yml
560
+ ```
561
+ Checked 214 Ruby files, 6 of them use api_recipes
562
+ Checked 2 configuration files: config/apis/billing.yml, config/apis/github.yml
563
+ app/models/shop.rb:4: declares the api 'shopify', and no configuration file found here describes it
564
+ config/apis/billing.yml: 2 values come from ERB and were not checked
480
565
 
481
- - Every directory or file you list is searched for Ruby code that stops working
482
- (marked `[breaks]`) and for lines that deserve a look because their result
483
- changes (marked `[check]`): a manual encoding of a path parameter, a bare
484
- `rescue`, `follow:`, `response.request`, the removed `Hash` and `Array`
485
- methods.
486
- - With `--config FILE`, each configuration file is checked with the rules of
487
- 3.0 (marked `[config]`). Use the option once for each file.
488
- - A file that contains ERB is evaluated only with `--erb`, because that runs the
489
- code in the file. Without it the file is reported and not read.
490
- - The command prints the file, the line and what to do, never the text of the
491
- line, which could hold a secret.
566
+ What this command cannot find
567
+ (the list of the changes that a search in the text cannot find)
492
568
 
493
- ```
494
569
  app/client.rb:5: [breaks] endpoint.route was removed: use response.fill or endpoint.definition
495
570
  app/client.rb:6: [check] a bare rescue now catches ApiRecipes errors too
496
571
  config/apis/github.yml: [config] github: unknown option 'hots'
497
572
 
498
- (the list of what the command cannot find)
573
+ Code to paste
574
+
575
+ In config/initializers/api_recipes.rb, replace the block of ApiRecipes.configure (lines 1 to 3) with:
576
+
577
+ ApiRecipes.configure do |config|
578
+ config.recipes_paths = Dir['config/api_recipes/*.recipe.yml']
579
+ config.values = {
580
+ github: { authorization: "Bearer #{ENV['GITHUB_TOKEN']}" }
581
+ }
582
+ end
583
+
584
+ Then remove the lines that gave these values: config/initializers/github.rb:1
499
585
 
500
586
  3 findings
587
+
588
+ What to do now
589
+ 1. Fix the 1 line marked breaks: that code stops working, and each line says what to use instead
590
+ 2. Correct what is marked config (1): each is a problem in a file that describes an api
591
+ 3. Read the 1 line marked check: the result changes, and only you can tell whether the code still does what it should. A check line is reported at every run
592
+ 4. Go through what this command cannot find: look in the code for the changes that concern the project
593
+ 5. Run this command again: go on when only check lines that you have read are left
594
+ 6. Start the application and run its tests: ApiRecipes.configure checks the whole configuration when it loads, also what an ERB tag gives, and lists every problem at once
501
595
  ```
502
596
 
503
- A directory is searched for `*.rb` files only; a file you name is read whatever
504
- its name. The command then prints the list of changes that a search in the text
505
- cannot find, which you check by hand (this guide has the details of each), and a
506
- summary line: `Nothing to change`, `1 finding` or `N findings`. The summary line
507
- is left out when there is no finding and something could not be read.
597
+ **On a terminal the command offers to make the changes it is sure of**, one
598
+ at a time. Today they are the values that a line gave when the application
599
+ started: `ApiRecipes.print_urls = ...` moves into the block of
600
+ `ApiRecipes.configure`, and the credentials assigned on `ApiRecipes.NAME`
601
+ become `config.values`. For a `rescue` that names no class, or
602
+ `StandardError`, it offers to put before it `rescue ApiRecipes::Error` with a
603
+ `raise`, which is what 2.x did: the errors of the gem go on to the code that
604
+ called. Answer no when that rescue should handle them from now on. Each change
605
+ is shown as a diff of the files it touches, and is made only when you answer
606
+ `y` or `yes`:
607
+
608
+ ```
609
+ Move print_urls into the block of ApiRecipes.configure
610
+
611
+ config/initializers/api_recipes.rb:1
612
+ ApiRecipes.configure do |config|
613
+ config.recipes_paths = Dir['config/api_recipes/*.recipe.yml']
614
+ + config.print_urls = true
615
+ end
616
+ - ApiRecipes.print_urls = true
617
+
618
+ Make this change? [y/N]
619
+ ```
620
+
621
+ - A change is all the files it needs or none: the line that gave the value
622
+ is taken out together with the line that is added.
623
+ - It touches only files that git has committed as they are now, so that
624
+ `git diff` shows the change and `git checkout` undoes it. Otherwise the
625
+ command says why, and gives the code to paste as before. A file saved while
626
+ the question waits is not written over: the command says so and writes
627
+ nothing. A file whose lines end with CR LF is left to you.
628
+ - A line is taken out only when it is the assignment and nothing else, and
629
+ the value reads nothing that only that place has: a local variable, an
630
+ instance variable, a method of the file, `__FILE__`. A value given after
631
+ other code that may prepare it, as a `require` or `Dotenv.load`, is left to
632
+ you: in the file of the block when that code comes between the block and the
633
+ line, in another file when that file holds any other code, because it runs
634
+ at another time. So are two credentials for one API, for which the code to
635
+ paste gives neither and says to choose, and a block of `configure` that the
636
+ command cannot read whole or that already assigns the value.
637
+ - A rescue is changed only in a file that names the gem. A change you refuse
638
+ stays among the findings, with its code to paste. A `rescue` that comes
639
+ after one that catches the errors of the gem first (`ApiRecipes::Error`,
640
+ `StandardError`, `Exception`, or one that names no class) is not a finding.
641
+ - Given files or folders to check, the command moves no API to a recipe and
642
+ does not take `apis_files_paths` out: it does not know the rest of the
643
+ project. Run it without arguments in the root of the project for those.
644
+ - It asks only when it reads the answers from a terminal and shows the
645
+ results on one. Away from a terminal, as in a CI or with the results sent
646
+ to a file, and with `--no-code`, the command asks nothing and changes
647
+ nothing.
648
+
649
+ The steps at the end are those of what was found: a kind of finding that is
650
+ not there has no step. On a terminal the same results are shown in sections,
651
+ with a colour for each kind of finding and lines that fit the width of the
652
+ window. Away from a terminal, as in a CI or through a pipe, and with
653
+ `NO_COLOR` set, the text is the one above, with no colours.
654
+
655
+ The line about `api :shopify` is said of a declaration in the code when no file
656
+ found in the project describes that API and the code never assigns
657
+ `apis_configs`: look for where its description comes from.
658
+
659
+ To check something else, name it: every directory is searched for `*.rb` and
660
+ `*.rake` files, a file you name is read whatever its name, and `--config FILE`,
661
+ once for each file, checks a description. Every check then applies to every
662
+ file.
663
+
664
+ $ api_recipes upgrade app lib --config config/apis/github.yml
665
+
666
+ The list of the changes that a search in the text cannot find is the same at
667
+ every run: you check them by hand, and this guide has the details of each. The
668
+ summary line is `Nothing to change`, `1 finding` or `N findings`. When it found
669
+ no description of an API it says so instead of `Nothing to change`. The summary
670
+ line is left out when there is no finding and something could not be read.
508
671
 
509
672
  A file or a directory that could not be read (missing, binary, not valid UTF-8,
510
673
  or not readable for lack of permission) is reported on the error stream, as
@@ -513,6 +676,7 @@ least one finding, even if something could not be read; otherwise it is 2 when
513
676
  something could not be read, and 0 when there is nothing to change. It can run
514
677
  in a CI.
515
678
 
516
- The command does not rewrite code. What matters most depends on values that exist
517
- only when the program runs, and an automatic rewrite would give a false sense of
518
- safety. For those, use the warnings that the gem logs.
679
+ The command does not rewrite code: it gives the code to paste where it is sure
680
+ of it. What matters most depends on values that exist only when the program
681
+ runs, and an automatic rewrite would give a false sense of safety. For those,
682
+ use the warnings that the gem logs.
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ApiRecipes
4
+ module CLI
5
+ # How each endpoint of an api is called in Ruby, after the name of the
6
+ # api: `.repos.issues(owner, repo).create`. It is what `routes` lists,
7
+ # made from the compiled tree, so that a comment that shows it is true
8
+ # when it is written.
9
+ module Calls
10
+ # What a call is made of: names of endpoints and of the parameters of
11
+ # their paths, and what joins them. Anything else is not written.
12
+ NAMES = /\A[\w.?!(), \[\]:"-]+\z/
13
+
14
+ # { names of the endpoint, from the api down => the call } for every
15
+ # endpoint that can be called.
16
+ def self.of(definition, level = definition.endpoints, names = [], steps = '', found = {})
17
+ level.each_value do |node|
18
+ here = names + [node.name.to_s]
19
+ call = "#{steps}#{Internals::Definition.step(node.name, node.path_params, names.empty?)}"
20
+ found[here] = call if node.route? && call.match?(NAMES)
21
+ of(definition, node.endpoints, here, call, found)
22
+ end
23
+ found
24
+ end
25
+ end
26
+ end
27
+ end
@@ -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