blob: 71c42596334f6c427008be58d3841c0659357482 (
plain)
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
|
# frozen_string_literal: true
# This cop enforces the enum value conventions from the enum style guide:
# https://docs.gitlab.com/ee/development/api_graphql_styleguide.html#enums
#
# @example
#
# # bad
# class BadEnum < BaseEnum
# graphql_name 'Bad'
#
# value 'foo'
# end
#
# class UngoodEnum < BaseEnum
# graphql_name 'Ungood'
#
# ['bar'].each do |val|
# value val
# end
# end
#
# # good
# class GoodEnum < BaseEnum
# graphql_name 'Good'
#
# value 'FOO'
# end
#
# class GreatEnum < BaseEnum
# graphql_name 'Great'
#
# ['bar'].each do |val|
# value val.upcase
# end
# end
module RuboCop
module Cop
module Graphql
class EnumValues < RuboCop::Cop::Base
MSG = "Enum values must either be an uppercase string literal or uppercased with the `upcase` method. " \
"See https://docs.gitlab.com/ee/development/api_graphql_styleguide.html#enums"
def_node_matcher :enum_value, <<~PATTERN
(send nil? :value $_ $...)
PATTERN
def_node_search :deprecated?, <<~PATTERN
(hash <(pair (sym :deprecated) _) ...>)
PATTERN
def_node_matcher :upcase_literal?, <<~PATTERN
(str #upcase?)
PATTERN
def_node_matcher :upcase_method?, <<~PATTERN
`(send _ :upcase)
PATTERN
def on_send(node)
value_node, params = enum_value(node)
return unless value_node
return if params.any? { deprecated?(_1) }
return if upcase_literal?(value_node) || upcase_method?(value_node)
add_offense(value_node)
end
private
def upcase?(str)
str == str.upcase
end
end
end
end
end
|