super-slim 3.4.1 → 3.5.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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: dc9a3f9a78ca93e94080ea623bc6f9a3a52e184148488861b81b53118d1a794a
4
- data.tar.gz: ee5e380942cf49f07d8346d7901b4e13b51a5a992a7b5715dc4e4de73a207829
3
+ metadata.gz: 2a4173bef747a6dd40e852a6247cbe0060838b637edb0268faaaaa6c2ba047f0
4
+ data.tar.gz: 12c36082a6c21e85e2021e892ff89b9d974c460bf63adf9a591f2b0ae71e09f6
5
5
  SHA512:
6
- metadata.gz: 6597c277f4ab79f1c662e45bc705e0a7ede102ebd391b1cf5a130924735c78d7de9df6089f777c6b7179f767af39f0b5f9ef64df1693ed26c6316dc35374a4e9
7
- data.tar.gz: 6f6ccfc27211da2295ed4273e10b84a867f18c1763d73c583e4f71fe90a15a837d8496fc174145bda5de14aabe71f84d0dc1faebb7b76536d6460c846497703e
6
+ metadata.gz: dbc8c86e31f77f5eb938395563215410dc339fda9dc08114961ee8c371ff60171094ac2fb0df9be277d5b5c073ba69c4cc5b29914738ee53e21021b5dfcbff7c
7
+ data.tar.gz: 2f89d6ca844580be8eb7ae0b7ffe1b8568c8757c6d1f7fe57f0e0106e8a6e954ecab1f9a72f6278005767514d433df8b6242656ca8f6b13db79dee417e237943
data/CHANGELOG.md CHANGED
@@ -2,6 +2,25 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [3.5.0] — 2026-11-08
6
+
7
+ Six lint rules and a page that documents every rule. Four of the new rules are on by default, so `super-slim lint` may
8
+ report lines it passed before.
9
+
10
+ **New**
11
+ - The website gives each lint rule its own entry: why it exists, a flagged and a clean example, its settings with
12
+ their defaults, and whether `super-slim format` fixes it. `super-slim lint` prints the link to each rule it reports,
13
+ on stderr.
14
+ - `AnchorHref` also flags `href="#"` and `javascript:` URLs, links that stand in for a button.
15
+ - `UnusedLocals`, on by default, flags a local declared in `/# locals:` that the partial never reads. The shorthand
16
+ `render "card", post:` counts as a read; a template that reads `local_assigns` is left alone.
17
+ - `SoleNestedConditional`, `NegatedIfElseCondition` and `UnlessElse`, on by default, flag an `if` alone inside
18
+ another, `- if !x` with an `else`, and `- unless` with an `else`: RuboCop's cops for these can't see `-` lines.
19
+ - `InlineEventHandlers`, off by default, flags `onclick`, `onchange` and the other `on*` attributes, which a strict
20
+ Content Security Policy blocks.
21
+ - `DatabaseQueries`, off by default, flags `where`, `find_by`, `pluck`, `exists?` and the like, and `Model.all`,
22
+ `Model.order` and the like, written in a template.
23
+
5
24
  ## [3.4.1] — 2026-11-07
6
25
 
7
26
  One fix: `super-slim format` no longer writes `-` lines that `super-slim lint` flags.
@@ -247,7 +266,8 @@ renders what Slim 5 renders with `format: :html, sort_attrs: false`, byte for by
247
266
  - Ruby 3.3 or later, every Ruby still maintained, Rails 8.0 or 8.1 for the railtie, and strscan 3.1.1 or later,
248
267
  newer than the one Ruby 3.3 ships.
249
268
 
250
- [Unreleased]: https://github.com/levups/super-slim/compare/v3.4.1...HEAD
269
+ [Unreleased]: https://github.com/levups/super-slim/compare/v3.5.0...HEAD
270
+ [3.5.0]: https://github.com/levups/super-slim/compare/v3.4.1...v3.5.0
251
271
  [3.4.1]: https://github.com/levups/super-slim/compare/v3.4.0...v3.4.1
252
272
  [3.4.0]: https://github.com/levups/super-slim/compare/v3.3.0...v3.4.0
253
273
  [3.3.0]: https://github.com/levups/super-slim/compare/v3.2.2...v3.3.0
data/README.md CHANGED
@@ -46,6 +46,16 @@ Rails then renders every `.slim` view with SuperSlim, and the digest of a `cache
46
46
  renders changes. A partial whose name is computed needs a `/# Template Dependency: orders/line` comment, as in ERB.
