rubocop-dev_doc 0.18.0 → 0.20.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/config/default.yml +184 -2
- data/lib/dev_doc/i18n/pseudo_locale.rb +1 -1
- data/lib/dev_doc/test/lints/cross_tenant_canary_check.rb +1 -1
- data/lib/dev_doc/test/lints/cross_tenant_canary_sweep.rb +6 -3
- data/lib/dev_doc/test/lints/http_driven_controller_tests.rb +2 -0
- data/lib/dev_doc/test/lints/no_file_excludes.rb +1 -1
- data/lib/dev_doc/test/pseudo_i18n_crawler.rb +4 -0
- data/lib/rubocop/cop/dev_doc/auth/adjacent_justification.rb +44 -7
- data/lib/rubocop/cop/dev_doc/auth/load_resource_current_user_guard.rb +2 -2
- data/lib/rubocop/cop/dev_doc/auth/login_only_policy_justification.rb +1 -1
- data/lib/rubocop/cop/dev_doc/auth/unscoped_find_justification.rb +2 -2
- data/lib/rubocop/cop/dev_doc/bundler/conflicting_gem.rb +74 -0
- data/lib/rubocop/cop/dev_doc/exception_class_list.rb +32 -0
- data/lib/rubocop/cop/dev_doc/i18n/translation_key_prefix.rb +1 -1
- data/lib/rubocop/cop/dev_doc/migration/legacy_migration.rb +26 -0
- data/lib/rubocop/cop/dev_doc/migration/redundant_reference_index.rb +5 -15
- data/lib/rubocop/cop/dev_doc/migration/require_reference_index.rb +115 -0
- data/lib/rubocop/cop/dev_doc/rails/avoid_lifecycle_method_override.rb +1 -1
- data/lib/rubocop/cop/dev_doc/rails/create_or_find_by.rb +66 -0
- data/lib/rubocop/cop/dev_doc/rails/find_or_create_by_justification.rb +106 -0
- data/lib/rubocop/cop/dev_doc/rails/no_error_message_comparison.rb +178 -0
- data/lib/rubocop/cop/dev_doc/rails/no_form_param_lookup_in_controller.rb +1 -1
- data/lib/rubocop/cop/dev_doc/rails/rescue_record_not_unique_index.rb +212 -0
- data/lib/rubocop/cop/dev_doc/rails/unique_index_backing.rb +205 -0
- data/lib/rubocop/cop/dev_doc/style/avoid_kernel_array.rb +103 -0
- data/lib/rubocop/cop/dev_doc/style/no_silent_rescue.rb +36 -26
- data/lib/rubocop/cop/dev_doc/style/no_unscoped_method_definitions.rb +1 -1
- data/lib/rubocop/cop/dev_doc/style/rescue_justification.rb +330 -0
- data/lib/rubocop/cop/dev_doc/test/justification_covers.rb +216 -0
- data/lib/rubocop/cop/dev_doc/test/justification_header.rb +86 -5
- data/lib/rubocop/cop/dev_doc/test/require_job_invocation_in_job_tests.rb +154 -0
- data/lib/rubocop/cop/dev_doc/test/require_unit_test_justification.rb +5 -24
- data/lib/rubocop/cop/dev_doc/test/test_file_placement.rb +30 -2
- data/lib/rubocop/dev_doc/version.rb +1 -1
- metadata +16 -3
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
require_relative 'unique_index_backing'
|
|
2
|
+
|
|
3
|
+
module RuboCop
|
|
4
|
+
module Cop
|
|
5
|
+
module DevDoc
|
|
6
|
+
module Rails
|
|
7
|
+
# Rule 2 of 03_model.md item 14, checked at the rescue site: a
|
|
8
|
+
# `rescue ActiveRecord::RecordNotUnique` must guard a write that
|
|
9
|
+
# (a) sits inside its own `transaction(requires_new: true)` and
|
|
10
|
+
# (b) is backed by a unique index in the schema.
|
|
11
|
+
#
|
|
12
|
+
# ## Rationale
|
|
13
|
+
# A rescued `RecordNotUnique` makes two promises, and both can be
|
|
14
|
+
# wrong silently:
|
|
15
|
+
#
|
|
16
|
+
# - **The savepoint promise.** In Postgres, one failed statement
|
|
17
|
+
# poisons the whole transaction; without a savepoint the rescue
|
|
18
|
+
# "succeeds" and the caller's NEXT statement raises
|
|
19
|
+
# `PG::InFailedSqlTransaction` — a 500 far from the race that
|
|
20
|
+
# caused it. Whether a site sits inside a caller's transaction is
|
|
21
|
+
# a property of its callers, and callers change, so the wrapper is
|
|
22
|
+
# required unconditionally: outside any transaction a savepoint
|
|
23
|
+
# costs one ordinary transaction; inside one it is the difference
|
|
24
|
+
# between a rescued race and a broken request.
|
|
25
|
+
# - **The index promise.** The rescue can only fire on a unique
|
|
26
|
+
# index; if none backs the write, the rescue is dead code and
|
|
27
|
+
# duplicates accumulate quietly. The cop proves the premise from
|
|
28
|
+
# the schema: the write's literal attribute keys (plus the
|
|
29
|
+
# association-implied foreign key and query-chain contributions —
|
|
30
|
+
# see `UniqueIndexBacking`) must cover a unique index, partial and
|
|
31
|
+
# expression indexes included.
|
|
32
|
+
#
|
|
33
|
+
# Writes whose attributes do not resolve (dynamic hashes,
|
|
34
|
+
# unresolvable receivers) carry a `# unique_index: <name>` tag
|
|
35
|
+
# adjacent to the write; the cop checks the named index exists.
|
|
36
|
+
# Name-only, by Decision: a column list adds review noise the
|
|
37
|
+
# per-site test already covers.
|
|
38
|
+
#
|
|
39
|
+
# There is deliberately NO prose requirement on rescue sites:
|
|
40
|
+
# `DevDoc/Style/RescueJustification` already exempts race verdicts,
|
|
41
|
+
# and the choice at a rule-2 site is stated by its rescue body —
|
|
42
|
+
# this cop checks facts (the savepoint wraps, the index exists),
|
|
43
|
+
# not sentences.
|
|
44
|
+
#
|
|
45
|
+
# Modifier rescues (`write rescue fallback`) are out of scope, as in
|
|
46
|
+
# RescueJustification: `Style/RescueModifier` flags every one on
|
|
47
|
+
# form alone. The rescued class is matched AS WRITTEN — spell it
|
|
48
|
+
# `ActiveRecord::RecordNotUnique` (a leading `::` is fine).
|
|
49
|
+
#
|
|
50
|
+
# @example
|
|
51
|
+
# # bad — no savepoint: a lost race poisons the caller's transaction
|
|
52
|
+
# def add(member)
|
|
53
|
+
# assignees.create!(member: member)
|
|
54
|
+
# rescue ActiveRecord::RecordNotUnique
|
|
55
|
+
# nil
|
|
56
|
+
# end
|
|
57
|
+
#
|
|
58
|
+
# # good — rule 2: savepoint, index-backed write, stated loss
|
|
59
|
+
# def add(member)
|
|
60
|
+
# transaction(requires_new: true) do
|
|
61
|
+
# assignees.create!(member: member)
|
|
62
|
+
# end
|
|
63
|
+
# rescue ActiveRecord::RecordNotUnique
|
|
64
|
+
# # Lost the (assignee_group, member) race: the member is already in the group.
|
|
65
|
+
# nil
|
|
66
|
+
# end
|
|
67
|
+
class RescueRecordNotUniqueIndex < Base
|
|
68
|
+
include RescueNode
|
|
69
|
+
include UniqueIndexBacking
|
|
70
|
+
|
|
71
|
+
SAVEPOINT_MSG = 'The write guarded by this `rescue ActiveRecord::RecordNotUnique` must sit inside its own ' \
|
|
72
|
+
'`transaction(requires_new: true)`: without a savepoint the rescued failed INSERT poisons ' \
|
|
73
|
+
'the caller\'s transaction and the NEXT statement raises PG::InFailedSqlTransaction ' \
|
|
74
|
+
'(03_model.md item 14, rule 2).'.freeze
|
|
75
|
+
INDEX_MSG = 'No unique index backs this write, so this `rescue ActiveRecord::RecordNotUnique` can never ' \
|
|
76
|
+
'fire and duplicates accumulate silently. Match the write\'s literal attributes against the ' \
|
|
77
|
+
'schema, or tag the write `# unique_index: <name>` (03_model.md item 14, rule 2).'.freeze
|
|
78
|
+
TAG_MSG = 'The `# unique_index:` tag names no index%<scope>s in db/schema.rb — a typo, or the index was ' \
|
|
79
|
+
'dropped. Fix the name or the write\'s attributes.'.freeze
|
|
80
|
+
|
|
81
|
+
RECORD_NOT_UNIQUE = 'ActiveRecord::RecordNotUnique'.freeze
|
|
82
|
+
private_constant :RECORD_NOT_UNIQUE
|
|
83
|
+
|
|
84
|
+
# The `# unique_index: <name>` tag adjacent to a write, read for
|
|
85
|
+
# its capture (name-only, by Decision).
|
|
86
|
+
UNIQUE_INDEX_TAG = /unique_index:\s*([A-Za-z0-9_]+)/
|
|
87
|
+
|
|
88
|
+
# Writes whose INSERT/UPDATE can raise RecordNotUnique. The
|
|
89
|
+
# upsert family is absent (ON CONFLICT absorbs the race); so are
|
|
90
|
+
# destroys (a DELETE cannot violate a unique index).
|
|
91
|
+
PERSISTENCE_WRITES = %i[
|
|
92
|
+
create create! insert insert! insert_all insert_all! create_or_find_by create_or_find_by!
|
|
93
|
+
find_or_create_by find_or_create_by! first_or_create first_or_create!
|
|
94
|
+
update update! update_all update_column update_columns update_attribute
|
|
95
|
+
save save! touch increment! decrement! toggle!
|
|
96
|
+
].freeze
|
|
97
|
+
|
|
98
|
+
def on_rescue(node)
|
|
99
|
+
check_writes(node.body) if guards_record_not_unique?(node)
|
|
100
|
+
end
|
|
101
|
+
|
|
102
|
+
private
|
|
103
|
+
|
|
104
|
+
# The rescued classes are matched as written (leading `::`
|
|
105
|
+
# ignored), the same fail-closed spelling contract as
|
|
106
|
+
# RescueJustification's class list; modifier rescues are out of
|
|
107
|
+
# scope.
|
|
108
|
+
def guards_record_not_unique?(rescue_node)
|
|
109
|
+
rescue_node.resbody_branches.reject { |resbody| rescue_modifier?(resbody) }.any? do |resbody|
|
|
110
|
+
resbody.exceptions.any? { |exception| exception.source.sub(/\A::/, '') == RECORD_NOT_UNIQUE }
|
|
111
|
+
end
|
|
112
|
+
end
|
|
113
|
+
|
|
114
|
+
def check_writes(region)
|
|
115
|
+
return unless region
|
|
116
|
+
|
|
117
|
+
region.each_node(:send, :csend) do |candidate|
|
|
118
|
+
next unless PERSISTENCE_WRITES.include?(candidate.method_name)
|
|
119
|
+
next if inside_rescue_body?(candidate, region)
|
|
120
|
+
|
|
121
|
+
check_savepoint(candidate)
|
|
122
|
+
check_index(candidate)
|
|
123
|
+
end
|
|
124
|
+
end
|
|
125
|
+
|
|
126
|
+
# A write lexically inside a nested rescue's body is not guarded
|
|
127
|
+
# by THIS rescue — its own clause owns it.
|
|
128
|
+
def inside_rescue_body?(candidate, region)
|
|
129
|
+
candidate.each_ancestor.take_while { |ancestor| !ancestor.equal?(region) }.any?(&:resbody_type?)
|
|
130
|
+
end
|
|
131
|
+
|
|
132
|
+
def check_savepoint(write)
|
|
133
|
+
return if requires_new_ancestor?(write)
|
|
134
|
+
|
|
135
|
+
add_offense(write.loc.selector, message: SAVEPOINT_MSG)
|
|
136
|
+
end
|
|
137
|
+
|
|
138
|
+
# Any lexically enclosing `transaction(requires_new: true)` counts:
|
|
139
|
+
# the failed INSERT rolls back to that savepoint however deeply the
|
|
140
|
+
# write nests inside the guarded region. A do-block's send node is
|
|
141
|
+
# the block's CHILD, so block ancestors are inspected through their
|
|
142
|
+
# send node.
|
|
143
|
+
def requires_new_ancestor?(write)
|
|
144
|
+
write.each_ancestor.any? do |ancestor|
|
|
145
|
+
transaction = enclosing_transaction(ancestor)
|
|
146
|
+
transaction && requires_new?(transaction)
|
|
147
|
+
end
|
|
148
|
+
end
|
|
149
|
+
|
|
150
|
+
# The `transaction` send for a block ancestor (through its send
|
|
151
|
+
# node) or a send ancestor, else nil.
|
|
152
|
+
def enclosing_transaction(ancestor)
|
|
153
|
+
candidate = ancestor.block_type? ? ancestor.send_node : ancestor
|
|
154
|
+
return nil unless candidate.respond_to?(:method_name)
|
|
155
|
+
return nil unless candidate.send_type? || candidate.csend_type?
|
|
156
|
+
return nil unless candidate.method_name == :transaction
|
|
157
|
+
|
|
158
|
+
candidate
|
|
159
|
+
end
|
|
160
|
+
|
|
161
|
+
def requires_new?(transaction_send)
|
|
162
|
+
transaction_send.arguments.any? do |argument|
|
|
163
|
+
next false unless argument.hash_type?
|
|
164
|
+
|
|
165
|
+
argument.pairs.any? do |pair|
|
|
166
|
+
pair.key.sym_type? && pair.key.value == :requires_new && pair.value.true_type?
|
|
167
|
+
end
|
|
168
|
+
end
|
|
169
|
+
end
|
|
170
|
+
|
|
171
|
+
def check_index(write)
|
|
172
|
+
return unless schema
|
|
173
|
+
|
|
174
|
+
table, implied_fk = receiver_resolution(write.receiver, write)
|
|
175
|
+
keys = write_attribute_keys(write)
|
|
176
|
+
return if covering_unique_index(table: table, attribute_keys: keys || [], implied_fk: implied_fk)
|
|
177
|
+
|
|
178
|
+
offense = index_offense(adjacent_unique_index_tag_name(write), table)
|
|
179
|
+
add_offense(write.loc.selector, message: offense) if offense
|
|
180
|
+
end
|
|
181
|
+
|
|
182
|
+
# The index gap's message: INDEX_MSG when no tag names the write,
|
|
183
|
+
# missing-tag wording when the tag names no index.
|
|
184
|
+
def index_offense(name, table)
|
|
185
|
+
return INDEX_MSG unless name
|
|
186
|
+
return nil if named_index(name, table: table)
|
|
187
|
+
|
|
188
|
+
format(TAG_MSG, scope: table ? " on #{table}" : '')
|
|
189
|
+
end
|
|
190
|
+
|
|
191
|
+
# The `# unique_index:` tag on the write's own line or in the
|
|
192
|
+
# contiguous comment block above it — the shared
|
|
193
|
+
# adjacent-justification placement contract, read for its capture.
|
|
194
|
+
def adjacent_unique_index_tag_name(write)
|
|
195
|
+
comments = processed_source.comments.group_by { |comment| comment.location.line }
|
|
196
|
+
adjacent = comments[write.first_line].to_a + comments_above(write.first_line - 1, comments)
|
|
197
|
+
adjacent.filter_map { |comment| comment.text[UNIQUE_INDEX_TAG, 1] }.first
|
|
198
|
+
end
|
|
199
|
+
|
|
200
|
+
def comments_above(line, comments)
|
|
201
|
+
found = []
|
|
202
|
+
while (line_comments = comments[line])
|
|
203
|
+
found.concat(line_comments)
|
|
204
|
+
line -= 1
|
|
205
|
+
end
|
|
206
|
+
found
|
|
207
|
+
end
|
|
208
|
+
end
|
|
209
|
+
end
|
|
210
|
+
end
|
|
211
|
+
end
|
|
212
|
+
end
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
require 'active_support/inflector'
|
|
2
|
+
|
|
3
|
+
module RuboCop
|
|
4
|
+
module Cop
|
|
5
|
+
module DevDoc
|
|
6
|
+
module Rails
|
|
7
|
+
# Shared schema resolution for the uniqueness-write cops
|
|
8
|
+
# (`RescueRecordNotUniqueIndex`, `FindOrCreateByJustification`):
|
|
9
|
+
# given a write's receiver and literal attribute keys, decide whether
|
|
10
|
+
# a unique index backs the write. Conventions (all escape-hatched by
|
|
11
|
+
# the `# unique_index: <name>` tag, read by the host cop at the
|
|
12
|
+
# write):
|
|
13
|
+
#
|
|
14
|
+
# - A CONSTANT receiver names the model (`Activity.create!` ->
|
|
15
|
+
# `activities`); a NIL receiver is a class-level write on the
|
|
16
|
+
# enclosing class.
|
|
17
|
+
# - An association-style receiver resolves by Rails naming: the
|
|
18
|
+
# first PLURAL method in the chain is the association
|
|
19
|
+
# (`organization.organization_managers`,
|
|
20
|
+
# `folders.managed_by_platform`, bare `assignees`), its pluralized
|
|
21
|
+
# name is the table, and the segment before it (or the enclosing
|
|
22
|
+
# class, for a bare association) implies the foreign key —
|
|
23
|
+
# credited only when the table has that column, so a custom
|
|
24
|
+
# `foreign_key:` falls to the tag. A chain with no plural segment
|
|
25
|
+
# is class-level query methods on the enclosing class.
|
|
26
|
+
# - An attribute key `member` covers the columns `member` and
|
|
27
|
+
# `member_id`; an expression index covers the identifiers it names
|
|
28
|
+
# (`user_id, lower((name)::text)` covers `user_id` and `name`).
|
|
29
|
+
# Partial unique indexes count: the rescue fires on any unique
|
|
30
|
+
# violation regardless of the index predicate, and the schema
|
|
31
|
+
# loader exposes no `where` anyway.
|
|
32
|
+
#
|
|
33
|
+
# Everything unresolvable (dynamic hashes, unknown tables) reports
|
|
34
|
+
# `nil` — the host cops require the tag there.
|
|
35
|
+
module UniqueIndexBacking
|
|
36
|
+
include ActiveRecordHelper
|
|
37
|
+
|
|
38
|
+
# Chain calls whose literal hash keys contribute to a write's
|
|
39
|
+
# covered columns (`Model.where(a: 1).create!` writes `a`;
|
|
40
|
+
# `find_or_initialize_by(email:).update!(...)` inserts the
|
|
41
|
+
# initialized attributes).
|
|
42
|
+
ATTRIBUTE_CONTRIBUTORS = %i[
|
|
43
|
+
where find_or_initialize_by find_or_create_by find_or_create_by!
|
|
44
|
+
first_or_create first_or_create! create_or_find_by create_or_find_by!
|
|
45
|
+
].freeze
|
|
46
|
+
|
|
47
|
+
# Node types that can root a receiver chain and still name the
|
|
48
|
+
# association's owner (a local, an ivar, a gvar).
|
|
49
|
+
VARIABLE_ROOTS = %i[lvar ivar cvar gvar].freeze
|
|
50
|
+
|
|
51
|
+
private
|
|
52
|
+
|
|
53
|
+
# The unique index on `table` whose columns (or expression
|
|
54
|
+
# identifiers) are all covered by `attribute_keys` plus the
|
|
55
|
+
# receiver-implied foreign key, or nil.
|
|
56
|
+
def covering_unique_index(table:, attribute_keys:, implied_fk: nil)
|
|
57
|
+
tbl = table && schema&.table_by(name: table)
|
|
58
|
+
return nil unless tbl
|
|
59
|
+
|
|
60
|
+
candidates = covered_columns(attribute_keys, implied_fk, tbl)
|
|
61
|
+
return nil if candidates.empty?
|
|
62
|
+
|
|
63
|
+
tbl.indices.find { |index| unique_index_covers?(index, candidates) }
|
|
64
|
+
end
|
|
65
|
+
|
|
66
|
+
# The schema's index by exact name — on `table` when it resolved,
|
|
67
|
+
# across the whole schema when it did not.
|
|
68
|
+
def named_index(name, table: nil)
|
|
69
|
+
return nil unless schema && name
|
|
70
|
+
|
|
71
|
+
indices = table ? schema.table_by(name: table)&.indices : schema.tables.flat_map(&:indices)
|
|
72
|
+
indices.to_a.find { |index| index.name == name }
|
|
73
|
+
end
|
|
74
|
+
|
|
75
|
+
# Column identifiers named by an expression index:
|
|
76
|
+
# `lower((name)::text)` -> name; `date(entered_at)` -> entered_at.
|
|
77
|
+
def expression_columns(index)
|
|
78
|
+
index.expression.to_s.split(',').flat_map do |segment|
|
|
79
|
+
stripped = segment.strip
|
|
80
|
+
stripped.match?(/\A[a-z_][a-z0-9_]*\z/) ? [stripped] : stripped.scan(/\(([a-z_][a-z0-9_]*)\)/).flatten
|
|
81
|
+
end
|
|
82
|
+
end
|
|
83
|
+
|
|
84
|
+
# [table, implied_fk] for a write's receiver, per the module-doc
|
|
85
|
+
# conventions; [nil, nil] when unresolvable.
|
|
86
|
+
def receiver_resolution(receiver, node)
|
|
87
|
+
return [enclosing_table(node), nil] if receiver.nil?
|
|
88
|
+
return [receiver_table(receiver), nil] if receiver.const_type?
|
|
89
|
+
return association_resolution(receiver, node) if receiver.send_type? || receiver.csend_type?
|
|
90
|
+
|
|
91
|
+
[nil, nil]
|
|
92
|
+
end
|
|
93
|
+
|
|
94
|
+
# Name segments of a receiver chain, root first: `folders.managed_by_platform`
|
|
95
|
+
# -> [:folders, :managed_by_platform]; `organization.organization_managers`
|
|
96
|
+
# inside `def self.x(organization:)` -> [:organization, :organization_managers]
|
|
97
|
+
# (a bound variable root contributes its name; the parser spells a
|
|
98
|
+
# kwarg as an lvar, a bare call as a send — both name the owner).
|
|
99
|
+
def receiver_chain_segments(receiver)
|
|
100
|
+
segments = []
|
|
101
|
+
root = each_receiver_link(receiver) { |link| segments.unshift(link.method_name) }
|
|
102
|
+
segments.unshift(root.children.first.to_s) if VARIABLE_ROOTS.include?(root&.type)
|
|
103
|
+
segments
|
|
104
|
+
end
|
|
105
|
+
|
|
106
|
+
# Yields each send/csend link of a receiver chain toward its root,
|
|
107
|
+
# returning the node that stopped the walk (nil, a variable, ...).
|
|
108
|
+
def each_receiver_link(receiver)
|
|
109
|
+
cursor = receiver
|
|
110
|
+
while cursor.is_a?(RuboCop::AST::Node) && (cursor.send_type? || cursor.csend_type?)
|
|
111
|
+
yield cursor
|
|
112
|
+
cursor = cursor.receiver
|
|
113
|
+
end
|
|
114
|
+
cursor
|
|
115
|
+
end
|
|
116
|
+
|
|
117
|
+
# [table, implied_fk] for an association-style chain, per the
|
|
118
|
+
# module-doc conventions (no plural segment -> the enclosing
|
|
119
|
+
# class's table, no implied key).
|
|
120
|
+
def association_resolution(receiver, node)
|
|
121
|
+
segments = receiver_chain_segments(receiver)
|
|
122
|
+
association = segments.find { |seg| ActiveSupport::Inflector.pluralize(seg.to_s) == seg.to_s }
|
|
123
|
+
return [enclosing_table(node), nil] unless association
|
|
124
|
+
|
|
125
|
+
owner_index = segments.index(association)
|
|
126
|
+
owner = owner_index.zero? ? enclosing_class_name(node) : segments[owner_index - 1].to_s
|
|
127
|
+
[ActiveSupport::Inflector.pluralize(association.to_s), "#{ActiveSupport::Inflector.underscore(owner)}_id"]
|
|
128
|
+
end
|
|
129
|
+
|
|
130
|
+
# The table a CONSTANT receiver names: `Activity` / `::Activity` ->
|
|
131
|
+
# `activities`; `Members::Filter` -> `members_filters` (Rails'
|
|
132
|
+
# own class-to-table arithmetic).
|
|
133
|
+
def receiver_table(const_node)
|
|
134
|
+
dotted_to_table(const_node.source)
|
|
135
|
+
end
|
|
136
|
+
|
|
137
|
+
def enclosing_class_name(node)
|
|
138
|
+
class_node = node.each_ancestor.find(&:class_type?)
|
|
139
|
+
return nil unless class_node
|
|
140
|
+
|
|
141
|
+
class_node.identifier.source
|
|
142
|
+
end
|
|
143
|
+
|
|
144
|
+
def enclosing_table(node)
|
|
145
|
+
name = enclosing_class_name(node)
|
|
146
|
+
name && dotted_to_table(name)
|
|
147
|
+
end
|
|
148
|
+
|
|
149
|
+
def dotted_to_table(dotted)
|
|
150
|
+
ActiveSupport::Inflector.pluralize(ActiveSupport::Inflector.underscore(dotted.sub(/\A::/, '')).tr('/', '_'))
|
|
151
|
+
end
|
|
152
|
+
|
|
153
|
+
# Literal keys of a write's own hash plus those contributed by
|
|
154
|
+
# query calls in its receiver chain. nil when the write's own
|
|
155
|
+
# attributes are dynamic.
|
|
156
|
+
def write_attribute_keys(write)
|
|
157
|
+
own = literal_hash_keys(write)
|
|
158
|
+
return nil unless own
|
|
159
|
+
|
|
160
|
+
own + chain_contributed_keys(write)
|
|
161
|
+
end
|
|
162
|
+
|
|
163
|
+
# A send's literal symbol/string hash keys, [] when it takes no
|
|
164
|
+
# hash, nil when its attributes are dynamic.
|
|
165
|
+
def literal_hash_keys(send_node)
|
|
166
|
+
hash = send_node.first_argument
|
|
167
|
+
return nil unless hash.nil? || hash.hash_type?
|
|
168
|
+
|
|
169
|
+
return [] if hash.nil?
|
|
170
|
+
|
|
171
|
+
hash.each_child_node(:pair).filter_map do |pair|
|
|
172
|
+
pair.key.value if pair.key.sym_type? || pair.key.str_type?
|
|
173
|
+
end
|
|
174
|
+
end
|
|
175
|
+
|
|
176
|
+
def chain_contributed_keys(write)
|
|
177
|
+
keys = []
|
|
178
|
+
each_receiver_link(write.receiver) do |link|
|
|
179
|
+
keys.concat(literal_hash_keys(link).compact) if ATTRIBUTE_CONTRIBUTORS.include?(link.method_name)
|
|
180
|
+
end
|
|
181
|
+
keys
|
|
182
|
+
end
|
|
183
|
+
|
|
184
|
+
# Both spellings an attribute key can satisfy: `member` writes the
|
|
185
|
+
# `member_id` column via association assignment, or `member` itself
|
|
186
|
+
# when it is a plain column.
|
|
187
|
+
def covered_columns(attribute_keys, implied_fk, tbl)
|
|
188
|
+
columns = attribute_keys.flat_map { |key| [key.to_s, "#{key}_id"] }
|
|
189
|
+
columns << implied_fk if implied_fk && tbl.columns.map(&:name).include?(implied_fk)
|
|
190
|
+
columns.to_set
|
|
191
|
+
end
|
|
192
|
+
|
|
193
|
+
# A unique index whose enforced columns (listed, or named inside
|
|
194
|
+
# its expression) are all covered.
|
|
195
|
+
def unique_index_covers?(index, candidates)
|
|
196
|
+
return false unless index.unique
|
|
197
|
+
|
|
198
|
+
enforced = index.columns.any? ? index.columns : expression_columns(index)
|
|
199
|
+
enforced.all? { |column| candidates.include?(column) }
|
|
200
|
+
end
|
|
201
|
+
end
|
|
202
|
+
end
|
|
203
|
+
end
|
|
204
|
+
end
|
|
205
|
+
end
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
module RuboCop
|
|
2
|
+
module Cop
|
|
3
|
+
module DevDoc
|
|
4
|
+
module Style
|
|
5
|
+
# Flag `Array(x)` / `Kernel.Array(x)` coercion; when nil is the only
|
|
6
|
+
# alternative to an array, say it with `x || []`.
|
|
7
|
+
#
|
|
8
|
+
# ## Rationale
|
|
9
|
+
# `Kernel#Array` coerces ANY input into an array, differently per
|
|
10
|
+
# shape:
|
|
11
|
+
#
|
|
12
|
+
# | Input | `Array(input)` |
|
|
13
|
+
# |---|---|
|
|
14
|
+
# | `nil` | `[]` |
|
|
15
|
+
# | `[a, b]` | `[a, b]` (unchanged) |
|
|
16
|
+
# | `{ k: v }` | `[[:k, v]]` (pairs) |
|
|
17
|
+
# | any other object | `[obj]` (wrapped) |
|
|
18
|
+
#
|
|
19
|
+
# Most call sites only want the first row: a nil guard. But the call
|
|
20
|
+
# reads as "this could be a scalar or a list" and silently accepts
|
|
21
|
+
# every other shape. When an unexpected shape arrives, the code does
|
|
22
|
+
# not fail — it iterates the wrong thing (Hash pairs, a wrapped
|
|
23
|
+
# scalar) and the bug surfaces somewhere downstream.
|
|
24
|
+
#
|
|
25
|
+
# The quiet one is the jsonb row: a nullable JSON column the code
|
|
26
|
+
# assumes holds an array can legally hold a Hash. `Array()` turns it
|
|
27
|
+
# into pairs and those render as list items with no error anywhere.
|
|
28
|
+
# Note `|| []` does NOT fix that Hash case — `(hash || []).each`
|
|
29
|
+
# yields the same pairs. What `|| []` fixes is nil (the assumption
|
|
30
|
+
# becomes visible) and the scalar (`.each` raises NoMethodError
|
|
31
|
+
# instead of silently wrapping). A column that may hold a Hash needs
|
|
32
|
+
# an explicit shape check: `value.is_a?(Array) ? value : []`.
|
|
33
|
+
#
|
|
34
|
+
# ❌
|
|
35
|
+
# rows = Array(params[:tags]).map { |t| ... } # strong params: array or nil
|
|
36
|
+
# ids = Array(order.line_item_ids) # `array: true` column
|
|
37
|
+
# Array(record.settings).each { ... } # jsonb, could hold a Hash
|
|
38
|
+
#
|
|
39
|
+
# ✔️
|
|
40
|
+
# rows = (params[:tags] || []).map { |t| ... }
|
|
41
|
+
# ids = order.line_item_ids || []
|
|
42
|
+
# settings = record.settings.is_a?(Array) ? record.settings : []
|
|
43
|
+
#
|
|
44
|
+
# `hash.fetch(:key, [])` is NOT an equivalent guard: `{ key: nil }
|
|
45
|
+
# .fetch(:key, [])` returns nil. `|| []` covers both an absent key
|
|
46
|
+
# and a key present with nil.
|
|
47
|
+
#
|
|
48
|
+
# ## Exception
|
|
49
|
+
# Real scalar-or-list input: a mail recipient that may be one string
|
|
50
|
+
# or a list, a filter scope documented as "one status or an array",
|
|
51
|
+
# an ActionMailer `formats:` option. There the coercion is the point
|
|
52
|
+
# — keep the call and disable inline with the reason:
|
|
53
|
+
#
|
|
54
|
+
# # rubocop:disable DevDoc/Style/AvoidKernelArray -- <why the input really is scalar-or-list>
|
|
55
|
+
# recipients = Array(message.to)
|
|
56
|
+
#
|
|
57
|
+
# `Array.wrap` (ActiveSupport: nil → [], Hash → [hash], scalar →
|
|
58
|
+
# [scalar]) is a different, narrower coercion and is not flagged.
|
|
59
|
+
#
|
|
60
|
+
# ## Relationship with Style/ArrayCoercion
|
|
61
|
+
# The stock cop (disabled by default, unsafe) pushes the OTHER way:
|
|
62
|
+
# from `[*x]` and `x = [x] unless x.is_a?(Array)` toward `Array(x)`.
|
|
63
|
+
# Do not enable both — keep this cop and write exceptions down with
|
|
64
|
+
# inline disables.
|
|
65
|
+
#
|
|
66
|
+
# @example
|
|
67
|
+
# # bad
|
|
68
|
+
# Array(params[:tags]).map { |t| t.upcase }
|
|
69
|
+
# Kernel.Array(order.line_item_ids).each { |id| id }
|
|
70
|
+
#
|
|
71
|
+
# # good
|
|
72
|
+
# (params[:tags] || []).map { |t| t.upcase }
|
|
73
|
+
# (order.line_item_ids || []).each { |id| id }
|
|
74
|
+
class AvoidKernelArray < Base
|
|
75
|
+
MSG = '`Array()` coerces any shape (Hash → pairs, scalar → [x]). If the only ' \
|
|
76
|
+
'alternative to an array is nil, use `x || []`; otherwise disable inline ' \
|
|
77
|
+
'with the reason.'.freeze
|
|
78
|
+
|
|
79
|
+
RESTRICT_ON_SEND = %i[Array].freeze
|
|
80
|
+
|
|
81
|
+
# `Array(x)`, `Kernel.Array(x)`, `::Kernel.Array(x)` — the
|
|
82
|
+
# Kernel#Array function by any spelling, with a single argument
|
|
83
|
+
# position (a splat `Array(*args)` included — it is the same call
|
|
84
|
+
# once the splat resolves). Any other receiver named `Array` (a
|
|
85
|
+
# user-defined `foo.Array(x)`) is not the Kernel function and is
|
|
86
|
+
# left alone.
|
|
87
|
+
def_node_matcher :kernel_array_call?, <<~PATTERN
|
|
88
|
+
{
|
|
89
|
+
(send nil? :Array _)
|
|
90
|
+
(send (const {nil? cbase} :Kernel) :Array _)
|
|
91
|
+
}
|
|
92
|
+
PATTERN
|
|
93
|
+
|
|
94
|
+
def on_send(node)
|
|
95
|
+
return unless kernel_array_call?(node)
|
|
96
|
+
|
|
97
|
+
add_offense(node.loc.selector)
|
|
98
|
+
end
|
|
99
|
+
end
|
|
100
|
+
end
|
|
101
|
+
end
|
|
102
|
+
end
|
|
103
|
+
end
|
|
@@ -82,6 +82,19 @@ module RuboCop
|
|
|
82
82
|
# even on a branch the run did not take, and a generic payload
|
|
83
83
|
# built WITHOUT the exception ("failed") still flags.
|
|
84
84
|
#
|
|
85
|
+
# ## Expected outcomes
|
|
86
|
+
# A clause rescuing ONLY classes listed in `ExpectedOutcomeClasses`
|
|
87
|
+
# (default: the concurrency verdicts — `RecordNotUnique`,
|
|
88
|
+
# `Deadlocked`, `LockWaitTimeout`, `StaleObjectError`,
|
|
89
|
+
# `SerializationFailure`) may stay silent: losing a race to a unique
|
|
90
|
+
# index is an outcome the code planned for, not a swallowed failure.
|
|
91
|
+
# Every class of the clause must be listed; one other class brings
|
|
92
|
+
# the body checks back. I/O failures are deliberately not in the
|
|
93
|
+
# default: an external failure is still a failure and must be
|
|
94
|
+
# reported, even when the code degrades around it. Whether the
|
|
95
|
+
# clause should exist at all is `DevDoc/Style/RescueJustification`'s
|
|
96
|
+
# question, not this cop's.
|
|
97
|
+
#
|
|
85
98
|
# ## Relationship with `Lint/SuppressedException` (stock)
|
|
86
99
|
# This cop is a strict superset at the stock cop's default settings
|
|
87
100
|
# (`AllowComments: true`, `AllowNil: true`): everything it flags —
|
|
@@ -123,6 +136,11 @@ module RuboCop
|
|
|
123
136
|
# `warning?` are not reporting. Add your project's in-house
|
|
124
137
|
# reporting verbs here.
|
|
125
138
|
#
|
|
139
|
+
# `ExpectedOutcomeClasses` — see "Expected outcomes" above. Matched
|
|
140
|
+
# against the constant as written (leading `::` ignored); an entry
|
|
141
|
+
# ending in `::` matches a namespace. Setting the key replaces the
|
|
142
|
+
# default list.
|
|
143
|
+
#
|
|
126
144
|
# NOTE: The walk judges the body syntactically: any matching call
|
|
127
145
|
# anywhere in the body counts as reporting, even one an if-condition
|
|
128
146
|
# hides, and a failure merely stashed (`@last_error = e`) does not.
|
|
@@ -131,7 +149,11 @@ module RuboCop
|
|
|
131
149
|
# unreported retry loop is the classic forever-silent failure. An
|
|
132
150
|
# empty-bodied clause's below-rescue marker also sits directly above
|
|
133
151
|
# the NEXT clause's `rescue`, so one marker justifies both — a single
|
|
134
|
-
# statement covering adjacent clauses, accepted as intended.
|
|
152
|
+
# statement covering adjacent clauses, accepted as intended. A marker
|
|
153
|
+
# trailing the last code line of one clause's body likewise counts
|
|
154
|
+
# for the next clause's `rescue` (the upward walk accepts trailing
|
|
155
|
+
# comments on code lines); `DevDoc/Style/RescueJustification` reads
|
|
156
|
+
# comment-only lines there instead. Only
|
|
135
157
|
# `app/` and `lib/` are inspected.
|
|
136
158
|
#
|
|
137
159
|
# @example
|
|
@@ -160,6 +182,7 @@ module RuboCop
|
|
|
160
182
|
# end
|
|
161
183
|
class NoSilentRescue < Base
|
|
162
184
|
include Auth::AdjacentJustification
|
|
185
|
+
include ExceptionClassList
|
|
163
186
|
include RescueNode
|
|
164
187
|
|
|
165
188
|
MSG = 'This rescue swallows the failure without a trace — report it (a logger/error-monitor ' \
|
|
@@ -172,8 +195,14 @@ module RuboCop
|
|
|
172
195
|
|
|
173
196
|
PROPAGATING_METHODS = %i[raise fail throw].freeze
|
|
174
197
|
|
|
198
|
+
DEFAULT_EXPECTED_OUTCOME_CLASSES = %w[
|
|
199
|
+
ActiveRecord::RecordNotUnique ActiveRecord::Deadlocked ActiveRecord::LockWaitTimeout
|
|
200
|
+
ActiveRecord::StaleObjectError ActiveRecord::SerializationFailure
|
|
201
|
+
].freeze
|
|
202
|
+
|
|
175
203
|
def on_resbody(node)
|
|
176
204
|
return if rescue_modifier?(node)
|
|
205
|
+
return if all_exceptions_listed?(node, expected_outcome_classes)
|
|
177
206
|
return if reports_or_propagates?(node.body)
|
|
178
207
|
return if surfaces_failure?(node)
|
|
179
208
|
return if adjacent_justification?(node) || leading_body_marker?(node)
|
|
@@ -192,30 +221,6 @@ module RuboCop
|
|
|
192
221
|
body.each_node(:send, :csend).any? { |call| reporting_call?(call) }
|
|
193
222
|
end
|
|
194
223
|
|
|
195
|
-
# The marker also counts in the body's own leading comment block —
|
|
196
|
-
# the contiguous comment-only lines directly below the `rescue`
|
|
197
|
-
# keyword, where adopters naturally state the reason. A comment
|
|
198
|
-
# after the first body statement is not adjacent to the rescue.
|
|
199
|
-
def leading_body_marker?(node)
|
|
200
|
-
marker = normalized_marker
|
|
201
|
-
comments_by_line = processed_source.comments.group_by { |comment| comment.location.line }
|
|
202
|
-
line = node.loc.keyword.line + 1
|
|
203
|
-
while (line_comments = comments_by_line[line]) && comment_only_line?(line)
|
|
204
|
-
return true if contains_marker?(line_comments, marker)
|
|
205
|
-
|
|
206
|
-
line += 1
|
|
207
|
-
end
|
|
208
|
-
|
|
209
|
-
false
|
|
210
|
-
end
|
|
211
|
-
|
|
212
|
-
# The String-downcasing the shared concern applies on its own
|
|
213
|
-
# path; a Regexp marker passes through for `contains_marker?`.
|
|
214
|
-
def normalized_marker
|
|
215
|
-
marker = justification_marker
|
|
216
|
-
marker.is_a?(String) ? marker.downcase : marker
|
|
217
|
-
end
|
|
218
|
-
|
|
219
224
|
# A body whose return value carries the bound exception hands the
|
|
220
225
|
# failure to the caller as data (error payload, rendered 4xx,
|
|
221
226
|
# persisted error column) — surfaced, not swallowed.
|
|
@@ -256,7 +261,12 @@ module RuboCop
|
|
|
256
261
|
|
|
257
262
|
def reporting_methods
|
|
258
263
|
@reporting_methods ||=
|
|
259
|
-
Array(cop_config.fetch('ReportingMethods', DEFAULT_REPORTING_METHODS))
|
|
264
|
+
Array(cop_config.fetch('ReportingMethods', DEFAULT_REPORTING_METHODS)) # rubocop:disable DevDoc/Style/AvoidKernelArray -- cop config accepts one method name or a list
|
|
265
|
+
end
|
|
266
|
+
|
|
267
|
+
def expected_outcome_classes
|
|
268
|
+
@expected_outcome_classes ||=
|
|
269
|
+
Array(cop_config.fetch('ExpectedOutcomeClasses', DEFAULT_EXPECTED_OUTCOME_CLASSES)) # rubocop:disable DevDoc/Style/AvoidKernelArray -- cop config accepts one class name or a list
|
|
260
270
|
end
|
|
261
271
|
|
|
262
272
|
def justification_marker
|
|
@@ -143,7 +143,7 @@ module RuboCop
|
|
|
143
143
|
end
|
|
144
144
|
|
|
145
145
|
def safe_receivers
|
|
146
|
-
DEFAULT_SAFE_DSL_RECEIVERS + Array(cop_config.fetch('SafeDSLReceivers', []))
|
|
146
|
+
DEFAULT_SAFE_DSL_RECEIVERS + Array(cop_config.fetch('SafeDSLReceivers', [])) # rubocop:disable DevDoc/Style/AvoidKernelArray -- cop config accepts one receiver name or a list
|
|
147
147
|
end
|
|
148
148
|
end
|
|
149
149
|
end
|