Skip to content

Commit

Permalink
Support for conditional comments in RuboCop linter (#469)
Browse files Browse the repository at this point in the history
  • Loading branch information
MaxLap authored Jan 7, 2024
1 parent 9f637a7 commit b25867d
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 0 deletions.
28 changes: 28 additions & 0 deletions lib/haml_lint/ruby_extraction/chunk_extractor.rb
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,35 @@ def visit_haml_comment(node)
def visit_comment(node)
line = @original_haml_lines[node.line - 1]
indent = line.index(/\S/)

@ruby_chunks << PlaceholderMarkerChunk.new(node, 'comment', indent: indent)

# Comment can have subnodes, such as plain. This happens for conditional comments, such as:
# %head
# /[if mso]
# %div
if node.children
# We don't want to use a block because assignments in a block are local to that block,
# so the semantics of the extracted ruby would be different from the one generated by
# Haml. Those differences can make some cops, such as UselessAssignment, have false
# positives
begin_chunk = AdHocChunk.new(node, [' ' * indent + 'begin'])
@ruby_chunks << begin_chunk
indent += 2

yield

indent -= 2

if @ruby_chunks.last.equal?(begin_chunk)
# So there is nothing nesting, remove the wrapping "begin"
@ruby_chunks.pop
else
@ruby_chunks << AdHocChunk.new(node,
[' ' * indent + 'ensure', ' ' * indent + ' HL.noop', ' ' * indent + 'end'],
haml_line_index: @ruby_chunks.last.haml_end_line_index)
end
end
end

# Visit a script which outputs. Lines looking like ` = foo`
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
!!! Removes indentation of a conditional comment's content
- if a
- if b
/[if mso]
%div
---
SKIP
---
SKIP
---
- if a && b
/[if mso]
%div


!!! fixes a single-line script that is inside a conditional comment
/[if mso]
^ foo(:bar => 123)
---
haml_lint_comment_1
begin
haml_lint_marker_3 $$2
^^foo(:bar => 123)
haml_lint_marker_5
ensure
HL.noop
end
---
haml_lint_comment_1
begin
haml_lint_marker_3
^^foo(bar: 123)
haml_lint_marker_5
ensure
HL.noop
end
---
/[if mso]
^ foo(bar: 123)

0 comments on commit b25867d

Please sign in to comment.