-
-
Notifications
You must be signed in to change notification settings - Fork 3k
/
ordered_dependencies.rb
104 lines (94 loc) · 2.98 KB
/
ordered_dependencies.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
# frozen_string_literal: true
module RuboCop
module Cop
module Gemspec
# Dependencies in the gemspec should be alphabetically sorted.
#
# @example
# # bad
# spec.add_dependency 'rubocop'
# spec.add_dependency 'rspec'
#
# # good
# spec.add_dependency 'rspec'
# spec.add_dependency 'rubocop'
#
# # good
# spec.add_dependency 'rubocop'
#
# spec.add_dependency 'rspec'
#
# # bad
# spec.add_development_dependency 'rubocop'
# spec.add_development_dependency 'rspec'
#
# # good
# spec.add_development_dependency 'rspec'
# spec.add_development_dependency 'rubocop'
#
# # good
# spec.add_development_dependency 'rubocop'
#
# spec.add_development_dependency 'rspec'
#
# # bad
# spec.add_runtime_dependency 'rubocop'
# spec.add_runtime_dependency 'rspec'
#
# # good
# spec.add_runtime_dependency 'rspec'
# spec.add_runtime_dependency 'rubocop'
#
# # good
# spec.add_runtime_dependency 'rubocop'
#
# spec.add_runtime_dependency 'rspec'
#
# # good only if TreatCommentsAsGroupSeparators is true
# # For code quality
# spec.add_dependency 'rubocop'
# # For tests
# spec.add_dependency 'rspec'
class OrderedDependencies < Cop
include ConfigurableEnforcedStyle
include OrderedGemNode
MSG = 'Dependencies should be sorted in an alphabetical order within ' \
'their section of the gemspec. '\
'Dependency `%<previous>s` should appear before `%<current>s`.'
def investigate(processed_source)
return if processed_source.blank?
dependency_declarations(processed_source.ast)
.each_cons(2) do |previous, current|
next unless consecutive_lines(previous, current)
next unless case_insensitive_out_of_order?(
gem_name(current),
gem_name(previous)
)
next unless get_dependency_name(previous) == get_dependency_name(current)
register_offense(previous, current)
end
end
def autocorrect(node)
OrderedGemCorrector.correct(
processed_source,
node,
previous_declaration(node),
treat_comments_as_separators
)
end
private
def previous_declaration(node)
declarations = dependency_declarations(processed_source.ast)
node_index = declarations.find_index(node)
declarations.to_a[node_index - 1]
end
def get_dependency_name(node)
node.method_name
end
def_node_search :dependency_declarations, <<~PATTERN
(send (lvar _) {:add_dependency :add_runtime_dependency :add_development_dependency} (str _) ...)
PATTERN
end
end
end
end