rubocop-dev_doc 0.17.0 → 0.19.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.
Files changed (48) hide show
  1. checksums.yaml +4 -4
  2. data/config/default.yml +461 -62
  3. data/config/obsoletion.yml +7 -3
  4. data/lib/dev_doc/i18n/pseudo_locale.rb +1 -1
  5. data/lib/dev_doc/i18n/tasks.rb +68 -0
  6. data/lib/dev_doc/railtie.rb +19 -0
  7. data/lib/dev_doc/test/lints/cross_tenant_canary_check.rb +1 -1
  8. data/lib/dev_doc/test/lints/cross_tenant_canary_sweep.rb +8 -3
  9. data/lib/dev_doc/test/lints/http_driven_controller_tests.rb +4 -0
  10. data/lib/dev_doc/test/lints/no_file_excludes.rb +1 -1
  11. data/lib/dev_doc/test/pseudo_i18n_crawler.rb +9 -0
  12. data/lib/rubocop/cop/dev_doc/auth/adjacent_justification.rb +44 -7
  13. data/lib/rubocop/cop/dev_doc/auth/load_resource_current_user_guard.rb +2 -2
  14. data/lib/rubocop/cop/dev_doc/auth/login_only_policy_justification.rb +1 -1
  15. data/lib/rubocop/cop/dev_doc/auth/unscoped_find_justification.rb +2 -2
  16. data/lib/rubocop/cop/dev_doc/bundler/conflicting_gem.rb +74 -0
  17. data/lib/rubocop/cop/dev_doc/exception_class_list.rb +32 -0
  18. data/lib/rubocop/cop/dev_doc/i18n/hardcoded_text.rb +243 -0
  19. data/lib/rubocop/cop/dev_doc/i18n/localizable_props.rb +69 -19
  20. data/lib/rubocop/cop/dev_doc/i18n/require_translation.rb +13 -17
  21. data/lib/rubocop/cop/dev_doc/i18n/text_shape.rb +94 -0
  22. data/lib/rubocop/cop/dev_doc/i18n/translation_key_prefix.rb +1 -1
  23. data/lib/rubocop/cop/dev_doc/migration/legacy_migration.rb +26 -0
  24. data/lib/rubocop/cop/dev_doc/migration/redundant_reference_index.rb +5 -15
  25. data/lib/rubocop/cop/dev_doc/migration/require_reference_index.rb +115 -0
  26. data/lib/rubocop/cop/dev_doc/rails/avoid_bypassing_validation.rb +81 -26
  27. data/lib/rubocop/cop/dev_doc/rails/avoid_lifecycle_method_override.rb +1 -1
  28. data/lib/rubocop/cop/dev_doc/rails/no_error_message_comparison.rb +178 -0
  29. data/lib/rubocop/cop/dev_doc/rails/no_errors_add_in_controller.rb +177 -0
  30. data/lib/rubocop/cop/dev_doc/rails/no_form_param_lookup_in_controller.rb +236 -0
  31. data/lib/rubocop/cop/dev_doc/style/avoid_kernel_array.rb +103 -0
  32. data/lib/rubocop/cop/dev_doc/style/in_memory_association_find.rb +162 -0
  33. data/lib/rubocop/cop/dev_doc/style/no_silent_rescue.rb +279 -0
  34. data/lib/rubocop/cop/dev_doc/style/no_unscoped_method_definitions.rb +1 -1
  35. data/lib/rubocop/cop/dev_doc/style/prefer_allowlist_symbol_param.rb +193 -0
  36. data/lib/rubocop/cop/dev_doc/style/rescue_justification.rb +330 -0
  37. data/lib/rubocop/cop/dev_doc/style/use_g_log.rb +133 -0
  38. data/lib/rubocop/cop/dev_doc/test/justification_covers.rb +216 -0
  39. data/lib/rubocop/cop/dev_doc/test/justification_header.rb +86 -5
  40. data/lib/rubocop/cop/dev_doc/test/prefer_find_sole_by.rb +146 -0
  41. data/lib/rubocop/cop/dev_doc/test/require_job_invocation_in_job_tests.rb +154 -0
  42. data/lib/rubocop/cop/dev_doc/test/require_unit_test_justification.rb +5 -24
  43. data/lib/rubocop/cop/dev_doc/test/test_file_placement.rb +30 -2
  44. data/lib/rubocop/cop/dev_doc/test/test_name_special_characters.rb +108 -0
  45. data/lib/rubocop/cop/dev_doc/view/prefer_prop_over_name.rb +11 -1
  46. data/lib/rubocop/dev_doc/version.rb +1 -1
  47. metadata +24 -4
  48. data/lib/rubocop/cop/dev_doc/i18n/report_text.rb +0 -76
