erb_check 0.1.0

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 ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: e621f0796b2373946ba02f6535c19db84d3d476ba6f2ee191fc21afc1d41d336
4
+ data.tar.gz: 24eb2938209e80d58c5556b609b18be359d5407ad41f74a6d064ee63fef1fc3a
5
+ SHA512:
6
+ metadata.gz: 4d5411619299b513202a54d466ab6205d65d2d77d0918033c39467b832d6d9d6356c43c0b80ee122fe92f50840dc1aedd0d85f7895374bc76c2a835be87465ee
7
+ data.tar.gz: a9f96103adc7ba033ce20150c6c41797cc0c50e0c7e55b4a5f675c80edb45616a3a79bd56b80a3d563bd5cdd1d6de2451328940d66112834519fdb4b5697ead2
data/CHANGELOG.md ADDED
@@ -0,0 +1,37 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0 (2026-12-01)
4
+
5
+ - `check` and `baseline` name the generated files to Sorbet, so `sorbet/config` can ignore `sorbet/erb_check/`,
6
+ and fail when Sorbet doesn't report a type erb_check reveals in every run, instead of passing templates
7
+ Sorbet never saw. They read Sorbet's output the same way whatever `--error-url-base` sorbet/config sets.
8
+ `lsp` reads `sorbet/config` without the `--ignore` patterns that would hide the generated programs.
9
+ - A partial without strict locals that no literal render reaches gets the local an object or collection
10
+ render gives it (`post`, `post_counter`, `post_iteration` in `_post`), so a scaffold's `render @post`
11
+ partial checks clean. A partial with literal callers gets only the locals they pass.
12
+ - `.erbcheck.yml` takes `sorbet:` as a string as well as a list, and `output:` with a trailing slash.
13
+ - `check` says when controllers, helpers, mailers, components or routes changed since the snapshot.
14
+ - `report` lists each render call it couldn't follow, at its file and line.
15
+ - Template errors leave out Sorbet's autocorrect offers; erb_check's own codes print as `[ERB1001]`.
16
+ - Strict locals are read with the installed Rails' pattern; CI runs against Rails 7.1, 7.2, 8.0 and 8.1.
17
+ - A missing `sorbet/config` gets a message naming `tapioca init`; `--help` and `--version` exit 0.
18
+ - The gem supports Rails 7.1 to 8.x (`actionpack`/`actionview` `< 9`).
19
+ - `check` and `baseline` fail when Sorbet exits unsuccessfully without an error they can parse, instead of
20
+ reporting a clean app.
21
+ - An app `helper_method` with a sorbet-runtime `sig` is read where it was written, not from sorbet-runtime's
22
+ wrapper, so it is declared in the view context instead of including its module (which broke on
23
+ `requires_ancestor`).
24
+ - Controller ivar types from Sorbet assignment probes and conservative execution analysis, including
25
+ inherited actions, ordered/conditional callbacks and skips, early responses and explicit renders.
26
+ Render paths union their types; missing facts stay untyped. Snapshot freshness checks, editor
27
+ invalidation on Ruby edits, and per-program coverage in `report` and `ivars.json`.
28
+ - `erb_check snapshot`, `compile`, `check`, `baseline` and `report`.
29
+ - Templates compiled with Rails' Erubi handler or Herb, mapped back byte for byte.
30
+ - View contexts from each controller's real helper chain and inherited `helper_method`s.
31
+ - A render graph that resolves literal renders through controller lookup prefixes, actions and layouts.
32
+ - Strict locals as keyword arguments, typed by `locals_sig`; render calls checked against them, and the
33
+ values a template passes checked against the partial's types.
34
+ - ViewComponent templates in their component class, with slot methods declared.
35
+ - `.erbcheck.yml` contexts, contracts and render wrappers; a fingerprinted baseline.
36
+ - `erb_check lsp`: Sorbet's language server with templates checked as you type, and hover, definition,
37
+ references and completion at template positions.
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Crowd Cow
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,173 @@
1
+ # erb_check
2
+
3
+ Sorbet type-checks Ruby files but not the Ruby in your ERB templates, and it won't
4
+ ([sorbet#8148](https://github.com/sorbet/sorbet/issues/8148)). erb_check compiles each template the way
5
+ Rails does, runs Sorbet over the result with the rest of your app, and reports each error at the
6
+ template's own line and column:
7
+
8
+ ```
9
+ app/views/orders/_summary.html.erb:12:7: Method `totl` does not exist on `Order` https://srb.help/7003
10
+ app/views/admin/_nav.html.erb:161:38: Method `has_role?` does not exist on `NilClass` component of `T.nilable(User)` https://srb.help/7003
11
+ app/controllers/orders_controller.rb:40: Renders app/views/orders/_card.html.erb without required locals order [ERB1001]
12
+ ```
13
+
14
+ ## What it checks
15
+
16
+ - **Each template as the view its controllers really give it.** A snapshot of your booted app records
17
+ every controller's helper modules, route helpers and `helper_method`s, inherited ones included.
18
+ erb_check follows your literal `render` calls the way Rails resolves them, so a partial rendered by
19
+ two controllers is checked against both, and a helper only one of them has is an error in the other.
20
+ - **Strict locals as keyword arguments.** `<%# locals: (order:, compact: false) -%>` becomes the
21
+ method's parameters. Add `<%# locals_sig: order: ::Order, compact: T::Boolean %>` and Sorbet checks
22
+ their types. A literal `render` that omits a required local, or passes one the template doesn't
23
+ declare, is reported at the call. When the call is in a template, each value it passes is checked
24
+ against the partial's `locals_sig` where the value is written.
25
+ - **Partials without strict locals** get the locals their literal callers pass. A partial no literal call
26
+ reaches gets the locals an object or collection render would give it (`post`, `post_counter` and
27
+ `post_iteration` in `_post`), untyped.
28
+ - **ViewComponent templates** run inside their component class, with its slot methods declared.
29
+ - **Controller instance variables** get Sorbet's types when supported assignments and the effective
30
+ callback chain establish them before rendering. Inherited actions, callback order and filters, skips,
31
+ early responses and literal renders participate. Different types reaching one template form a union;
32
+ a missing fact stays `T.untyped`. [Supported cases and limits](docs/controller-ivars.md).
33
+ - **Output identical to Rails.** Templates compile with Rails' own Erubi handler, or with Herb for the
34
+ formats your app compiles with Herb, byte for byte.
35
+
36
+ Locals without a `locals_sig` and controller instance variables without a proven type are `T.untyped`.
37
+ Sorbet checks calls on what it can type: helpers, constants, typed locals and ivars, and chains from typed methods.
38
+
39
+ ## Requirements
40
+
41
+ Rails 7.1 or later (CI runs the specs against 7.1, 7.2, 8.0 and 8.1), Sorbet, Tapioca 0.19.1 or later (for
42
+ your gems' and models' RBIs), and Herb 0.11.
43
+
44
+ ## Setup
45
+
46
+ ```ruby
47
+ # Gemfile
48
+ gem "sorbet-runtime"
49
+
50
+ group :development, :test do
51
+ gem "sorbet", require: false
52
+ gem "tapioca", ">= 0.19.1", require: false
53
+ gem "erb_check", require: false
54
+ end
55
+ ```
56
+
57
+ ```sh
58
+ bundle install
59
+ bundle exec tapioca init # sorbet/config, and RBIs for your gems
60
+ bundle exec tapioca dsl # RBIs for your models, routes and helpers
61
+ echo "--ignore=sorbet/erb_check/" >> sorbet/config
62
+ bundle exec erb_check snapshot
63
+ bundle exec erb_check check
64
+ ```
65
+
66
+ erb_check names its generated files to Sorbet itself, so `erb_check check` and `erb_check lsp` still check
67
+ them, while plain `srb tc` and Sorbet's own editor server skip them instead of reporting template errors
68
+ against generated class names. `check` also adds a file with a deliberate error to every Sorbet run and
69
+ fails if Sorbet doesn't report it, so a setup that leaves the templates unchecked can't pass.
70
+
71
+ ```sh
72
+ bundle exec erb_check snapshot # boots the app once; `check` says when controllers, helpers or components changed since
73
+ bundle exec erb_check check # compiles templates, runs Sorbet, reports new template errors (--all: every one)
74
+ bundle exec erb_check baseline # records today's template errors, so `check` fails only on new ones
75
+ bundle exec erb_check report # what was checked, and the render calls erb_check couldn't follow
76
+ bundle exec erb_check lsp # language server for your editor (below)
77
+ ```
78
+
79
+ The generated code, snapshot and RBIs go to `sorbet/erb_check/`; add it to `.gitignore`. Commit
80
+ `.erbcheck-baseline.json`. In CI, run `tapioca gem`, `tapioca dsl`, `erb_check snapshot` and then
81
+ `erb_check check`, which exits non-zero on new template errors or any Sorbet error elsewhere.
82
+
83
+ ## In your editor
84
+
85
+ `erb_check lsp` runs Sorbet's language server and stands in front of it, so point your editor's Ruby
86
+ *and* ERB files at it in place of `srb tc --lsp`. Ruby files behave exactly as under Sorbet. In a template
87
+ you get Sorbet's errors as you type, before you save, plus hover, go to definition, references and
88
+ completion on the template's Ruby. It needs a snapshot (`erb_check snapshot`) and reads it at start-up;
89
+ restart it after you add a controller, helper or component. Neovim:
90
+
91
+ ```lua
92
+ vim.lsp.config("erb_check", {
93
+ cmd = { "bundle", "exec", "erb_check", "lsp" },
94
+ filetypes = { "ruby", "eruby" },
95
+ root_markers = { ".erbcheck.yml", "Gemfile" },
96
+ })
97
+ vim.lsp.enable("erb_check")
98
+ ```
99
+
100
+ Any client that can run a command for `ruby` and `erb` files works the same way. Sorbet's quick fixes
101
+ aren't offered in templates. A Ruby/RBI edit withdraws inferred controller ivar types for the session;
102
+ save Ruby, refresh the snapshot, and restart the server to recover them.
103
+
104
+ ## Configuration
105
+
106
+ Everything is optional. `.erbcheck.yml`:
107
+
108
+ ```yaml
109
+ roots: [app/views, app/components] # where templates live
110
+ default_context: ApplicationController # the controller a template nothing renders is checked as
111
+ contexts: # templates rendered in ways erb_check can't follow
112
+ "app/views/admin/_partner_nav.html.erb": PartnerController
113
+ contracts: # locals for templates that don't declare them yet
114
+ "app/views/tasks/_detail.html.erb": { locals: "task:, compact: nil", locals_sig: "task: ::Task" }
115
+ render_wrappers: # app methods that render a template from a path and a hash
116
+ - { class: Labels::Printer, method: render, path: path, locals: variables, root: app/lib/labels,
117
+ controller: ApplicationController }
118
+ sorbet: [bundle, exec, srb, tc]
119
+ baseline: .erbcheck-baseline.json
120
+ ```
121
+
122
+ In a template:
123
+
124
+ ```erb
125
+ <%# typed: false %> check this template less strictly
126
+ <%# erb_check: ignore -- reason %> skip it; the reason shows in `erb_check report`
127
+ ```
128
+
129
+ ## Development
130
+
131
+ ```sh
132
+ bundle install
133
+ bundle exec rspec # the end-to-end specs run the real Sorbet binary from sorbet-static
134
+ python3 script/mutate.py # breaks one rule at a time; every row must make a spec fail
135
+ ```
136
+
137
+ ## How it works
138
+
139
+ 1. **Snapshot.** Records each controller's and mailer's lookup prefixes, layout, helper chain and
140
+ `helper_method`s, method source locations, effective callbacks and source digests, the routes, and
141
+ each component's templates and slots. Compiling never boots Rails.
142
+ 2. **Render graph.** Reads every literal `render` in your Ruby and templates. A name without a slash
143
+ resolves through the rendering controller's prefixes, an action renders its own template, and a
144
+ controller that renders a page renders its layout. Unrouted controllers render nothing. A template
145
+ nothing reaches is checked as its directory's controller, marked as a guess.
146
+ 3. **View contexts.** Controllers with the same helpers share one RBI class, so a big app has a few
147
+ dozen contexts.
148
+ 4. **Compile.** Each template becomes a method in a class that inherits its context, once per context
149
+ and set of locals and ivar types. Sorbet probes supported controller assignments in temporary
150
+ copies of their original scope, then validates reusable type expressions; execution analysis
151
+ carries those facts to renders.
152
+ The engines record every Ruby fragment they copy, and erb_check finds each in the
153
+ template's Ruby (whole tokens only), so every copied byte maps back exactly.
154
+ 5. **Diagnostics.** Sorbet's output is mapped through those maps. The same error in several contexts is
155
+ reported once, naming them. An error in code erb_check generated is reported as erb_check's failure,
156
+ and the baseline never hides one.
157
+
158
+ ## Limits
159
+
160
+ - Calls on untyped locals and instance variables aren't checked; type locals with `locals_sig`.
161
+ `report` shows ivar coverage, and `sorbet/erb_check/ivars.json` records each program's inferred types.
162
+ Refresh the snapshot after changing controller code; stale callback metadata cannot establish types.
163
+ - Typed ivars expose existing Sorbet/RBI limitations too: repeated association guards don't narrow a
164
+ subsequent method call, and an RBI may declare a persisted association nullable. These diagnostics
165
+ remain visible; erb_check doesn't strengthen application contracts or suppress them.
166
+ - Values passed from controllers and helpers, and to collections, aren't checked against `locals_sig` yet.
167
+ - Sorbet doesn't narrow on `respond_to?(:helper)` or `defined?(local)`, so a guard written that way
168
+ still reports the call. Declare the local with a default instead.
169
+ - Render targets that aren't literal (`render @post`, `render partial: name`) can't be followed. A partial only
170
+ they reach is checked as its directory's controller, with its object locals untyped; pin its controller in
171
+ `contexts`. A partial that also has a literal caller gets only the locals literal callers pass.
172
+ - In the editor, who renders a template comes from the files on disk when the server started; a render
173
+ call added since is picked up on restart.
@@ -0,0 +1,93 @@
1
+ # Controller instance variables
2
+
3
+ ```ruby
4
+ class OrdersController < ApplicationController
5
+ before_action :load_order, only: :show
6
+
7
+ def show; end
8
+
9
+ private
10
+
11
+ def load_order
12
+ @order = Order.find(params[:id])
13
+ end
14
+ end
15
+ ```
16
+
17
+ If Sorbet knows that `Order.find` returns `Order`, `@order.totl` in `orders/show.html.erb`
18
+ reports an error on `totl` at the template's own position. `@order.total` passes when the
19
+ method exists. No model-name heuristic is involved: missing RBIs mean missing information.
20
+
21
+ ## Where the types come from
22
+
23
+ The Rails snapshot records method source locations, source digests, and the effective
24
+ `_process_action_callbacks` chain. This includes inherited methods and Rails' normalized
25
+ `only`, `except`, prepend, skip, `if` and `unless` rules. It never runs actions or predicates.
26
+ Older snapshots remain usable, but provide no controller ivar facts.
27
+
28
+ Compilation runs Sorbet on temporary controller/source copies containing `T.reveal_type`
29
+ around supported assignment values. The original files are excluded from this probe run,
30
+ so methods are never defined twice. Copies preserve lexical scope and are removed afterward.
31
+ Application files are not edited. Literal types are widened; only reusable nominal types,
32
+ unions, nilable types and supported standard containers are copied into generated declarations.
33
+ Unknown types, including unknown elements inside containers, remain unknown.
34
+ A second run validates distinct type expressions outside the controller's lexical scope, rejecting
35
+ private constants and incomplete generic types before they can cause generated-code errors.
36
+
37
+ Supported values include `T.let`, constructors, model finders and signed method calls when
38
+ Sorbet supplies a type. Their expressions must not depend on local variables or ivars, contain
39
+ blocks or nested control flow, or use SQL projection calls (`select`, `reselect`, `find_by_sql`).
40
+ Projected columns can exist at runtime without appearing in a model's nominal type.
41
+
42
+ The execution analysis tracks assignments through supported branches and calls to known
43
+ controller methods. It records state at each literal `render`, and at implicit rendering after
44
+ the action returns. A `render` does not return from the Ruby method. A callback that performed
45
+ a response halts the remaining callback/action chain. Redirects and `head` do not cause an
46
+ implicit template render. Unconditional `return` can still lead to implicit rendering.
47
+
48
+ All paths and actions reaching a template in one controller contribute to its type. Two known
49
+ types become `T.any(A, B)`, never `T.all`. If any incoming path lacks a fact, that ivar is untyped.
50
+ An explicit nil assignment or a nilable Sorbet return type can introduce nil; an absent assignment
51
+ or unsupported analysis cannot. Guards the analysis cannot refine discard the affected facts
52
+ instead of carrying an unrefined nullable type past them. Authentication helpers keep their
53
+ existing signatures; no directory name implies that `current_user` is present.
54
+
55
+ Controllers with the same helpers share a generated program only when the types used by that
56
+ template also agree. Controller ivars are declared in a synthetic initializer, separate from
57
+ the engine output and source map. ViewComponent initializers and types are untouched.
58
+
59
+ ## Deliberately untyped
60
+
61
+ - A template with no known rendering action, an unknown incoming render edge, or stale source metadata.
62
+ - Partials reached through other templates and layouts. View/helper execution could change state.
63
+ - An ivar that the template itself writes, including compound writes.
64
+ - Facts preceding an unknown controller call, recursive call, block, loop, rescue/ensure, `super`,
65
+ dynamic writer or other unsupported execution. Later straightforward assignments can recover facts.
66
+ - Facts preceding an around callback. If it yields, later callbacks and the action run from unknown
67
+ state. Both explicit and Rails implicit rendering occur inside that yield; a wrapper's own render
68
+ remains an unmodeled edge.
69
+ - Conditional callback writes without a known value on the skipped path. Arbitrary conditions are
70
+ alternatives, not assumed true. Predicate execution can also invalidate facts.
71
+ - Display-only Sorbet types such as shapes, tuples, attached classes and unresolved type members.
72
+
73
+ This is source analysis, not a proof about arbitrary metaprogramming. Runtime method replacement,
74
+ reflective writes hidden inside other objects, and template helpers that secretly mutate controller
75
+ ivars are outside the supported contract. Refresh snapshots after changing callback registrations,
76
+ including registrations in initializers. No controller source or type result cache persists between
77
+ checks. In the editor, Ruby/RBI changes withdraw inferred types until restart with a fresh snapshot.
78
+
79
+ ## Reading the results
80
+
81
+ `erb_check report` counts typed reads per generated program, so the same template checked in two
82
+ different contexts can contribute twice. `sorbet/erb_check/ivars.json` records the template,
83
+ controllers, inferred types, read names (including repeated reads), and counts for each program.
84
+ Component ivars are excluded from these controller counts.
85
+
86
+ Sorbet's ordinary limitations still apply. For example, `if @order.user` does not narrow a
87
+ second `@order.user` call, and a generated association RBI can be broader than a database constraint.
88
+ Those diagnostics are not suppressed. Improve the application/RBI contract or use a checked local;
89
+ erb_check never invents nonnil associations or inserts `T.must` to make them disappear.
90
+
91
+ The integration specs run real Sorbet against planted mistakes, Rails' real callback chain, and
92
+ the editor proxy. `script/mutate.py` independently breaks these rules and must exit successfully
93
+ only when every selected mutation causes a spec failure.
data/exe/erb_check ADDED
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require_relative "../lib/erb_check/cli"
5
+
6
+ exit ErbCheck::CLI.new(ARGV).run
@@ -0,0 +1,173 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "action_view"
4
+ require "action_dispatch/http/mime_type"
5
+ require "herb"
6
+ require "herb/engine"
7
+ require_relative "code_search"
8
+
9
+ module ErbCheck
10
+ # Rails' two ERB handlers, unchanged except that each records the Ruby it copies from the template, so the
11
+ # generated program can be mapped back to it. Erubi is Rails 8.1's handler; Herb is Rails main's
12
+ # (rails/rails#58552), which Rails 8.2 uses for HTML.
13
+ module Backends
14
+ # A code fragment in the engine's output: `code` as the template wrote it, at byte `offset` of `src`.
15
+ Fragment = Data.define(:code, :offset)
16
+
17
+ # `ruby` is the template with everything but the Ruby the engine sees blanked in place, byte for byte, so a
18
+ # fragment is looked for only where this engine reads code.
19
+ Result = Data.define(:src, :fragments, :ruby)
20
+
21
+ # Records the outermost emission call that carries template Ruby. The engines call each other
22
+ # (add_expression_block calls add_expression, which may call add_expression_result), so nested calls
23
+ # are the same fragment.
24
+ module Recording
25
+ CODE_ARGUMENT = {
26
+ add_code: 0, add_expression: 1, add_expression_block: 1, add_expression_block_end: 0,
27
+ add_context_aware_expression: 1, add_expression_result: 0, add_expression_result_escaped: 0,
28
+ }.freeze
29
+
30
+ attr_reader :fragments
31
+
32
+ def initialize(...)
33
+ @fragments = []
34
+ super
35
+ end
36
+
37
+ CODE_ARGUMENT.each do |name, index|
38
+ define_method(name) do |*args, **kwargs, &block|
39
+ return super(*args, **kwargs, &block) if @recording
40
+
41
+ @recording = true
42
+ before = src.bytesize
43
+ result = super(*args, **kwargs, &block)
44
+ code = args[index].to_s.strip
45
+ unless code.empty?
46
+ offset = CodeSearch.find(src.byteslice(before, src.bytesize - before).to_s.b, code.b)
47
+ raise CompileError, "the engine didn't emit #{code.inspect} as written" unless offset
48
+
49
+ fragments << Fragment.new(code:, offset: before + offset)
50
+ end
51
+ result
52
+ ensure
53
+ @recording = false
54
+ end
55
+ end
56
+ end
57
+
58
+ class Erubi < ::ActionView::Template::Handlers::ERB::Erubi
59
+ prepend Recording
60
+ end
61
+
62
+ # Rails main's ActionView::Template::Handlers::ERB::Herb.
63
+ class Herb < ::Herb::Engine
64
+ prepend Recording
65
+
66
+ def initialize(input, properties = {})
67
+ @newline_pending = 0
68
+ properties = properties.dup
69
+ properties[:bufvar] ||= "@output_buffer"
70
+ properties[:preamble] ||= ""
71
+ properties[:postamble] ||= properties[:bufvar].to_s
72
+ properties[:freeze_template_literals] = !::ActionView::Template.frozen_string_literal
73
+ properties[:escapefunc] = ""
74
+ properties[:attrfunc] = nil
75
+ properties[:jsfunc] = nil
76
+ properties[:cssfunc] = nil
77
+ super
78
+ end
79
+
80
+ private
81
+
82
+ def add_text(text)
83
+ return if text.empty?
84
+
85
+ if text == "\n"
86
+ @newline_pending += 1
87
+ else
88
+ with_buffer do
89
+ src << ".safe_append='"
90
+ src << ("\n" * @newline_pending) if @newline_pending.positive?
91
+ src << text.gsub(/['\\]/, '\\\\\&') << @text_end
92
+ end
93
+ @newline_pending = 0
94
+ end
95
+ end
96
+
97
+ def add_expression_block(indicator, code)
98
+ add_expression(indicator, code, block: true)
99
+ end
100
+
101
+ def add_expression(indicator, code, block: false)
102
+ flush_newline_if_pending(src)
103
+
104
+ with_buffer do
105
+ src << ((indicator == "==") || @escape ? ".safe_expr_append=" : ".append=")
106
+ if block
107
+ src << " " << code
108
+ else
109
+ src << "(" << code << trailing_newline(code) << ")"
110
+ end
111
+ end
112
+ end
113
+
114
+ def add_code(code)
115
+ flush_newline_if_pending(src)
116
+ super
117
+ end
118
+
119
+ def add_postamble(_)
120
+ flush_newline_if_pending(src)
121
+ super
122
+ end
123
+
124
+ def flush_newline_if_pending(src)
125
+ return unless @newline_pending.positive?
126
+
127
+ with_buffer { src << ".safe_append='#{"\n" * @newline_pending}" << @text_end }
128
+ @newline_pending = 0
129
+ end
130
+ end
131
+
132
+ # Compiles as ActionView::Template::Handlers::ERB#call does, with the handler Rails picks for the format.
133
+ def self.compile(source, format:, herb_formats:, filename: nil)
134
+ erb = source.b.gsub(::ActionView::Template::Handlers::ERB::ENCODING_TAG, "")
135
+ erb.force_encoding(source.encoding)
136
+ erb.encode!
137
+ erb.chomp! if ::ActionView::Template::Handlers::ERB.strip_trailing_newlines
138
+
139
+ options = {
140
+ escape: ::ActionView::Template::Handlers::ERB.escape_ignore_list.include?(mime_type(format)),
141
+ trim: ::ActionView::Template::Handlers::ERB.erb_trim_mode == "-",
142
+ filename:,
143
+ }
144
+ herb = herb_formats.include?(format.to_s)
145
+ engine = (herb ? Herb : Erubi).new(erb, options)
146
+ Result.new(src: engine.src, fragments: engine.fragments, ruby: herb ? herb_ruby(source) : erubi_ruby(source))
147
+ end
148
+
149
+ def self.herb_ruby(source)
150
+ ruby = ::Herb.extract_ruby(source, semicolons: false, comments: true).b
151
+ ruby.bytesize == source.bytesize ? ruby : source.b
152
+ end
153
+
154
+ # Erubi finds tags with this pattern; group 2 is the code.
155
+ def self.erubi_ruby(source)
156
+ template = source.b
157
+ ruby = template.gsub(/[^\n]/n, " ")
158
+ template.scan(::Erubi::Engine::DEFAULT_REGEXP) do
159
+ match = Regexp.last_match
160
+ next if ["#", "%"].include?(match[1])
161
+
162
+ ruby[match.begin(2), match[2].bytesize] = match[2]
163
+ end
164
+ ruby
165
+ end
166
+
167
+ def self.mime_type(format)
168
+ return unless format
169
+
170
+ ::Mime[format]&.to_s
171
+ end
172
+ end
173
+ end
@@ -0,0 +1,44 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module ErbCheck
6
+ # Known template errors, so CI fails only on new ones. An entry is a template, an error code, the message and
7
+ # the Ruby on the error's line, never a line number, so unrelated edits don't move it. A count per entry
8
+ # catches a second copy of a known error. Compiler failures are never baselined.
9
+ class Baseline
10
+ def initialize(path)
11
+ @path = path
12
+ @entries = File.exist?(path) ? JSON.parse(File.read(path)).fetch("entries") : []
13
+ end
14
+
15
+ def self.key(diagnostic, source_line)
16
+ [diagnostic.path, diagnostic.code, diagnostic.message, source_line.to_s.strip.gsub(/\s+/, " ")]
17
+ end
18
+
19
+ # The diagnostics not covered by the baseline, and the baseline entries nothing matched.
20
+ def compare(diagnostics, lines)
21
+ remaining = @entries.to_h { |e| [e.values_at("path", "code", "message", "line_text"), e["count"]] }
22
+ fresh = diagnostics.reject do |d|
23
+ next false if d.code == Diagnostics::COMPILER_FAILURE
24
+
25
+ key = self.class.key(d, lines.call(d))
26
+ next false unless remaining[key].to_i.positive?
27
+
28
+ remaining[key] -= 1
29
+ end
30
+ stale = remaining.select { |_, count| count.positive? }.keys
31
+ [fresh, stale]
32
+ end
33
+
34
+ def write(diagnostics, lines)
35
+ counts = Hash.new(0)
36
+ diagnostics.reject { |d| d.code == Diagnostics::COMPILER_FAILURE }.each { |d| counts[self.class.key(d, lines.call(d))] += 1 }
37
+ entries = counts.sort.map do |(path, code, message, line_text), count|
38
+ { "path" => path, "code" => code, "message" => message, "line_text" => line_text, "count" => count }
39
+ end
40
+ File.write(@path, JSON.pretty_generate("version" => 1, "entries" => entries) + "\n")
41
+ entries.sum { |e| e["count"] }
42
+ end
43
+ end
44
+ end