47
47
  There is nothing to configure. Rails itself is optional, and SuperSlim is tested on Rails 8.0 and later.
48
48
 
49
+ To keep Slim as your engine and use only the [linter](#linter), the [formatter](#formatter) or the
50
+ [RuboCop plugin](#rubocop-plugin), add SuperSlim with `require: false`. Rails then never loads it and goes on
51
+ rendering with Slim, while `super-slim lint`, `super-slim format` and `rubocop` still find it:
52
+
53
+ ```ruby
54
+ gem "super-slim", require: false
55
+ ```
56
+
57
+ They read templates as SuperSlim does, [additions](#additions-to-slim) included, which Slim can't render.
58
+
49
59
  Without Rails, `SuperSlim.compile` turns a template into Ruby code, which you evaluate where the template's
50
60
  variables and methods are defined:
51
61
 
@@ -202,20 +212,24 @@ linters, so most will look familiar:
202
212
  |---|---|---|
203
213
  | Indentation, Tab, TrailingWhitespace, EmptyLines, TrailingBlankLines, ControlStatementSpacing, RedundantDiv | slim-lint (`super-slim format` fixes them) | on |
204
214
  | LineLength (`max: 120`), CommentControlStatement, EmptyControlStatement, ConsecutiveControlStatements (`max: 2`), TagCase | slim-lint | on |
215
+ | SoleNestedConditional, NegatedIfElseCondition, UnlessElse (conditionals spread over `-` lines, out of the RuboCop plugin's reach) | RuboCop | on |
205
216
  | InstanceVariables (in partials) | haml-lint, Rails conventions | on |
206
217
  | StrictLocals (partials declare `/# locals:`) | Rails 7.1 strict locals | off |
207
- | DuplicateId, ImageAlt, IframeTitle, AnchorHref, NestedLinks, PositiveTabindex, BooleanAttributeValue, AriaBooleanValue (`aria-*=true` renders no value, `aria-*=false` no attribute), AriaRole, AriaAttribute | Herb, eslint-plugin-jsx-a11y | on |
208
- | ButtonType, InlineStyles | eslint-plugin-react, haml-lint | off |
218
+ | UnusedLocals (a local declared in `/# locals:` that the partial never reads) | Rails 7.1 strict locals | on |
219
+ | DuplicateId, ImageAlt, IframeTitle, AnchorHref (also `href="#"` and `javascript:`), NestedLinks, PositiveTabindex, BooleanAttributeValue, AriaBooleanValue (`aria-*=true` renders no value, `aria-*=false` no attribute), AriaRole, AriaAttribute | Herb, eslint-plugin-jsx-a11y | on |
220
+ | ButtonType, InlineStyles, InlineEventHandlers (`onclick` and other `on*` attributes) | eslint-plugin-react, haml-lint | off |
209
221
  | DeprecatedClasses (`classes: {old: new}`, `old-*: new-*` for a prefix), DeprecatedAttributes (`attributes: {old: new}`), both with `preset: bootstrap5` | erb_lint | on, but empty |
210
222
  | UnescapedOutput (`==`, `html_safe`, `raw`, `#{{}}`) | Brakeman, erb_lint | off |
223
+ | DatabaseQueries (`where`, `find_by`, `pluck`, `exists?`, `Model.all`, `Model.order`… in a template) | Rails guides | off |
211
224
  | SlimSyntax (code continued after an opening bracket, a comment after code: Slim and Brakeman can't read them) | Brakeman | on |
212
225
  | EmbeddedEngines (`forbidden_engines: [javascript, css]`) | slim-lint | off |
213
226
  | HardcodedText (text that should be translated) | erb_lint | off |
214
227
  | UnnecessaryInterpolation, UnnecessaryStringOutput | haml-lint | on |
215
228
  | Zwsp (invisible characters) | slim-lint | on |
216
229
 
217
- The website shows [each rule with an example](https://levups.github.io/super-slim/tools.html). A configuration
218
- file looks like this:
230
+ The website gives [each rule](https://levups.github.io/super-slim/tools.html#rules) its own entry: why it exists,
231
+ an example, its settings with their defaults, and whether `super-slim format` fixes it. `super-slim lint` prints
232
+ the link to each rule it reports, on stderr. A configuration file looks like this:
219
233
 
220
234
  ```yaml
221
235
  # .super-slim.yml
@@ -55,6 +55,10 @@ module SuperSlim
55
55
  [Linter::Offense.new(path, 0, "Error", "#{exception.class}: #{exception.message.lines.first&.strip}")]
56
56
  end.flatten
57
57
  offenses.each { |offense| puts printable("#{offense.path}:#{offense.lineno}: [#{offense.rule}] #{offense.message}") }
58
+ # On stderr, so that stdout stays one offense per line for the tools that read it.
59
+ $stdout.flush
60
+ reported = offenses.to_set(&:rule)
61
+ Linter::Rules.all.each { |rule| warn("#{rule.rule_name}: #{Linter::RULES_URL}##{rule.rule_name}") if reported.include?(rule.rule_name) }
58
62
  offenses.empty? ? 0 : 1
59
63
  end
60
64
 
@@ -1,5 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "prism"
4
+
3
5
  module SuperSlim
4
6
  class Linter
5
7
  module Rules
@@ -76,6 +78,44 @@ module SuperSlim
76
78
  def literal_attributes(tag, name)
77
79
  tag.attributes.select { _1.respond_to?(:name) && _1.name == name && literal_value(_1) }
78
80
  end
81
+
82
+ INTERPOLATION = /#\{\{?([^{}]*)\}?\}/
83
+
84
+ # Each piece of Ruby in the template, with the line it starts on: `-` and `=` lines, attribute values, splats,
85
+ # `ruby:` blocks, and the interpolations of text and quoted attributes.
86
+ def each_ruby(document)
87
+ document.each_node do |node, ancestors|
88
+ case node
89
+ when AST::Control, AST::Output then yield node.code, document.line_of(node)
90
+ when AST::Tag
91
+ node.attributes.each do |attribute|
92
+ case attribute
93
+ when AST::CodeAttribute, AST::Splat then yield attribute.code, document.line_of(node)
94
+ when AST::QuotedAttribute then attribute.text.scan(INTERPOLATION) { yield $1, document.line_of(node) }
95
+ end
96
+ end
97
+ when AST::Embedded
98
+ next unless node.engine == "ruby"
99
+
100
+ yield node.children.grep(AST::Text).map(&:text).join, document.line_of(node) + 1
101
+ when AST::Text
102
+ next if ancestors.last.is_a?(AST::Embedded) && ancestors.last.engine == "ruby"
103
+
104
+ node.text.scan(INTERPOLATION) { yield $1, line_near(document, node, ancestors) }
105
+ end
106
+ end
107
+ end
108
+
109
+ # Prism reads a `- if` or `- each do` line without its `end`, as it reads code with errors: the tree it gives
110
+ # holds the calls written.
111
+ def each_prism_node(code_or_node)
112
+ stack = [code_or_node.is_a?(String) ? Prism.parse(code_or_node).value : code_or_node]
113
+ until stack.empty?
114
+ node = stack.pop
115
+ yield node
116
+ stack.concat(node.compact_child_nodes)
117
+ end
118
+ end
79
119
  end
80
120
 
81
121
  # Layout: everything `super-slim format` rewrites.
@@ -274,6 +314,41 @@ module SuperSlim
274
314
  end
275
315
  end
276
316
 
317
+ class UnusedLocals < Rule
318
+ SIGNATURE = %r{\A\s*/#\s*locals:\s*(\(.*\))\s*\z}
319
+
320
+ def offenses(document, _source)
321
+ return [] unless (lineno = document.lines.index { _1.match?(SIGNATURE) })
322
+
323
+ definition = Prism.parse("def _#{document.lines[lineno][SIGNATURE, 1]}; end").value.statements&.body&.first
324
+ return [] unless definition.is_a?(Prism::DefNode) && definition.parameters
325
+
326
+ declared = definition.parameters.keywords.map(&:name)
327
+ # A default can read another local: `(post:, title: post.title)`.
328
+ read = Set.new
329
+ definition.parameters.keywords.each { read.merge(names_read(_1.value)) if _1.respond_to?(:value) }
330
+ each_ruby(document) { |code,| read.merge(names_read(code)) }
331
+ return [] if read.include?(:local_assigns)
332
+
333
+ (declared - read.to_a).map { offense(document, lineno + 1, "The local `#{_1}` is declared but never read") }
334
+ end
335
+
336
+ private
337
+
338
+ # A partial reads its locals as methods without receiver nor arguments, the shorthand `post:` included, or as
339
+ # variables once code has assigned them.
340
+ def names_read(code_or_node)
341
+ names = Set.new
342
+ each_prism_node(code_or_node) do |node|
343
+ case node
344
+ when Prism::LocalVariableReadNode then names << node.name
345
+ when Prism::CallNode then names << node.name if node.receiver.nil? && node.arguments.nil?
346
+ end
347
+ end
348
+ names
349
+ end
350
+ end
351
+
277
352
  # HTML and accessibility, after Herb, erb_lint and eslint-plugin-jsx-a11y.
278
353
 
279
354
  class DuplicateId < Rule
@@ -306,9 +381,20 @@ module SuperSlim
306
381
  end
307
382
  end
308
383
 
384
+ # After eslint-plugin-jsx-a11y's anchor-is-valid: `href="#"` and `javascript:` only stand in for a click handler.
309
385
  class AnchorHref < Rule
386
+ PLACEHOLDER = /\A\s*(?:#|javascript:.*)\z/im
387
+
310
388
  def offenses(document, _source)
311
- missing_attribute(document, "a", "href", "A link without `href` is not a link: use a `button` for actions")
389
+ placeholders = enum_for(:each_tag, document, "a").flat_map do |tag,|
390
+ literal_attributes(tag, "href").filter_map do |attribute|
391
+ next unless (href = literal_value(attribute)).match?(PLACEHOLDER)
392
+
393
+ target = href.strip.start_with?("#") ? '`href="#"`' : "A `javascript:` URL"
394
+ offense(document, document.line_of(tag), "#{target} goes nowhere: use a `button` for actions")
395
+ end
396
+ end
397
+ missing_attribute(document, "a", "href", "A link without `href` is not a link: use a `button` for actions") + placeholders
312
398
  end
313
399
  end
314
400
 
@@ -481,6 +567,19 @@ module SuperSlim
481
567
  end
482
568
  end
483
569
 
570
+ class InlineEventHandlers < Rule
571
+ DEFAULTS = {enabled: false}.freeze
572
+ HANDLER = /\Aon[a-z]+\z/
573
+
574
+ def offenses(document, _source)
575
+ enum_for(:each_tag, document).flat_map do |tag,|
576
+ attribute_names(tag).grep(HANDLER).map do |name|
577
+ offense(document, document.line_of(tag), "Move the `#{name}` handler to JavaScript: a strict Content Security Policy blocks it")
578
+ end
579
+ end
580
+ end
581
+ end
582
+
484
583
  class UnescapedOutput < Rule
485
584
  DEFAULTS = {enabled: false}.freeze
486
585
  SKIPS_ESCAPING = /\.html_safe\b|(?<![\w.:@])raw[ (]/
@@ -552,6 +651,45 @@ module SuperSlim
552
651
  end
553
652
  end
554
653
 
654
+ # Matched by method name: an off-by-default rule, since a few of these also run on arrays.
655
+ class DatabaseQueries < Rule
656
+ DEFAULTS = {enabled: false}.freeze
657
+ QUERY_METHODS = %i[where find_by find_by! pluck pick exists? find_each find_in_batches in_batches].to_set.freeze
658
+ # Called on a constant, these read a model's table: `Tag.order(:name)`.
659
+ MODEL_METHODS = %i[all order find first last count limit includes joins sum minimum maximum].to_set.freeze
660
+
661
+ def offenses(document, _source)
662
+ calls_by_lineno = Hash.new { |hash, lineno| hash[lineno] = [] }
663
+ each_ruby(document) do |code, lineno|
664
+ next unless lineno
665
+
666
+ each_prism_node(code) do |node|
667
+ next unless node.is_a?(Prism::CallNode) && (call = query(node))
668
+
669
+ calls_by_lineno[lineno + node.location.start_line - 1] << [node.message_loc.start_offset, call]
670
+ end
671
+ end
672
+ # One offense a line, its calls in the order they are written: the tree is walked from the outermost.
673
+ calls_by_lineno.keys.sort!.map! do |lineno|
674
+ calls = calls_by_lineno[lineno].sort.map!(&:last).uniq
675
+ offense(document, lineno, "#{calls.map { "`#{_1}`" }.join(", ")} #{(calls.size == 1) ? "queries" : "query"} " \
676
+ "the database from the template: load the records in the controller")
677
+ end
678
+ end
679
+
680
+ private
681
+
682
+ def query(node)
683
+ return unless node.receiver
684
+
685
+ if node.receiver.is_a?(Prism::ConstantReadNode) || node.receiver.is_a?(Prism::ConstantPathNode)
686
+ "#{node.receiver.slice}.#{node.name}" if MODEL_METHODS.include?(node.name) || QUERY_METHODS.include?(node.name)
687
+ elsif QUERY_METHODS.include?(node.name)
688
+ node.name.to_s
689
+ end
690
+ end
691
+ end
692
+
555
693
  # Brakeman parses views with Slim, which refuses these lines: it reports the template and checks nothing in it.
556
694
  class SlimSyntax < Rule
557
695
  MESSAGE = "Slim, and so Brakeman, cannot read"
@@ -615,6 +753,78 @@ module SuperSlim
615
753
  end
616
754
  end
617
755
 
756
+ # Conditionals RuboCop would rewrite, but its plugin hands it each `-` line without the lines around it.
757
+
758
+ module Conditionals
759
+ CONDITIONAL = /\A\s*(?:if|unless)\s/
760
+ ELSE = /\A\s*else\s*\z/
761
+
762
+ private
763
+
764
+ # Each conditional `-` line, the line after it at its depth, comments skipped, and its sub-lines.
765
+ def each_conditional(document)
766
+ [document.nodes, *document.visits.filter_map { |node,| Document.children_of(node) }].each do |siblings|
767
+ lines = significant(siblings)
768
+ lines.each_with_index do |node, index|
769
+ yield node, lines[index + 1], significant(node.children) if node.is_a?(AST::Control) && node.code.match?(CONDITIONAL)
770
+ end
771
+ end
772
+ end
773
+
774
+ def significant(nodes)
775
+ (nodes || []).reject { _1 == AST::NEWLINE || (_1.is_a?(AST::Control) && _1.code.match?(/\A\s*#/)) }
776
+ end
777
+
778
+ def else?(node)
779
+ node.is_a?(AST::Control) && node.code.match?(ELSE)
780
+ end
781
+
782
+ def branch?(node)
783
+ node.is_a?(AST::Control) && node.code.match?(/\A\s*(?:else|elsif)\b/)
784
+ end
785
+ end
786
+
787
+ class SoleNestedConditional < Rule
788
+ include Conditionals
789
+
790
+ def offenses(document, _source)
791
+ enum_for(:each_conditional, document).filter_map do |_node, following, children|
792
+ next if branch?(following) || children.size != 1
793
+ next unless (inner = children.first).is_a?(AST::Control) && inner.code.match?(CONDITIONAL)
794
+
795
+ keyword = inner.code[/\w+/]
796
+ offense(document, document.line_of(inner), "Merge this `#{keyword}` into the one around it with `&&`")
797
+ end
798
+ end
799
+ end
800
+
801
+ class NegatedIfElseCondition < Rule
802
+ include Conditionals
803
+
804
+ NEGATED_IF = /\A\s*if\s+!(?!=)\s*(\S.*)\z/m
805
+
806
+ def offenses(document, _source)
807
+ enum_for(:each_conditional, document).filter_map do |node, following|
808
+ next unless else?(following) && (condition = node.code[NEGATED_IF, 1])
809
+ next if condition.match?(Formatter::COMPOUND_CONDITION)
810
+
811
+ offense(document, document.line_of(node), "Write `if #{condition.strip}` and swap the branches")
812
+ end
813
+ end
814
+ end
815
+
816
+ class UnlessElse < Rule
817
+ include Conditionals
818
+
819
+ def offenses(document, _source)
820
+ enum_for(:each_conditional, document).filter_map do |node, following|
821
+ next unless else?(following) && node.code.match?(/\A\s*unless\s/)
822
+
823
+ offense(document, document.line_of(node), "Write `if` instead of `unless`, and swap the branches")
824
+ end
825
+ end
826
+ end
827
+
618
828
  class Zwsp < Rule
619
829
  INVISIBLE = /[\u200B-\u200D\u2060\uFEFF]/
620
830
  # The zero-width joiner of 🐈‍⬛ or 👩🏻‍💻: between two pictographs, after an optional skin tone or emoji style.
@@ -70,6 +70,8 @@ module SuperSlim
70
70
  end
71
71
 
72
72
  CONFIG_FILE = ".super-slim.yml"
73
+ # Each rule has an entry there, its name as the fragment: `rake docs` writes them.
74
+ RULES_URL = "https://levups.github.io/super-slim/tools.html"
73
75
  DISABLE_DIRECTIVE = %r{\A?\s*/\s*super-slim:disable\s+(\S.*?)\s*\z}
74
76
  # The layout rules: what `super-slim format` rewrites.
75
77
  LAYOUT_RULE_NAMES = %w[Indentation Tab TrailingWhitespace EmptyLines ControlStatementSpacing RedundantDiv].freeze
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module SuperSlim
4
- VERSION = "3.4.1"
4
+ VERSION = "3.5.0"
5
5
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: super-slim
3
3
  version: !ruby/object:Gem::Version
4
- version: 3.4.1
4
+ version: 3.5.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Level UP Solutions