@@ -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
@@ -0,0 +1,162 @@
1
+ module RuboCop
2
+ module Cop
3
+ module DevDoc
4
+ module Style
5
+ # Flag block-form `find`/`detect` on an ActiveRecord association
6
+ # declared in the same file, and demand the fork: refactor to
7
+ # `find_by`, or keep the in-memory view and justify it with a
8
+ # disable-reason.
9
+ #
10
+ # ## Rationale
11
+ # `Relation#find` with a block returns straight into
12
+ # `Enumerable#find` over the association's loaded target —
13
+ # persisted rows PLUS records built in memory and not yet saved.
14
+ # `find_by` is `where(...).take`: a SQL query that has never seen
15
+ # those records — and on an unsaved owner the association's DB
16
+ # scope is empty outright, so `find_by` returns nil while the
17
+ # loaded target holds the caller's submitted selection (`build`,
18
+ # nested attributes, a `*_ids=` assignment on a new record). A
19
+ # validator refactored to `find_by` stops seeing what was
20
+ # submitted, and the very check it exists to make silently
21
+ # passes. (On a persisted owner a `*_ids=` assignment writes the
22
+ # join rows immediately, inside a transaction, so both spellings
23
+ # agree there; the block form's edge is the unsaved population.)
24
+ # Code whose in-memory semantics are load-bearing but unexplained
25
+ # is one well-meaning `find_by` refactor away from a bug its suite
26
+ # does not pin, so the cop's job is to force that explanation to
27
+ # exist.
28
+ #
29
+ # ## Exception — the justified in-memory search
30
+ # Where the in-memory view is required (validators over unsaved
31
+ # records, nested-attribute flows), keep the block form and
32
+ # disable this cop inline, with the reason stated at the disable:
33
+ # why the loaded target — not the database — is the correct thing
34
+ # to search here. The disable-with-reason is the sanctioned exit
35
+ # (the same doctrine as the sibling doctrine cops); no magic
36
+ # comment keyword is recognized, because a keyword can be typed
37
+ # without the understanding.
38
+ #
39
+ # ## Relationship with DevDoc/Rails/NoBlockPredicateOnRelation
40
+ # That cop fires on PROVEN relation chains (`.where(...)`,
41
+ # scopes) and deliberately exempts bare association reads — its
42
+ # dogfooding history names "validators that must see unsaved
43
+ # in-memory records" as the exempted population. This cop is the
44
+ # complement: bare association reads proven by a same-file
45
+ # `has_many` / `has_and_belongs_to_many` declaration,
46
+ # `find`/`detect` only, about correctness justification rather
47
+ # than SQL push-down. The two never fire on the same node.
48
+ #
49
+ # NOTE: non-offenses, by design: an `lvar` shadowing the
50
+ # association's name (`tags = load_tags; tags.find { }` with a
51
+ # `has_many :tags` in the file); a same-file `def` receiver (a
52
+ # scope-shaped method is not a declaration); a `.where`-chained
53
+ # receiver (NoBlockPredicateOnRelation's territory);
54
+ # `has_one`/`belongs_to` names (singular associations do not
55
+ # enumerate); chained receivers such as
56
+ # `association.reload.find { }`; receivers on other objects
57
+ # (`other.posts.find { }`); and receivers in files that do not
58
+ # declare the association — a controller's
59
+ # `@post.comments.find { }` is a stated blind spot, since the
60
+ # declaring class is invisible outside its file. Safe-navigation
61
+ # receivers (`association&.find { }`) fire: same in-memory
62
+ # semantics. `&:sym` block-passes and numbered-block spellings
63
+ # fire like block literals; other block-passes
64
+ # (`&->(tag) { ... }`, `&method(:tag)`) are not detected — the
65
+ # same documented hole NoBlockPredicateOnRelation carries.
66
+ #
67
+ # @example
68
+ # # bad (declaration and search in one file)
69
+ # class Post < ApplicationRecord
70
+ # has_many :comments
71
+ #
72
+ # def foreign_comment?
73
+ # comments.find { |comment| comment.post_id != id }
74
+ # end
75
+ # end
76
+ #
77
+ # # good — the database side
78
+ # comments.find_by(post_id: id)
79
+ #
80
+ # # good — the justified in-memory side
81
+ # # The post is unsaved, so the submitted comments exist only in
82
+ # # the loaded target; find_by on an unsaved owner's association
83
+ # # is empty and would let a foreign comment through.
84
+ # # rubocop:disable DevDoc/Style/InMemoryAssociationFind
85
+ # comments.find { |comment| comment.post_id != id }
86
+ # # rubocop:enable DevDoc/Style/InMemoryAssociationFind
87
+ class InMemoryAssociationFind < Base
88
+ MSG = 'Block-form `%<method>s` on association `%<association>s` searches the loaded ' \
89
+ 'association, including unsaved in-memory children. Use `find_by` unless that ' \
90
+ 'in-memory view is required; if it is, keep the block form and disable this ' \
91
+ 'cop with that reason.'.freeze
92
+
93
+ RESTRICT_ON_SEND = %i[find detect].freeze
94
+
95
+ # A bare association read: `comments` or `self.comments`.
96
+ # Anything else — an lvar, an ivar, a constant, another object's
97
+ # call, a chained call — captures nothing and the send is left
98
+ # alone. The safe-navigation spelling reaches here through
99
+ # `on_csend`: `comments&.find` dispatches on_csend with a plain
100
+ # `(send nil? :comments)` receiver.
101
+ def_node_matcher :bare_receiver_name, <<~PATTERN
102
+ {(send nil? $_) (send (self) $_)}
103
+ PATTERN
104
+
105
+ # The name a `has_many` / `has_and_belongs_to_many` macro declares;
106
+ # the trailing `...` carries the scope lambda and options hash.
107
+ def_node_matcher :declared_association_name, <<~PATTERN
108
+ (send nil? {:has_many :has_and_belongs_to_many} $({sym str} _) ...)
109
+ PATTERN
110
+
111
+ def on_new_investigation
112
+ super
113
+ @association_names = nil
114
+ end
115
+
116
+ def on_send(node)
117
+ return unless node.block_literal? || symbol_block_pass?(node)
118
+ return if node.receiver.nil?
119
+
120
+ name = bare_receiver_name(unwrap_begin(node.receiver))
121
+ return unless name
122
+ return unless association_names.include?(name)
123
+
124
+ add_offense(node, message: format(MSG, method: node.method_name, association: name))
125
+ end
126
+
127
+ alias on_csend on_send
128
+
129
+ private
130
+
131
+ # A paren group's value is its LAST child (`(a; b).find { }`
132
+ # searches `b`), so unwrap to that before matching — same
133
+ # doctrine as NoBlockPredicateOnRelation.
134
+ def unwrap_begin(node)
135
+ node = node.children.last while node&.begin_type?
136
+ node
137
+ end
138
+
139
+ # `find(&:sym)` searches the loaded target exactly like the literal
140
+ # block form — one character shorter, so it must not be a dodge.
141
+ def symbol_block_pass?(node)
142
+ last = node.last_argument
143
+ last&.block_pass_type? && last.children.first&.sym_type?
144
+ end
145
+
146
+ # Every collection association name declared in this file, wherever
147
+ # the macro sits — class body, `included do` block in a concern.
148
+ def association_names
149
+ @association_names ||= Set.new.tap do |names|
150
+ next unless processed_source.ast
151
+
152
+ processed_source.ast.each_node(:send) do |node|
153
+ name = declared_association_name(node)
154
+ names << name.value.to_sym if name
155
+ end
156
+ end
157
+ end
158
+ end
159
+ end
160
+ end
161
+ end
162
+ end
@@ -0,0 +1,279 @@
1
+ module RuboCop
2
+ module Cop
3
+ module DevDoc
4
+ module Style
5
+ # Flag a block-form `rescue` whose body swallows the failure without
6
+ # a trace: no re-raise, no reporting call, no stated justification.
7
+ #
8
+ # ## Rationale
9
+ # A rescue that neither re-raises nor reports makes production
10
+ # failures invisible. The code keeps running on a fallback as if
11
+ # nothing happened, nothing reaches the logs or the error monitor,
12
+ # and the first observable symptom is wrong behavior or wrong data —
13
+ # usually far from the cause, which makes the swallow self-concealing:
14
+ # the very breakage that should have been seen is the one thing no
15
+ # one can see. The shape ships easily because it starts as "this must
16
+ # never break the page": a display helper degrading on a malformed
17
+ # file, an optional integration returning a fallback. Degrading is
18
+ # fine; degrading UNRECORDED is not — the report is one line beside
19
+ # the fallback.
20
+ #
21
+ # The broad spellings are the aggravating case: a bare `rescue` or
22
+ # `rescue StandardError` catches programming errors (NoMethodError,
23
+ # TypeError) together with the expected environmental failure, so a
24
+ # bug in the very code being protected is silenced too. A narrow,
25
+ # named exception class shrinks that blast radius but still owes the
26
+ # same three exits.
27
+ #
28
+ # ## What an offense means
29
+ # An offense does NOT assert the swallow is a defect. The cop cannot
30
+ # see whether a deliberate degradation is correct for the call site —
31
+ # it asserts the swallow is UNDOCUMENTED. A rescue that degrades on
32
+ # purpose is a violation until the reason is stated in the marker
33
+ # comment; the marker is the intended resolution for deliberate
34
+ # ones, not a workaround. On adoption, expect a one-time
35
+ # justification sweep over existing rescues — writing each reason
36
+ # honestly IS the audit.
37
+ #
38
+ # ## Remedy
39
+ # The blessed shape is report-then-degrade — one reporting line,
40
+ # then the fallback:
41
+ #
42
+ # ❌ the failure vanishes
43
+ # def verified_suffix
44
+ # stamp = read_stamp
45
+ # "verified #{stamp.fetch('checked_at')}"
46
+ # rescue StandardError
47
+ # nil
48
+ # end
49
+ #
50
+ # ✔️ report, then degrade — the page still renders, the failure
51
+ # still lands where someone will read it
52
+ # def verified_suffix
53
+ # stamp = read_stamp
54
+ # "verified #{stamp.fetch('checked_at')}"
55
+ # rescue StandardError => e
56
+ # logger.error("stamp unreadable, suffix suppressed: #{e.class} #{e.message}")
57
+ # nil
58
+ # end
59
+ #
60
+ # ✔️ re-raise (after any partial handling) — the caller decides
61
+ #
62
+ # ✔️ deliberate degradation, reason stated for review
63
+ # def verified_suffix
64
+ # stamp = read_stamp
65
+ # "verified #{stamp.fetch('checked_at')}"
66
+ # rescue StandardError
67
+ # # silent-rescue: cosmetic suffix only; the stamp file is
68
+ # # machine-regenerated and a stale suffix must not break the page.
69
+ # nil
70
+ # end
71
+ #
72
+ # ## Returning the failure as data counts as surfacing it
73
+ # A body whose return VALUE carries the bound exception — an error
74
+ # payload (`Result.new(status: 502, body: { error: e.class.to_s })`),
75
+ # a rendered 4xx (`render json: { error: e.message }, status:
76
+ # :bad_request`), an error column persisted for a status page — is
77
+ # not silent: the failure leaves the method with the caller, who
78
+ # decides what to do with it, exactly as with a re-raise. The cop
79
+ # reads this structurally: the body's final expression (or any
80
+ # explicit `return`) references the bound exception variable.
81
+ # Blind spots of that reading, for reviewers: the reference counts
82
+ # even on a branch the run did not take, and a generic payload
83
+ # built WITHOUT the exception ("failed") still flags.
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
+ #
98
+ # ## Relationship with `Lint/SuppressedException` (stock)
99
+ # This cop is a strict superset at the stock cop's default settings
100
+ # (`AllowComments: true`, `AllowNil: true`): everything it flags —
101
+ # the empty, uncommented rescue — this cop flags too, and it also
102
+ # catches the `nil`, literal and silent-action bodies those settings
103
+ # allow, requiring a named marker phrase instead of any comment.
104
+ # Disable `Lint/SuppressedException` when enabling this one to avoid
105
+ # double-flagging the empty-body corner.
106
+ #
107
+ # Modifier rescues (`value rescue fallback`) are deliberately out of
108
+ # scope: the modifier form has no room to report, so every instance
109
+ # is categorically silent, and `Style/RescueModifier` already flags
110
+ # all of them on form alone. Keep that cop enabled; this one adds
111
+ # nothing there.
112
+ #
113
+ # ## Configuration
114
+ # `JustificationMarker` (default: `silent-rescue:`) — the phrase the
115
+ # adjacent comment must contain: on the `rescue` line itself
116
+ # (trailing), in the contiguous comment block ending on the line
117
+ # directly above the `rescue` keyword, or in the body's leading
118
+ # comment block directly below it (measured adopters put the reason
119
+ # there; unlike the auth marker cops both sides of the `rescue`
120
+ # keyword are accepted — the marker still has to name the phrase
121
+ # deliberately, whichever placement reads best).
122
+ #
123
+ # `ReportingMethods` (default: `log`, `warn`, `error`, `errors`,
124
+ # `exception`, `fatal`, `critical`, `notify`, `notice`, `report`,
125
+ # `capture`, `track`, `instrument`, `monitor`, `alert`,
126
+ # `breadcrumb`, `handle`) — matched as whole name TOKENS, not
127
+ # substrings: a method counts when, after stripping a trailing
128
+ # `?`/`!`/`=`, any of its `_`-separated segments equals one of these
129
+ # words. Receiver-agnostic, so any logger or error-monitor API
130
+ # counts (`logger.error(e)`, `Sentry.capture_exception(e)`,
131
+ # `NewRelic::Agent.notice_error(e)`), a delegating handler whose
132
+ # name says what it does counts (`handle_api_error(e)`), and a body
133
+ # surfacing the failure through the record counts
134
+ # (`record.errors.add(:base, ...)` — the user sees it). A name that
135
+ # merely CONTAINS a verb does not: `login_path`, `tracking_number`,
136
+ # `warning?` are not reporting. Add your project's in-house
137
+ # reporting verbs here.
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
+ #
144
+ # NOTE: The walk judges the body syntactically: any matching call
145
+ # anywhere in the body counts as reporting, even one an if-condition
146
+ # hides, and a failure merely stashed (`@last_error = e`) does not.
147
+ # Reviewers judge whether what gets reported is the right failure.
148
+ # Retry-only bodies (`rescue; retry; end`) are flagged — an
149
+ # unreported retry loop is the classic forever-silent failure. An
150
+ # empty-bodied clause's below-rescue marker also sits directly above
151
+ # the NEXT clause's `rescue`, so one marker justifies both — a single
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
157
+ # `app/` and `lib/` are inspected.
158
+ #
159
+ # @example
160
+ # # bad — fallback, no trace
161
+ # begin
162
+ # sync_prices
163
+ # rescue StandardError
164
+ # []
165
+ # end
166
+ #
167
+ # # good — report, then degrade
168
+ # begin
169
+ # sync_prices
170
+ # rescue StandardError => e
171
+ # logger.error("price sync failed: #{e.message}")
172
+ # []
173
+ # end
174
+ #
175
+ # # good — deliberate, stated
176
+ # begin
177
+ # sync_prices
178
+ # rescue StandardError
179
+ # # silent-rescue: prices refresh hourly; a failed refresh keeps
180
+ # # the list from the last successful run.
181
+ # []
182
+ # end
183
+ class NoSilentRescue < Base
184
+ include Auth::AdjacentJustification
185
+ include ExceptionClassList
186
+ include RescueNode
187
+
188
+ MSG = 'This rescue swallows the failure without a trace — report it (a logger/error-monitor ' \
189
+ 'call), re-raise it, or state the reason in a "%<marker>s" comment next to the rescue.'.freeze
190
+
191
+ DEFAULT_REPORTING_METHODS = %w[
192
+ log warn error errors exception fatal critical notify notice report capture track
193
+ instrument monitor alert breadcrumb handle
194
+ ].freeze
195
+
196
+ PROPAGATING_METHODS = %i[raise fail throw].freeze
197
+
198
+ DEFAULT_EXPECTED_OUTCOME_CLASSES = %w[
199
+ ActiveRecord::RecordNotUnique ActiveRecord::Deadlocked ActiveRecord::LockWaitTimeout
200
+ ActiveRecord::StaleObjectError ActiveRecord::SerializationFailure
201
+ ].freeze
202
+
203
+ def on_resbody(node)
204
+ return if rescue_modifier?(node)
205
+ return if all_exceptions_listed?(node, expected_outcome_classes)
206
+ return if reports_or_propagates?(node.body)
207
+ return if surfaces_failure?(node)
208
+ return if adjacent_justification?(node) || leading_body_marker?(node)
209
+
210
+ add_offense(node.loc.keyword, message: format(MSG, marker: justification_marker))
211
+ end
212
+
213
+ private
214
+
215
+ # Any reporting or propagating call in the body — including the
216
+ # body itself when it is that call — makes the rescue audible.
217
+ # An empty body reports nothing by construction.
218
+ def reports_or_propagates?(body)
219
+ return false if body.nil?
220
+
221
+ body.each_node(:send, :csend).any? { |call| reporting_call?(call) }
222
+ end
223
+
224
+ # A body whose return value carries the bound exception hands the
225
+ # failure to the caller as data (error payload, rendered 4xx,
226
+ # persisted error column) — surfaced, not swallowed.
227
+ def surfaces_failure?(node)
228
+ exception_variable = node.exception_variable
229
+ return false unless exception_variable
230
+
231
+ body = node.body
232
+ return false if body.nil?
233
+
234
+ name = exception_variable.name
235
+ references_exception?(final_expression(body), name) ||
236
+ body.each_descendant(:return).any? do |returned|
237
+ references_exception?(returned.children.first, name)
238
+ end
239
+ end
240
+
241
+ def final_expression(body)
242
+ body.begin_type? ? body.children.last : body
243
+ end
244
+
245
+ def references_exception?(node, name)
246
+ return false unless node
247
+
248
+ node.each_node(:lvar).any? { |lvar| lvar.children.first == name }
249
+ end
250
+
251
+ # Token match, not substring: `login_path` must not read as
252
+ # reporting. `warning?`/`save!`/`level=` lose their suffix before
253
+ # splitting.
254
+ def reporting_call?(call)
255
+ name = call.method_name
256
+ return true if PROPAGATING_METHODS.include?(name)
257
+
258
+ tokens = name.to_s.sub(/[?!=]\z/, '').split('_')
259
+ reporting_methods.any? { |verb| tokens.include?(verb) }
260
+ end
261
+
262
+ def reporting_methods
263
+ @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
270
+ end
271
+
272
+ def justification_marker
273
+ cop_config.fetch('JustificationMarker', 'silent-rescue:')
274
+ end
275
+ end
276
+ end
277
+ end
278
+ end
279
+ end
@@ -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