api_recipes 3.0.0.beta4 → 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.
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
 
@@ -87,21 +86,46 @@ configuration in place. Four things are worth knowing:
87
86
  - A `base_url` with a path placeholder (`:name` or `*name`) is an error. In 2.x
88
87
  it silently became a required parameter of every root endpoint. For a value
89
88
  that changes, declare a [variable](README.md#variables) and write `{name}`.
90
- - A word in braces, such as `{id}`, in a value of `default_headers` is now a
91
- variable, and one that is not declared is an error. To send that text as it
92
- 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
93
95
  `variables: { template: { default: '{id}' } }` with the header value
94
96
  `'{template}'`. Braces around anything else, such as a JSON value, are sent
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}`.
100
- - A file that is missing, empty, not valid YAML or not valid UTF-8 raises
101
- `ApiRecipes::RecipeFileError`, which names the file. Files are read with
102
- `YAML.safe_load`: plain values, symbols and aliases are accepted, and nothing
103
- else. A file called `something.recipe.yml` is refused: it is a portable
104
- 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".
105
129
 
106
130
  ### A class with its own destination needs its own credential
107
131
 
@@ -319,13 +343,6 @@ the nearest, then in the API, and takes the first value it finds. Look at the
319
343
  endpoints that set one of them and also contain other endpoints: those now
320
344
  find it there. `ok_code` is read only on its endpoint.
321
345
 
322
- ### `apis_configs` after the files
323
-
324
- In 2.x, assigning `apis_configs` after `apis_files_paths` discarded what the
325
- files had loaded. Now every source is used, in the order they were assigned, and a
326
- later source replaces an API with the same name. If you assigned `apis_configs` to
327
- get rid of the files, do not assign the files.
328
-
329
346
  ### Endpoints named like a method
330
347
 
331
348
  An endpoint called `with`, `definition`, `authorization`, `basic_auth` or `variables`
@@ -427,8 +444,9 @@ You can adopt these when you are ready. The [README](README.md) describes each o
427
444
  `protocol`, `port`, `timeout`, `on_bad_code`, `mime_type`, `verb` and
428
445
  `ok_code`, with values given at any of those levels.
429
446
  - **`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.
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.
432
450
  - **`resource`**: `resource: true` on an endpoint adds `show`, `create`,
433
451
  `update`, `replace` and `delete` under it.
434
452
  - **`auth`**: says where the credential goes: the `Authorization` header, a header
@@ -460,7 +478,8 @@ You can adopt these when you are ready. The [README](README.md) describes each o
460
478
  `definition` hide the values of `default_headers`.
461
479
  - An API, an endpoint, a response and a definition refuse `Marshal.dump` and
462
480
  `YAML.dump`; the first three refuse JSON too.
463
- - 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.
464
483
 
465
484
  What stays with your application:
466
485
 
@@ -469,14 +488,17 @@ What stays with your application:
469
488
  host). Check it against a list of hosts you know.
470
489
  - `response.original_response` is the raw http.rb response and gives access to the
471
490
  request that was sent, headers included. Do not log or serialize it.
472
- - 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.
473
494
 
