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.
@@ -0,0 +1,125 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "digest"
4
+ require "shellwords"
5
+ require "yaml"
6
+
7
+ module ErbCheck
8
+ # `.erbcheck.yml` in the app root. Every key is optional.
9
+ #
10
+ # roots: [app/views, app/components] where templates live
11
+ # output: sorbet/erb_check generated code, RBIs and the snapshot
12
+ # default_context: ApplicationController the controller a template nobody renders is checked as
13
+ # contexts: templates checked as a named controller, by glob
14
+ # "app/views/admin/_partner_nav.html.erb": PartnerController
15
+ # render_wrappers: app methods that render a template under `root`
16
+ # - { class: Labels::Printer, method: render, path: path, locals: variables, root: app/lib/labels,
17
+ # controller: ApplicationController }
18
+ # route_helper_modules: [...] modules declaring route helpers (Tapioca's, when present)
19
+ # sorbet: [bundle, exec, srb, tc] how to run Sorbet
20
+ # baseline: .erbcheck-baseline.json
21
+ # contracts: locals for templates that don't declare them yet, by glob
22
+ # "app/views/tasks/_detail.html.erb": { locals: "task:, compact: nil", locals_sig: "task: ::Task" }
23
+ class Config
24
+ DEFAULTS = {
25
+ "roots" => %w[app/views app/components],
26
+ "output" => "sorbet/erb_check",
27
+ "default_context" => "ApplicationController",
28
+ "contexts" => {},
29
+ "render_wrappers" => [],
30
+ "route_helper_modules" => nil,
31
+ "sorbet" => %w[bundle exec srb tc],
32
+ "baseline" => ".erbcheck-baseline.json",
33
+ "contracts" => {},
34
+ }.freeze
35
+
36
+ # The app's Ruby a snapshot reads: when any of it changes, the snapshot is out of date.
37
+ SNAPSHOT_SOURCES = "{app/{controllers,helpers,mailers,components}/**/*.rb,config/routes.rb,config/routes/**/*.rb}"
38
+
39
+ attr_reader :app_root
40
+
41
+ def self.load(app_root = Dir.pwd)
42
+ path = File.join(app_root, ".erbcheck.yml")
43
+ new(app_root, File.exist?(path) ? (YAML.safe_load_file(path) || {}) : {})
44
+ end
45
+
46
+ def initialize(app_root, values)
47
+ @app_root = app_root
48
+ unknown = values.keys - DEFAULTS.keys
49
+ raise ArgumentError, ".erbcheck.yml: unknown keys #{unknown.join(', ')}" if unknown.any?
50
+
51
+ @values = DEFAULTS.merge(values)
52
+ @values["sorbet"] = Shellwords.split(@values["sorbet"]) if @values["sorbet"].is_a?(String)
53
+ @values["output"] = @values["output"].chomp("/")
54
+ end
55
+
56
+ DEFAULTS.each_key { |key| define_method(key) { @values[key] } }
57
+
58
+ def path(*parts)
59
+ File.join(app_root, *parts)
60
+ end
61
+
62
+ def output_path(*parts)
63
+ path(output, *parts)
64
+ end
65
+
66
+ # Each file in SNAPSHOT_SOURCES and its digest.
67
+ def snapshot_sources
68
+ Dir.glob(SNAPSHOT_SOURCES, base: app_root).sort.to_h { |file| [file, Digest::SHA256.file(path(file)).hexdigest] }
69
+ end
70
+
71
+ # sorbet/config's arguments without the --ignore patterns that hide the generated programs, as arguments that
72
+ # replace the file, and the patterns dropped. Sorbet's language server takes no file arguments and skips files
73
+ # under an ignored directory, so it must read the generated programs from the directory that sorbet/config
74
+ # keeps away from plain `srb tc`.
75
+ def sorbet_config_seeing_output
76
+ file = path("sorbet/config")
77
+ return [[], []] if sorbet.include?("--no-config") || !File.exist?(file)
78
+
79
+ args = File.readlines(file, chomp: true).map(&:strip).reject { |line| line.empty? || line.start_with?("#") }
80
+ kept = []
81
+ dropped = []
82
+ until args.empty?
83
+ arg = args.shift
84
+ value = if arg.start_with?("--ignore=") then arg.delete_prefix("--ignore=")
85
+ elsif arg == "--ignore" && args.first then args.shift
86
+ end
87
+ next kept << arg unless value
88
+
89
+ hiding, rest = value.split(",").partition { |pattern| ignores_output?(pattern) }
90
+ dropped.concat(hiding)
91
+ kept << "--ignore=#{rest.join(',')}" if rest.any?
92
+ end
93
+ [["--no-config", *kept], dropped]
94
+ end
95
+
96
+ # Whether a Sorbet --ignore pattern hides the generated programs. Sorbet matches whole path components of a
97
+ # path relative to its input directory: anywhere in it, or at its start when the pattern begins with "/".
98
+ def ignores_output?(pattern)
99
+ generated = "/#{output}/generated/"
100
+ name = pattern.chomp("/")
101
+ return false if name.empty? || name == "/"
102
+
103
+ pattern.start_with?("/") ? generated.start_with?("#{name}/") : generated.include?("/#{name}/")
104
+ end
105
+
106
+ # Tapioca's route helper modules, when the app has their RBI.
107
+ def route_modules
108
+ return route_helper_modules if route_helper_modules
109
+
110
+ %w[GeneratedUrlHelpersModule GeneratedPathHelpersModule].select do |mod|
111
+ Dir.glob(path("sorbet/rbi/**/*.rbi")).any? { |f| File.basename(f, ".rbi") == mod.gsub(/(?<!^)([A-Z])/, '_\1').downcase }
112
+ end
113
+ end
114
+
115
+ # The `locals` and `locals_sig` the config declares for a template, if any.
116
+ def contract(template_path)
117
+ contracts.find { |glob, _| File.fnmatch?(glob, template_path, File::FNM_PATHNAME | File::FNM_EXTGLOB) }&.last
118
+ end
119
+
120
+ # The controller a template is pinned to in `contexts`, if any.
121
+ def context_override(template_path)
122
+ contexts.find { |glob, _| File.fnmatch?(glob, template_path, File::FNM_PATHNAME | File::FNM_EXTGLOB) }&.last
123
+ end
124
+ end
125
+ end
@@ -0,0 +1,102 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "digest"
4
+
5
+ module ErbCheck
6
+ # The view contexts templates run in. Each controller and mailer has one: ActionView::Base plus its helper
7
+ # chain, route helpers and helper_methods. Controllers with the same helpers share a context, so a template
8
+ # rendered by forty admin controllers is usually checked once.
9
+ class ContextRegistry
10
+ Context = Data.define(:id, :controllers, :helper_modules, :helper_methods)
11
+
12
+ attr_reader :contexts
13
+
14
+ def initialize(snapshot, route_helper_modules: [])
15
+ @route_helper_modules = route_helper_modules
16
+ @controllers = snapshot.fetch("controllers").to_h { |c| [c["name"], c] }
17
+ by_key = Hash.new { |h, k| h[k] = [] }
18
+ @controllers.each_value { |c| by_key[[c["helper_modules"], c["helper_methods"]]] << c["name"] }
19
+ @contexts = by_key.map do |(modules, methods), names|
20
+ id = "C#{Digest::SHA256.hexdigest(JSON.generate([modules, methods]))[0, 10]}"
21
+ Context.new(id:, controllers: names.sort, helper_modules: modules, helper_methods: methods)
22
+ end.sort_by(&:id)
23
+ @by_controller = @contexts.flat_map { |ctx| ctx.controllers.map { |name| [name, ctx] } }.to_h
24
+ end
25
+
26
+ def for_controller(name)
27
+ @by_controller[name]
28
+ end
29
+
30
+ def controller(name)
31
+ @controllers[name]
32
+ end
33
+
34
+ def controllers
35
+ @controllers.values
36
+ end
37
+
38
+ def rbi
39
+ out = +"# typed: true\n# Generated by erb_check from the Rails snapshot. Do not edit.\n\n"
40
+ out << "module ErbCheck; module Contexts; end; module Generated; end; end\n\n"
41
+ @contexts.each { |ctx| out << context_rbi(ctx) << "\n" }
42
+ out
43
+ end
44
+
45
+ private
46
+
47
+ def context_rbi(ctx)
48
+ gem_modules = ctx.helper_methods.filter_map { |m| m["owner"] if gem_owned?(m) }
49
+ lines = ["class ErbCheck::Contexts::#{ctx.id} < ::ActionView::Base"]
50
+ lines << " # #{ctx.controllers.first(3).join(', ')}#{" and #{ctx.controllers.size - 3} more" if ctx.controllers.size > 3}"
51
+ (ctx.helper_modules + @route_helper_modules + gem_modules).uniq.each { |mod| lines << " include ::#{mod}" }
52
+ ctx.helper_methods.reject { |m| gem_owned?(m) }.each { |m| lines.concat(RbiMethod.new(m).lines(indent: " ")) }
53
+ lines << "end"
54
+ lines.join("\n") << "\n"
55
+ end
56
+
57
+ # A helper_method a gem defines (Devise's current_user) keeps the gem RBI's signature when its module is
58
+ # included, rather than copied unsigned.
59
+ def gem_owned?(method)
60
+ method["owner_is_module"] && method["in_app"] == false && method["owner"]
61
+ end
62
+ end
63
+
64
+ # An RBI method declaration from a snapshot entry: a name, runtime parameters and, when sorbet-runtime knew
65
+ # one, a signature.
66
+ class RbiMethod
67
+ def initialize(entry)
68
+ @name = entry["name"]
69
+ @parameters = entry["parameters"] || [%w[rest args], %w[keyrest kwargs], %w[block blk]]
70
+ @signature = entry["signature"]
71
+ end
72
+
73
+ def lines(indent:)
74
+ params = @parameters.each_with_index.map { |(kind, name), i| [kind, name || "_arg#{i}"] }
75
+ out = []
76
+ out << "#{indent}sig { #{sig(params)} }" if @signature && params.all? { |_, name| @signature["params"].key?(name) }
77
+ out << "#{indent}def #{@name}(#{params.filter_map { |kind, name| param(kind, name) }.join(', ')}); end"
78
+ out
79
+ end
80
+
81
+ private
82
+
83
+ def sig(params)
84
+ typed = params.map { |_, name| "#{name}: #{@signature['params'][name]}" }
85
+ returns = @signature["returns"] == "<VOID>" ? "void" : "returns(#{@signature['returns']})"
86
+ typed.empty? ? returns : "params(#{typed.join(', ')}).#{returns}"
87
+ end
88
+
89
+ def param(kind, name)
90
+ case kind
91
+ when "req" then name
92
+ when "opt" then "#{name} = T.unsafe(nil)"
93
+ when "rest" then "*#{name}"
94
+ when "keyreq" then "#{name}:"
95
+ when "key" then "#{name}: T.unsafe(nil)"
96
+ when "keyrest" then "**#{name}"
97
+ when "block" then "&#{name}"
98
+ when "nokey" then "**nil"
99
+ end
100
+ end
101
+ end
102
+ end
@@ -0,0 +1,115 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "action_view"
4
+ require "prism"
5
+
6
+ module ErbCheck
7
+ # What a template says about its inputs and checking, read from its comments:
8
+ #
9
+ # <%# locals: (order:, compact: nil) -%> Rails strict locals
10
+ # <%# locals_sig: order: ::Order, compact: T::Boolean %> their types (or `sig { params(...) }`)
11
+ # <%# typed: false %> this template's Sorbet strictness
12
+ # <%# erb_check: ignore -- why %> skip it, with a reason
13
+ #
14
+ # A declaration in the template wins over one in `.erbcheck.yml`'s `contracts`; one from config has no
15
+ # offset, since no template bytes hold it.
16
+ class Contracts
17
+ # Rails' own pattern, so a declaration counts here exactly when it counts at runtime. Rails 8.1 reads a
18
+ # declaration across lines; earlier versions read one line.
19
+ STRICT_LOCALS = ::ActionView::Template::STRICT_LOCALS_REGEX
20
+ LOCALS_SIG = /<%#\s+locals_sig:\s+(.*?)\s*-?%>/m
21
+ TYPED = /<%#\s+typed:\s+(ignore|false|true|strict)\s*-?%>/
22
+ IGNORE = /<%#\s+(?:erb_check|sorbet_view):\s+ignore\b(?:\s*--\s*(.*?))?\s*-?%>/m
23
+
24
+ Span = Data.define(:offset, :text)
25
+ Param = Data.define(:kind, :name, :default) # kind: :required, :optional, :rest
26
+
27
+ attr_reader :source
28
+
29
+ def initialize(source, external: nil)
30
+ @source = source.b
31
+ @external = external || {}
32
+ end
33
+
34
+ # The strict-locals parameter list, with its byte offset in the template; nil when undeclared.
35
+ def strict_locals
36
+ match = @source.match(STRICT_LOCALS)
37
+ return Span.new(offset: match.begin(1), text: match[1]) if match
38
+
39
+ Span.new(offset: nil, text: @external["locals"].b) if @external["locals"]
40
+ end
41
+
42
+ def params
43
+ span = strict_locals
44
+ return [] unless span
45
+
46
+ node = Prism.parse("def x(#{span.text}); end").value.statements.body.first
47
+ node.parameters ? param_list(node.parameters) : []
48
+ end
49
+
50
+ # The locals_sig parameter types, with their offset; accepts `name: Type, ...` or `sig { params(...) }`.
51
+ def locals_sig
52
+ match = @source.match(LOCALS_SIG)
53
+ return Span.new(offset: nil, text: @external["locals_sig"].b) if !match && @external["locals_sig"]
54
+ return unless match
55
+
56
+ text = match[1]
57
+ offset = match.begin(1)
58
+ if (inner = text.match(/\Asig\s*\{\s*params\((.*)\)\s*\}\z/m))
59
+ offset += inner.begin(1)
60
+ text = inner[1]
61
+ end
62
+ Span.new(offset:, text:)
63
+ end
64
+
65
+ # The names locals_sig types.
66
+ def typed_names
67
+ typed_params.keys
68
+ end
69
+
70
+ # Each typed local's type, as a Span in the template (no offset when the sig came from config).
71
+ def typed_params
72
+ span = locals_sig
73
+ return {} unless span
74
+
75
+ prefix = "params("
76
+ call = Prism.parse("#{prefix}#{span.text})").value.statements.body.first
77
+ hash = call.arguments&.arguments&.first
78
+ return {} unless hash.is_a?(Prism::KeywordHashNode)
79
+
80
+ hash.elements.each_with_object({}) do |el, types|
81
+ next unless el.is_a?(Prism::AssocNode) && el.key.is_a?(Prism::SymbolNode)
82
+
83
+ offset = span.offset && (span.offset + el.value.location.start_offset - prefix.bytesize)
84
+ types[el.key.unescaped] = Span.new(offset:, text: el.value.slice)
85
+ end
86
+ end
87
+
88
+ def typed
89
+ @source[TYPED, 1] || "true"
90
+ end
91
+
92
+ # The reason the template asks to be skipped, "" when none was given, nil when it isn't skipped.
93
+ def ignore_reason
94
+ match = @source.match(IGNORE)
95
+ match && (match[1] || "")
96
+ end
97
+
98
+ private
99
+
100
+ def param_list(node)
101
+ list = []
102
+ node.requireds.each { |p| list << Param.new(kind: :required, name: p.name.to_s, default: nil) }
103
+ node.optionals.each { |p| list << Param.new(kind: :optional, name: p.name.to_s, default: p.value.slice) }
104
+ node.keywords.each do |p|
105
+ list << if p.is_a?(Prism::RequiredKeywordParameterNode)
106
+ Param.new(kind: :required, name: p.name.to_s, default: nil)
107
+ else
108
+ Param.new(kind: :optional, name: p.name.to_s, default: p.value.slice)
109
+ end
110
+ end
111
+ list << Param.new(kind: :rest, name: node.keyword_rest.name.to_s, default: nil) if node.keyword_rest.respond_to?(:name) && node.keyword_rest.name
112
+ list
113
+ end
114
+ end
115
+ end
@@ -0,0 +1,144 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module ErbCheck
6
+ # Sorbet's output with every location in a generated program moved to its template. An error whose range
7
+ # touches no copied template code is erb_check's own fault and is reported as a compiler failure. The same
8
+ # error found in several contexts of one template is reported once, naming the contexts.
9
+ class Diagnostics
10
+ Diagnostic = Data.define(:path, :line, :column, :code, :message, :detail, :contexts) do
11
+ def template?
12
+ !path.end_with?(".rb", ".rbi")
13
+ end
14
+
15
+ def to_s
16
+ location = column ? "#{path}:#{line}:#{column + 1}" : "#{path}:#{line}"
17
+ text = "#{location}: #{message} #{code.match?(/\A\d+\z/) ? "https://srb.help/#{code}" : "[#{code}]"}"
18
+ text += "\n (checked as #{contexts.first(3).join(', ')}#{' and others' if contexts.size > 3})" if contexts.size > 1
19
+ detail.empty? ? text : "#{text}\n#{detail}"
20
+ end
21
+ end
22
+
23
+ HEADER = %r{\A(?<path>[^\s:][^:]*):(?<line>\d+): (?<message>.*?)(?: https://srb\.help/(?<code>\d+))?\z}
24
+ SOURCE_LINE = /\A(\s*\d+\s*\|)(.*)\z/
25
+ AUTOCORRECT = /\A\s*(?:Autocorrect: Use `-a` to autocorrect|\S+:\d+: (?:Replace with|Insert|Delete)\b)/
26
+ COMPILER_FAILURE = "ERB0002"
27
+ UNREACHABLE = "7006"
28
+
29
+ attr_reader :diagnostics, :error_count
30
+
31
+ def initialize(config)
32
+ @config = config
33
+ @maps = {}
34
+ @units = {}
35
+ units_file = config.output_path("units.json")
36
+ JSON.parse(File.read(units_file)).each { |u| @units[u["generated"]] = u } if File.exist?(units_file)
37
+ end
38
+
39
+ def parse(output)
40
+ blocks = []
41
+ output.each_line(chomp: true) do |line|
42
+ if (match = HEADER.match(line)) && match[:code]
43
+ blocks << { header: match, lines: [] }
44
+ elsif line.start_with?("Errors: ") || line == "No errors! Great job."
45
+ @error_count = line[/\d+/].to_i
46
+ elsif blocks.any?
47
+ blocks.last[:lines] << line
48
+ end
49
+ end
50
+ @diagnostics = merge(blocks.map { |block| map_block(block) })
51
+ self
52
+ end
53
+
54
+ private
55
+
56
+ def map_block(block)
57
+ header = block[:header]
58
+ # Sorbet prefixes "./" to the files it finds under `--dir .` when it's also given other inputs.
59
+ path = header[:path].delete_prefix("./")
60
+ line = header[:line].to_i
61
+ columns = caret_columns(block[:lines])
62
+ message = normalize(header[:message])
63
+ detail = generated?(path) ? normalize(map_detail(block[:lines])) : block[:lines].map { |l| without_dot(l) }.join("\n")
64
+ return Diagnostic.new(path:, line:, column: nil, code: header[:code], message:, detail:, contexts: []) unless generated?(path)
65
+
66
+ unit = @units[path]
67
+ template = map_for(path)
68
+ position = columns && template.locate(line, *columns)
69
+ position ||= template.next_code(line) if header[:code] == UNREACHABLE
70
+ unless position
71
+ return Diagnostic.new(path: unit ? unit["template"] : template.template_path, line: 1, column: nil, code: COMPILER_FAILURE,
72
+ message: "erb_check generated code Sorbet rejected (#{path}:#{line}): #{message}",
73
+ detail: "", contexts: [])
74
+ end
75
+
76
+ Diagnostic.new(path: template.template_path, line: position.line, column: position.column, code: header[:code],
77
+ message:, detail:, contexts: unit ? unit["controllers"] : [])
78
+ end
79
+
80
+ # The column range of the first caret line, relative to the source line Sorbet printed above it.
81
+ def caret_columns(lines)
82
+ lines.each_cons(2) do |source, carets|
83
+ prefix = source[SOURCE_LINE, 1] or next
84
+ next unless carets.include?("^")
85
+
86
+ start = carets.index("^") - prefix.length
87
+ finish = carets.rindex("^") - prefix.length
88
+ return [start, finish] if start >= 0
89
+ end
90
+ nil
91
+ end
92
+
93
+ # Related locations ("Got X originating from: path:line:") move to their templates too; source excerpts
94
+ # of generated code are dropped, and so are Sorbet's autocorrect offers, which erb_check can't apply.
95
+ def map_detail(lines)
96
+ lines.filter_map do |text|
97
+ next if text.match?(SOURCE_LINE) || text.match?(/\A\s*\^+\s*\z/) || text.match?(AUTOCORRECT)
98
+
99
+ text = without_dot(text.delete_suffix(" Use `-a` to autocorrect"))
100
+
101
+ text.gsub(%r{(#{Regexp.escape(@config.output)}/generated/\S+?\.rb):(\d+)}) do
102
+ generated, line = Regexp.last_match(1), Regexp.last_match(2).to_i
103
+ map = map_for(generated)
104
+ position = map&.next_code(line, lines: 0)
105
+ position ? "#{map.template_path}:#{position.line}" : "(erb_check generated code)"
106
+ end
107
+ end.join("\n")
108
+ end
109
+
110
+ def without_dot(line) = line.sub(%r{\A(\s*)\./}, '\1')
111
+
112
+ def merge(list)
113
+ list.group_by { |d| [d.path, d.line, d.column, d.code, d.message] }.map do |_, same|
114
+ same.first.with(contexts: same.flat_map(&:contexts).uniq)
115
+ end
116
+ end
117
+
118
+ def normalize(message) = self.class.normalize(message)
119
+
120
+ # Generated class names mean nothing to the reader.
121
+ def self.normalize(message)
122
+ message.gsub(/method `(?:::)?ErbCheck::Generated::L\h+\.check_\w+`/, "the rendered template's `locals_sig`")
123
+ .gsub(/ErbCheck::Generated::T\h+/, "the template").gsub(/ErbCheck::Contexts::C\h+/, "the view context")
124
+ end
125
+
126
+ # The file `erb_check check` adds to each Sorbet run to prove Sorbet checked the generated programs.
127
+ def self.canary?(path)
128
+ File.basename(path).match?(/\Aerb_check-canary-\d+\.rb\z/)
129
+ end
130
+
131
+ def generated?(path)
132
+ path.start_with?("#{@config.output}/generated/") && !self.class.canary?(path)
133
+ end
134
+
135
+ def map_for(path)
136
+ @maps[path] ||= begin
137
+ file = @config.path(path)
138
+ data = JSON.parse(File.read("#{file}.map.json"))
139
+ SourceMap.from_h(data, template_source: File.binread(@config.path(data["template"])),
140
+ generated_source: File.binread(file))
141
+ end
142
+ end
143
+ end
144
+ end
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ErbCheck
4
+ # Every ERB template under the configured roots, relative to the app root.
5
+ class Inventory
6
+ def initialize(app_root, roots)
7
+ @app_root = app_root
8
+ @roots = roots
9
+ end
10
+
11
+ def templates
12
+ @templates ||= @roots.flat_map do |root|
13
+ Dir.glob("#{root}/**/*.erb", base: @app_root).sort.map { |path| TemplateId.parse(path, root:) }
14
+ end
15
+ end
16
+
17
+ def source(template)
18
+ File.read(File.join(@app_root, template.path))
19
+ end
20
+ end
21
+ end