forked from sds/scss-lint
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bang_format.rb
68 lines (54 loc) · 2 KB
/
bang_format.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
module SCSSLint
# Checks spacing of ! declarations, like !important and !default
class Linter::BangFormat < Linter
include LinterRegistry
STOPPING_CHARACTERS = ['!', "'", '"', nil].freeze
def visit_extend(node)
check_bang(node)
end
def visit_prop(node)
check_bang(node)
end
def visit_variable(node)
check_bang(node)
end
private
def check_bang(node)
range = if node.respond_to?(:value_source_range)
node.value_source_range
else
node.source_range
end
return unless source_from_range(range).include?('!')
return unless check_spacing(range)
before_qualifier = config['space_before_bang'] ? '' : 'not '
after_qualifier = config['space_after_bang'] ? '' : 'not '
add_lint(node, "! should #{before_qualifier}be preceded by a space, " \
"and should #{after_qualifier}be followed by a space")
end
# Start from the back and move towards the front so that any !important or
# !default !'s will be found *before* quotation marks. Then we can
# stop at quotation marks to protect against linting !'s within strings
# (e.g. `content`)
def find_bang_offset(range)
offset = 0
offset -= 1 until STOPPING_CHARACTERS.include?(character_at(range.end_pos, offset))
offset
end
def is_before_wrong?(range, offset)
before_expected = config['space_before_bang'] ? / / : /[^ ]/
before_actual = character_at(range.end_pos, offset - 1)
(before_actual =~ before_expected).nil?
end
def is_after_wrong?(range, offset)
after_expected = config['space_after_bang'] ? / / : /[^ ]/
after_actual = character_at(range.end_pos, offset + 1)
(after_actual =~ after_expected).nil?
end
def check_spacing(range)
offset = find_bang_offset(range)
return if character_at(range.end_pos, offset) != '!'
is_before_wrong?(range, offset) || is_after_wrong?(range, offset)
end
end
end