474
495
  See [Security in the README](README.md#security) for the same list in its place.
475
496
 
476
497
  ## The `api_recipes upgrade` command
477
498
 
478
- The gem installs a command that looks for the changes of this guide. It never
479
- changes a file. Run it in the root of your project, with no argument:
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:
480
502
 
481
503
  $ bundle exec api_recipes upgrade
482
504
 
@@ -489,11 +511,25 @@ It finds by itself what to check, and says what it checked:
489
511
  `[breaks]`; a line that deserves a look because its result changes is marked
490
512
  `[check]`: a manual encoding of a path parameter, a bare `rescue`, `follow:`,
491
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.
492
525
  - **The files that describe an API**: the YAML files (`.yml`, `.yaml`, also
493
526
  followed by `.erb`) where a name has `endpoints`, each with its options or
494
527
  with none, and the files called `NAME.recipe.yml`. Those under `spec`, `test`
495
528
  and `features` are fixtures and are left out. Each is checked with the rules
496
- of 3.0 (marked `[config]`).
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.
497
533
  - **Less noise.** A bare `rescue` or a call to `CGI.escape` is in every
498
534
  application. The checks that also match code that has nothing to do with the
499
535
  gem are applied only to the files whose code names `ApiRecipes` or calls one
@@ -518,22 +554,28 @@ It finds by itself what to check, and says what it checked:
518
554
  only what it is sure of: one whole expression, with no `if`, `unless`,
519
555
  `rescue`, `and` or `or` after it, on a line that is always run.
520
556
 
521
- ```
522
- app/client.rb:5: [breaks] endpoint.route was removed: use response.fill or endpoint.definition
523
- app/client.rb:6: [check] a bare rescue now catches ApiRecipes errors too
524
- config/apis/github.yml: [config] github: unknown option 'hots'
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.
525
559
 
560
+ ```
526
561
  Checked 214 Ruby files, 6 of them use api_recipes
527
562
  Checked 2 configuration files: config/apis/billing.yml, config/apis/github.yml
528
563
  app/models/shop.rb:4: declares the api 'shopify', and no configuration file found here describes it
529
564
  config/apis/billing.yml: 2 values come from ERB and were not checked
530
565
 
566
+ What this command cannot find
567
+ (the list of the changes that a search in the text cannot find)
568
+
569
+ app/client.rb:5: [breaks] endpoint.route was removed: use response.fill or endpoint.definition
570
+ app/client.rb:6: [check] a bare rescue now catches ApiRecipes errors too
571
+ config/apis/github.yml: [config] github: unknown option 'hots'
572
+
531
573
  Code to paste
532
574
 
533
575
  In config/initializers/api_recipes.rb, replace the block of ApiRecipes.configure (lines 1 to 3) with:
534
576
 
535
577
  ApiRecipes.configure do |config|
536
- config.apis_files_paths = Dir['config/apis/*.yml']
578
+ config.recipes_paths = Dir['config/api_recipes/*.recipe.yml']
537
579
  config.values = {
538
580
  github: { authorization: "Bearer #{ENV['GITHUB_TOKEN']}" }
539
581
  }
@@ -541,10 +583,74 @@ In config/initializers/api_recipes.rb, replace the block of ApiRecipes.configure
541
583
 
542
584
  Then remove the lines that gave these values: config/initializers/github.rb:1
543
585
 
544
- (the list of what the command cannot find)
545
-
546
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
595
+ ```
596
+
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
+
547
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.
548
654
 
549
655
  The line about `api :shopify` is said of a declaration in the code when no file
550
656
  found in the project describes that API and the code never assigns
@@ -557,9 +663,9 @@ file.
557
663
 
558
664
  $ api_recipes upgrade app lib --config config/apis/github.yml
559
665
 
560
- The command then prints the list of changes that a search in the text
561
- cannot find, which you check by hand (this guide has the details of each), and a
562
- summary line: `Nothing to change`, `1 finding` or `N findings`. When it found
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
563
669
  no description of an API it says so instead of `Nothing to change`. The summary
564
670
  line is left out when there is no finding and something could not be read.
565
671
 
@@ -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
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require 'open3'
4
+ require 'digest'
4
5
  require 'tmpdir'
5
6
  require 'pathname'
6
7
  require 'fileutils'
@@ -26,12 +27,38 @@ module ApiRecipes
26
27
  # git does not run a program that the repository names.
27
28
  GIT = ['git', '-c', 'core.fsmonitor=false', '-c', 'core.hooksPath=/dev/null'].freeze
28
29
 
29
- def initialize(result, source, out:, err:, root: '.')
30
+ # Whether the file is what git has in its index and in HEAD. The id
31
+ # of the index and the one of HEAD are compared with the id of the
32
+ # bytes of the file, worked out here: unlike `git status`, this runs
33
+ # no filter that the repository is configured with. The bytes with
34
+ # CR LF read as LF count too, as git writes a file with core.autocrlf.
35
+ # path: where the file is read; git is a block that runs git, in the
36
+ # project, with the arguments it is given.
37
+ def self.as_committed?(file, path, &git)
38
+ staged, listed = git.call('ls-files', '-s', '--', file)
39
+ head, found = git.call('rev-parse', '--verify', '-q', "HEAD:./#{Pathname.new(file).cleanpath}")
40
+ format, known = git.call('rev-parse', '--show-object-format')
41
+ return false unless [listed, found].all? { |status| status&.success? }
42
+
43
+ id = staged.lines.size == 1 ? staged.split[1] : nil
44
+ return false unless id && id == head.strip
45
+
46
+ digest = known&.success? && format.strip == 'sha256' ? Digest::SHA256 : Digest::SHA1
47
+ bytes = File.binread(path)
48
+ [bytes, bytes.gsub("\r\n", "\n")].uniq.any? { |one| digest.hexdigest("blob #{one.bytesize}\0#{one}") == id }
49
+ rescue SystemCallError
50
+ false
51
+ end
52
+
53
+ # written: { file => text } for the files that the same run of the
54
+ # command already changed, when it converts several apis.
55
+ def initialize(result, source, out:, err:, root: '.', written: {})
30
56
  @result = result
31
57
  @source = source
32
58
  @out = out
33
59
  @err = err
34
60
  @root = root
61
+ @written = written
35
62
  @blocking = []
36
63
  @left = []
37
64
  @done = []
@@ -43,6 +70,14 @@ module ApiRecipes
43
70
  # Returns the exit code: 0 when the project was changed, 1 when it was
44
71
  # not, 2 when something could not be written.
45
72
  def call
73
+ return refused unless prepare.empty?
74
+
75
+ finish
76
+ end
77
+
78
+ # Works out every change without writing anything. Returns the
79
+ # reasons why the project cannot be changed: none when it can.
80
+ def prepare
46
81
  @project = Upgrade::Project.new(@root)
47
82
  inside = Pathname.new(File.expand_path(@source)).relative_path_from(Pathname.new(File.expand_path(@root))).to_s
48
83
  @source = inside unless inside.start_with?('..')
@@ -54,9 +89,42 @@ module ApiRecipes
54
89
  plan_verify_with
55
90
  plan_old_description
56
91
  plan_valid
57
- return refused unless @blocking.empty?
92
+ # What the changes were worked out from: a file changed after this
93
+ # is not written over.
94
+ @seen = (@planned.keys | [@source, @lock]).select { |file| File.file?(full(file)) }.to_h { |file| [file, File.binread(full(file))] }
95
+ @absent = [@target, @lock].reject { |file| File.exist?(full(file)) || File.symlink?(full(file)) }
96
+ @blocking
97
+ end
98
+
99
+ # What prepare worked out: the recipe that is created, the files that
100
+ # are edited, with the text they have and the one they get, and the
101
+ # files that are deleted.
102
+ def preview
103
+ lock = Internals::RecipeLock.read(full(@directory))
104
+ entry = Internals::RecipeLock::Entry.new(version: @result.version, source: nil, commit: nil, sha256: Internals::Recipe.digest(@result.text))
105
+ lock_text = Recipes::LockFile.text(lock.entries.merge(@result.name => entry))
106
+ now = File.exist?(full(@lock)) ? File.read(full(@lock)) : nil
107
+ edited = @planned.select { |_, text| text }.to_h { |file, text| [file, [File.read(full(file)), text]] }
108
+ { created: { @target => @result.text }.merge(now ? {} : { @lock => lock_text }),
109
+ edited: now ? { @lock => [now, lock_text] }.merge(edited) : edited,
110
+ deleted: @planned.select { |_, text| text.nil? }.keys }
111
+ end
112
+
113
+ # Makes the changes that prepare worked out. Returns the exit code.
114
+ def finish
115
+ changed = @seen.reject { |file, text| File.file?(full(file)) && File.binread(full(file)) == text }.keys +
116
+ @absent.select { |file| File.exist?(full(file)) || File.symlink?(full(file)) }
117
+ unless changed.empty?
118
+ @err.puts "the project was not changed: #{changed.map { |file| shown(file) }.join(', ')} changed after this command " \
119
+ 'read it. Nothing was written: run the command again'
120
+ return 2
121
+ end
122
+ # Only a file that git had as it was can be changed again by this
123
+ # run as if it were committed: one that had other changes cannot.
124
+ kept = @planned.keys.select { |file| committed?(file) }
58
125
  return 2 unless apply
59
126
 
127
+ @planned.each { |file, text| text && kept.include?(file) ? @written[file] = text : @written.delete(file) }
60
128
  report
61
129
  0
62
130
  end
@@ -116,9 +184,10 @@ module ApiRecipes
116
184
  # Whether git has the file committed as it is now.
117
185
  def committed?(file)
118
186
  return false unless tracked?(file)
187
+ # As this run left it, after a change made when git had it committed.
188
+ return true if @written.key?(file) && File.read(full(file)) == @written[file]
119
189
 
120
- changes, status = git('status', '--porcelain', '--', file)
121
- status&.success? && changes.empty?
190
+ Migration.as_committed?(file, full(file)) { |*arguments| git(*arguments) }
122
191
  end
123
192
 
124
193
  def git_reason(file)
@@ -153,7 +222,7 @@ module ApiRecipes
153
222
  def place_problems
154
223
  directory = full(@directory)
155
224
  @blocking << "#{@target} already exists" if File.exist?(full(@target)) || File.symlink?(full(@target))
156
- @blocking << "#{@directory} is a symbolic link: the recipe would be written outside the project" if File.symlink?(directory)
225
+ @blocking << "#{@directory} is a symbolic link, or is below one: the recipe would be written outside the project" unless inside?(directory)
157
226
  _, ignored = git('check-ignore', '-q', '--', @target)
158
227
  @blocking << "#{@target} would be ignored by git: the recipe would not be committed with the rest" if ignored&.success?
159
228
  lock_problem
@@ -165,6 +234,21 @@ module ApiRecipes
165
234
  @blocking << "#{@result.name} is described in #{also.map { |file| shown(file) }.join(', ')} too: a recipe never takes the place of an api" unless also.empty?
166
235
  end
167
236
 
237
+ # Whether path, or the folder that holds it, is in the project and not
238
+ # below a symbolic link: the nearest part of it that exists is
239
+ # where it is written.
240
+ def inside?(path)
241
+ root = File.expand_path(@root)
242
+ existing = File.expand_path(path)
243
+ existing = File.dirname(existing) until File.exist?(existing) || File.symlink?(existing) || existing == root || existing == File.dirname(existing)
244
+ relative = Pathname.new(existing).relative_path_from(Pathname.new(root)).to_s
245
+ return false if relative.start_with?('..')
246
+
247
+ File.realpath(existing) == (relative == '.' ? File.realpath(root) : File.join(File.realpath(root), relative))
248
+ rescue SystemCallError
249
+ false
250
+ end
251
+
168
252
  # A recipes.lock that is there is rewritten with one more line: it must
169
253
  # be a plain file that reads as a lock.
170
254
  def lock_problem
@@ -204,7 +288,8 @@ module ApiRecipes
204
288
  edits = edits.map { |from, to, added_text| [from, to, added_text.gsub("\n", "\r\n")] } if text.include?("\r\n")
205
289
  @proposal = [text, Code.edited(text, edits)]
206
290
  taken_out = edits.any? { |from, to, _| to > from }
207
- plan(@initializer, @proposal.last, 'recipes_paths and config.values') if taken_out ? removable(@initializer) : addable(@initializer)
291
+ note = "recipes_paths and config.values#{'; apis_files_paths, which loads nothing now, is gone' if @gone}"
292
+ plan(@initializer, @proposal.last, note) if taken_out ? removable(@initializer) : addable(@initializer)
208
293
  end
209
294
 
210
295
  # The lines that give the variables of this api, one variable a line.
@@ -311,6 +396,7 @@ module ApiRecipes
311
396
  covered << found.last
312
397
  end
313
398
  end
399
+ edits, covered = without_dead_assignments(block, given, text, edits, covered)
314
400
  @project.ruby_files.each do |file|
315
401
  @project.text(file).to_s.lines.each_with_index do |line, index|
316
402
  next unless line.include?(name)
@@ -322,6 +408,115 @@ module ApiRecipes
322
408
  edits
323
409
  end
324
410
 
411
+ # When the file that goes was the last one that apis_files_paths
412
+ # loaded, its lines are taken out, if git has the file as it is now;
413
+ # otherwise the person is told, and the lines stay. They stay too when
414
+ # the command cannot tell what the assignment loads.
415
+ def without_dead_assignments(block, given, text, edits, covered)
416
+ return [edits, covered] if given.empty?
417
+ loads = given.map { |node| loads(node.arguments&.arguments&.first) }
418
+ # Gone when nothing it names is left, or when it cannot be read and
419
+ # the project has no other description: never while it names one.
420
+ return [edits, covered] if loads.include?(:something)
421
+ return [edits, covered] unless loads.all?(:nothing) || last_description?
422
+
423
+ lines = text.lines
424
+ whole = given.map do |node|
425
+ first = node.location.start_line
426
+ last = node.location.end_line
427
+ alone = lines[first - 1].b[0...node.location.start_column].strip.empty? && lines[last - 1].b[node.location.end_column..].to_s.strip.empty?
428
+ from = lines[0...first - 1].sum(&:bytesize)
429
+ alone ? [[from, from + lines[first - 1..last - 1].sum(&:bytesize), ''], first..last] : nil
430
+ end
431
+ if whole.all? && committed?(@initializer)
432
+ @gone = true
433
+ return [whole.map(&:first), whole.map(&:last)]
434
+ end
435
+
436
+ @left << "#{block.config}.apis_files_paths, at line #{given.first.location.start_line} of #{shown(@initializer)}, loads no " \
437
+ 'file now: you can take it out'
438
+ [edits, covered]
439
+ end
440
+
441
+ # Whether the project has no other file that describes an api: what
442
+ # apis_files_paths named is then gone, however it was written.
443
+ def last_description?
444
+ others = @project.config_files.reject { |file| file.end_with?(Internals::Recipe::SUFFIX) }
445
+ whole_file? && others.all? { |file| File.expand_path(file, @root) == File.expand_path(@source, @root) }
446
+ end
447
+
448
+ # What value, given to apis_files_paths, loads once the old file is
449
+ # gone: :nothing, :something (a pattern or a list that gives another
450
+ # description of an api), or :unknown when the command cannot tell.
451
+ def loads(value)
452
+ if pattern?(value)
453
+ found = files_of(value)
454
+ return :unknown if found.nil?
455
+
456
+ return found.any? { |file| description?(file) } ? :something : :nothing
457
+ end
458
+ return combined([loads(value.receiver), loads(value.arguments.arguments.first)]) if value.is_a?(Prism::CallNode) && value.name == :+ && value.arguments&.arguments&.size == 1
459
+ return :unknown unless value.is_a?(Prism::ArrayNode) && value.opening_loc&.slice == '['
460
+
461
+ combined(value.elements.map do |element|
462
+ if written?(element) then named(element)
463
+ else loads(element.is_a?(Prism::SplatNode) ? element.expression : element)
464
+ end
465
+ end)
466
+ end
467
+
468
+ # What one file named in a list gives once the old file is gone.
469
+ def named(element)
470
+ return :nothing if element.slice.include?(File.basename(@source))
471
+
472
+ path = written_path(element)
473
+ return :unknown unless path
474
+
475
+ description?(path) ? :something : :nothing
476
+ end
477
+
478
+ # Whether the file describes an api. One that cannot be read is
479
+ # taken as one: the command does not say that it loads nothing.
480
+ def description?(path)
481
+ return false unless File.file?(path)
482
+
483
+ Convert.shape(File.read(path)).values.any? { |options| options.is_a?(Hash) }
484
+ rescue Refused, Psych::Exception, SystemCallError, ArgumentError, EncodingError
485
+ true
486
+ end
487
+
488
+ def combined(states)
489
+ return :something if states.include?(:something)
490
+
491
+ states.all?(:nothing) ? :nothing : :unknown
492
+ end
493
+
494
+ # The files that a pattern of Dir finds now, without the recipes and
495
+ # the file that goes; nil when its folder is not written out.
496
+ def files_of(pattern)
497
+ arguments = pattern.arguments&.arguments
498
+ path = arguments&.size == 1 ? written_path(arguments.first) : nil
499
+ return nil unless path
500
+
501
+ Dir.glob(path).select { |file| File.file?(file) }.reject do |file|
502
+ file.end_with?(Internals::Recipe::SUFFIX) || File.expand_path(file) == File.expand_path(full(@source))
503
+ end
504
+ end
505
+
506
+ # The path that node gives, when it is written with text only: 'a/*.yml',
507
+ # File.expand_path('a/*.yml', __dir__), Rails.root.join('a', '*.yml').
508
+ def written_path(node)
509
+ return File.expand_path(node.unescaped, @root) if node.is_a?(Prism::StringNode)
510
+ return nil unless written?(node)
511
+
512
+ texts = node.arguments.arguments.select { |one| one.is_a?(Prism::StringNode) }.map(&:unescaped)
513
+ if node.name == :expand_path
514
+ texts.size == 1 && node.arguments.arguments.size == 2 ? File.expand_path(texts.first, File.dirname(full(@initializer))) : nil
515
+ elsif node.receiver.is_a?(Prism::CallNode) && node.receiver.name == :root && node.receiver.receiver.is_a?(Prism::ConstantReadNode) && node.receiver.receiver.name == :Rails
516
+ File.join(File.expand_path(@root), *texts)
517
+ end
518
+ end
519
+
325
520
  # Whether value, given to apis_files_paths, names the file called
326
521
  # name. :none when it does not; [edit, lines] to take out the one
327
522
  # element that does; nil when the command cannot read value.