forked from sds/scss-lint
-
Notifications
You must be signed in to change notification settings - Fork 0
/
leading_zero.rb
49 lines (40 loc) · 1.57 KB
/
leading_zero.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
module SCSSLint
# Checks for unnecessary leading zeros in numeric values with decimal points.
class Linter::LeadingZero < Linter
include LinterRegistry
def visit_script_string(node)
return unless node.type == :identifier
non_string_values = remove_quoted_strings(node.value).split
non_string_values.each do |value|
next unless number = value[NUMBER_WITH_LEADING_ZERO_REGEX, 1]
check_for_leading_zeros(node, number)
end
end
def visit_script_number(node)
return unless number =
source_from_range(node.source_range)[NUMBER_WITH_LEADING_ZERO_REGEX, 1]
check_for_leading_zeros(node, number)
end
private
NUMBER_WITH_LEADING_ZERO_REGEX = /^-?(0?\.\d+)/
CONVENTIONS = {
'exclude_zero' => {
explanation: '`%s` should be written without a leading zero as `%s`',
validator: ->(original) { original =~ /^\.\d+$/ },
converter: ->(original) { original[1..-1] },
},
'include_zero' => {
explanation: '`%s` should be written with a leading zero as `%s`',
validator: ->(original) { original =~ /^0\.\d+$/ },
converter: ->(original) { "0#{original}" }
},
}.freeze
def check_for_leading_zeros(node, original_number)
style = config.fetch('style', 'exclude_zero')
convention = CONVENTIONS[style]
return if convention[:validator].call(original_number)
corrected = convention[:converter].call(original_number)
add_lint(node, convention[:explanation] % [original_number, corrected])
end
end
end