rubocop-dev_doc 0.18.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 (32) hide show
  1. checksums.yaml +4 -4
  2. data/config/default.yml +161 -2
  3. data/lib/dev_doc/i18n/pseudo_locale.rb +1 -1
  4. data/lib/dev_doc/test/lints/cross_tenant_canary_check.rb +1 -1
  5. data/lib/dev_doc/test/lints/cross_tenant_canary_sweep.rb +6 -3
  6. data/lib/dev_doc/test/lints/http_driven_controller_tests.rb +2 -0
  7. data/lib/dev_doc/test/lints/no_file_excludes.rb +1 -1
  8. data/lib/dev_doc/test/pseudo_i18n_crawler.rb +4 -0
  9. data/lib/rubocop/cop/dev_doc/auth/adjacent_justification.rb +44 -7
  10. data/lib/rubocop/cop/dev_doc/auth/load_resource_current_user_guard.rb +2 -2
  11. data/lib/rubocop/cop/dev_doc/auth/login_only_policy_justification.rb +1 -1
  12. data/lib/rubocop/cop/dev_doc/auth/unscoped_find_justification.rb +2 -2
  13. data/lib/rubocop/cop/dev_doc/bundler/conflicting_gem.rb +74 -0
  14. data/lib/rubocop/cop/dev_doc/exception_class_list.rb +32 -0
  15. data/lib/rubocop/cop/dev_doc/i18n/translation_key_prefix.rb +1 -1
  16. data/lib/rubocop/cop/dev_doc/migration/legacy_migration.rb +26 -0
  17. data/lib/rubocop/cop/dev_doc/migration/redundant_reference_index.rb +5 -15
  18. data/lib/rubocop/cop/dev_doc/migration/require_reference_index.rb +115 -0
  19. data/lib/rubocop/cop/dev_doc/rails/avoid_lifecycle_method_override.rb +1 -1
  20. data/lib/rubocop/cop/dev_doc/rails/no_error_message_comparison.rb +178 -0
  21. data/lib/rubocop/cop/dev_doc/rails/no_form_param_lookup_in_controller.rb +1 -1
  22. data/lib/rubocop/cop/dev_doc/style/avoid_kernel_array.rb +103 -0
  23. data/lib/rubocop/cop/dev_doc/style/no_silent_rescue.rb +36 -26
  24. data/lib/rubocop/cop/dev_doc/style/no_unscoped_method_definitions.rb +1 -1
  25. data/lib/rubocop/cop/dev_doc/style/rescue_justification.rb +330 -0
  26. data/lib/rubocop/cop/dev_doc/test/justification_covers.rb +216 -0
  27. data/lib/rubocop/cop/dev_doc/test/justification_header.rb +86 -5
  28. data/lib/rubocop/cop/dev_doc/test/require_job_invocation_in_job_tests.rb +154 -0
  29. data/lib/rubocop/cop/dev_doc/test/require_unit_test_justification.rb +5 -24
  30. data/lib/rubocop/cop/dev_doc/test/test_file_placement.rb +30 -2
  31. data/lib/rubocop/dev_doc/version.rb +1 -1
  32. metadata +12 -3
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 3852833893968d60a5c0c198ffd3a2f34cb524a71998464a27803de2d56b44de
4
- data.tar.gz: 1b4f675aa6967bca65d6f706997c06c73fe3b954b4092f6f8586e5c17b1e16b8
3
+ metadata.gz: ff4f06f5a2bc2e22f493fdc53c810709df74c457ac08ce00b5db539a2947d74d
4
+ data.tar.gz: f709c72a76c989795d08156449a9ac166e44838f04217084c7bceb4da3072911
5
5
  SHA512:
6
- metadata.gz: 3b4be761462f9974fa8caa317e1df9d71ead56160dc4d9d0e7b98407af11a8835f09a888e4b8677448981c6e8e032129312d6e469f7134426714351e594cdc64
7
- data.tar.gz: 5aca39f093385aae489a8c1a18fcf43eff4995dd7a5d575d237e5a472a8477457789a9cb201ce5ba09abdc6c49fcbf80fbd761467ee2d46447f5ee943111292f
6
+ metadata.gz: ce797e0cd5bda079b45274bb11c521055a65ff71dae446d9e293c1d838d2dde97563cfd13b677589bc79b3a550cc00b6943ff3b3e51311ca7c3ee5e5489d3565
7
+ data.tar.gz: fd06374240e731ac64d5be478e46ece5f8b3b86f4ebb7a114e980485db7b1d399a9c05e0737722325f65fba041bb63e20b40f35f018cbdf21501a98882c6c1a1
data/config/default.yml CHANGED
@@ -7,6 +7,10 @@ DevDoc/Auth:
7
7
  DocumentationBaseURL: https://github.com/hgani/dev-doc/blob/main/docs/cops
8
8
  DocumentationExtension: ".md"
9
9
 
10
+ DevDoc/Bundler:
11
+ DocumentationBaseURL: https://github.com/hgani/dev-doc/blob/main/docs/cops
12
+ DocumentationExtension: ".md"
13
+
10
14
  DevDoc/I18n:
11
15
  DocumentationBaseURL: https://github.com/hgani/dev-doc/blob/main/docs/cops
12
16
  DocumentationExtension: ".md"
@@ -35,6 +39,26 @@ DevDoc/View:
35
39
  DocumentationBaseURL: https://github.com/hgani/dev-doc/blob/main/docs/cops
36
40
  DocumentationExtension: ".md"
37
41
 
42
+ DevDoc/Bundler/ConflictingGem:
43
+ Description: "Gems that duplicate a concern glib already provides (versioning, authorization, uploads, soft delete). Use the glib way instead."
44
+ Enabled: true
45
+ Include:
46
+ - "**/Gemfile"
47
+ - "**/gems.rb"
48
+ ConflictingGems:
49
+ paper_trail: "use Glib::SnapshotV2 (active_snapshot) for versioning and audit history."
50
+ audited: "use Glib::SnapshotV2 (active_snapshot) for versioning and audit history."
51
+ logidze: "use Glib::SnapshotV2 (active_snapshot) for versioning and audit history."
52
+ cancancan: "glib uses Pundit; write a policy."
53
+ action_policy: "glib uses Pundit; write a policy."
54
+ carrierwave: "use ActiveStorage; glib's file fields bind to attachments."
55
+ shrine: "use ActiveStorage; glib's file fields bind to attachments."
56
+ paperclip: "use ActiveStorage; glib's file fields bind to attachments."
57
+ kt-paperclip: "use ActiveStorage; glib's file fields bind to attachments."
58
+ paranoia: "soft deletion is project-specific; implement it in the model (see 01_basic.md item 7)."
59
+ acts_as_paranoid: "soft deletion is project-specific; implement it in the model (see 01_basic.md item 7)."
60
+ discard: "soft deletion is project-specific; implement it in the model (see 01_basic.md item 7)."
61
+
38
62
  DevDoc/Migration/AvoidJsonColumn:
39
63
  Description: "Use `jsonb` instead of `json` for column types."
40
64
  Enabled: true
@@ -222,6 +246,20 @@ DevDoc/Rails/NoErrorsAddInController:
222
246
  Include:
223
247
  - "app/controllers/**/*.rb"
224
248
 
249
+ # The text of an error message is written in two places — the `errors.add`
250
+ # that produces it and the branch that matches it — and only both copies
251
+ # staying identical keeps the branch alive; rewording, translating, or a
252
+ # second error silently breaks it. Add the error with a symbol type and
253
+ # branch on the type (`errors.of_kind?` / `errors.added?`), not the text.
254
+ # Measured over 13 consuming apps (one clone per origin, plus one non-glib
255
+ # Rails app): one offense, a true positive.
256
+ DevDoc/Rails/NoErrorMessageComparison:
257
+ Description: "Do not branch on the text of an ActiveModel error message (`errors.full_messages`, `errors[:attr]`, `errors.messages`, and their kin compared to a literal); add the error with a symbol type and check it with `errors.of_kind?` / `errors.added?`."
258
+ Enabled: true
259
+ Include:
260
+ - "app/**/*.rb"
261
+ - "app/**/*.jbuilder"
262
+
225
263
  DevDoc/Rails/EnumMustBeSymbolized:
226
264
  Description: "Declare enums with `enum_symbolize :foo, { … }` instead of a bare `enum`, so the attribute type is set before the enum and the reader returns a symbol."
227
265
  Enabled: true
@@ -359,11 +397,13 @@ DevDoc/Migration/NoBulkChangeTable:
359
397
  - "db/migrate/*.rb"
360
398
  - "db/migrate/**/*.rb"
361
399
 
362
- # The reference-options trio. Each of a reference's three options gets the
400
+ # The reference-option cops. Each of a reference's options gets the
363
401
  # enforcement shape its house position calls for:
364
402
  # - foreign_key: has one right value (constrain) -> enforce the VALUE.
365
403
  # - null: both values are legitimate -> enforce EXPLICITNESS (either passes).
366
- # - index: the default is already correct -> enforce SILENCE (flag redundancy).
404
+ # - index: the default is already correct -> enforce SILENCE (flag
405
+ # redundancy), and opting out is banned — every FK column carries its
406
+ # own index (see RequireReferenceIndex below for why).
367
407
  # Net effect: everything written on a reference line is a decision, everything
368
408
  # omitted is doctrine.
369
409
  DevDoc/Migration/RequireReferenceForeignKey:
@@ -373,6 +413,17 @@ DevDoc/Migration/RequireReferenceForeignKey:
373
413
  - "db/migrate/*.rb"
374
414
  - "db/migrate/**/*.rb"
375
415
 
416
+ # No autocorrect: removing `index: false` changes the migration's resulting
417
+ # schema (the index comes back), which is the developer's decision to make.
418
+ # Migration[4.2] classes are skipped (the default there is `index: false`, so
419
+ # the written option restates it rather than opting out).
420
+ DevDoc/Migration/RequireReferenceIndex:
421
+ Description: "References must not opt out of their default index (`index: false` is banned) — every FK column carries its own index."
422
+ Enabled: true
423
+ Include:
424
+ - "db/migrate/*.rb"
425
+ - "db/migrate/**/*.rb"
426
+
376
427
  DevDoc/Migration/ExplicitNullOnReference:
377
428
  Description: "References must state `null:` explicitly — optional and mandatory are both legitimate."
378
429
  Enabled: true
@@ -458,6 +509,22 @@ DevDoc/Style/AvoidSymbolizingBoundaryInput:
458
509
  Description: "Unvalidated `.to_sym` on params/request.headers lets any client value into the symbol domain; allow-list it (glib_allowlist_symbol_param) instead."
459
510
  Enabled: true
460
511
 
512
+ # Measured on one consuming app's app/ (2026-11-08: 21 hits in 1191 files —
513
+ # 17 drift/risky, 4 justified scalar-or-list inputs to keep via inline
514
+ # disables there) and on this repo's own lib (17 hits: 1 true positive
515
+ # converted to `|| []`, 16 genuine one-or-many shapes kept with inline
516
+ # disables — I18n scope args, mail recipients, persona tenant keys,
517
+ # cop-config values, an Exclude section). Tests are excluded because there `Array()` mostly
518
+ # walks rendered JSON output, where a silent coercion hides at worst a bad
519
+ # assertion, not data corruption (same Exclude shape as
520
+ # DevDoc/Rails/AvoidBypassingValidation).
521
+ DevDoc/Style/AvoidKernelArray:
522
+ Description: "Avoid `Array()` coercion; use `x || []` when nil is the only alternative. Do not enable stock Style/ArrayCoercion alongside."
523
+ Enabled: true
524
+ Exclude:
525
+ - "spec/**/*"
526
+ - "test/**/*"
527
+
461
528
  DevDoc/Style/LiteralOrInWhenClause:
462
529
  Description: "`||`/`&&` between literals in a `when` clause folds to one value — the other literal silently never matches; use comma-separated alternatives."
463
530
  Enabled: true
@@ -737,6 +804,22 @@ DevDoc/Test/RequireGlibIntegrationBase:
737
804
  - "test/mailers/**/*_test.rb"
738
805
  - "test/channels/**/*_test.rb"
739
806
 
807
+ # The entry-point check for the inbound-edge directory: a *Test class under
808
+ # test/jobs that never invokes the job (perform / perform_now / perform_later /
809
+ # perform_enqueued_jobs) is a service-flow test parked where the lints trust
810
+ # it — dispatch, guards and follow-up enqueues never run (observed 2026-10:
811
+ # ~18 integration-base cases in one consumer file drove a service .call and
812
+ # never the job). Same-file ancestor classes satisfy via their own bodies.
813
+ # The entry-point set lives in code, not here: config lists are droppable,
814
+ # code baselines are not. An enqueue-routing test whose trigger is not a
815
+ # job send (a request, a service call) takes an inline disable with a
816
+ # rationale.
817
+ DevDoc/Test/RequireJobInvocationInJobTests:
818
+ Description: "Every *Test class under test/jobs must invoke the job (perform/perform_now/perform_later/perform_enqueued_jobs) directly or via a same-file ancestor — a job test that drives a service instead never exercises dispatch, guards or follow-up enqueues."
819
+ Enabled: true
820
+ Include:
821
+ - "test/jobs/**/*_test.rb"
822
+
740
823
  # Previews render on every GET in development — persistence inside one mutates
741
824
  # the dev DB as a side effect of viewing an email. Also guards the preview
742
825
  # harness as a relocation target: mailer-body variants staged for snapshots
@@ -851,6 +934,32 @@ DevDoc/Test/RequireUnitTestJustification:
851
934
  Include:
852
935
  - "test/**/*_test.rb"
853
936
 
937
+ DevDoc/Test/JustificationCovers:
938
+ Description: "A justification header must list the methods its claim covers (Covers: line), and every test in the file must call one of them."
939
+ Enabled: true
940
+ CoversPhrase: "covers:"
941
+ # The marker phrase gates this cop: files without it are
942
+ # RequireUnitTestJustification's to report — this cop never double-reports
943
+ # a missing header.
944
+ MarkerPhrase: "deliberate exception"
945
+ # Applicability is the shared justification_header_required? predicate
946
+ # (in the cops' TestFilePlacement module), which reads the base and
947
+ # directory keys below — mirror them from
948
+ # DevDoc/Test/RequireUnitTestJustification and keep the two entries in
949
+ # sync, or the cops police different file sets.
950
+ NonHttpBaseClasses:
951
+ - Glib::NonHttpIntegrationTest
952
+ UnitTestDirectories:
953
+ - models
954
+ - services
955
+ - helpers
956
+ NonHttpDirectories:
957
+ - jobs
958
+ - mailers
959
+ - channels
960
+ Include:
961
+ - "test/**/*_test.rb"
962
+
854
963
  Naming/PredicatePrefix:
855
964
  Enabled: false
856
965
 
@@ -1316,6 +1425,56 @@ DevDoc/Style/NoSilentRescue:
1316
1425
  - "alert"
1317
1426
  - "breadcrumb"
1318
1427
  - "handle"
1428
+ # A clause rescuing only these is an expected outcome (a lost race), not a
1429
+ # swallowed failure, and may stay silent. I/O failures are not here: they
1430
+ # are still failures and must be reported.
1431
+ ExpectedOutcomeClasses:
1432
+ - "ActiveRecord::RecordNotUnique"
1433
+ - "ActiveRecord::Deadlocked"
1434
+ - "ActiveRecord::LockWaitTimeout"
1435
+ - "ActiveRecord::StaleObjectError"
1436
+ - "ActiveRecord::SerializationFailure"
1437
+
1438
+ DevDoc/Style/RescueJustification:
1439
+ Description: "Every rescue clause either rescues only failures no validator can prevent (races, I/O), propagates, or states its reason in a `rescue-reason: <category>: <why>` comment."
1440
+ Enabled: true
1441
+ Include:
1442
+ - "app/**/*.rb"
1443
+ - "lib/**/*.rb"
1444
+ JustificationMarker: "rescue-reason:"
1445
+ # Failures no validator of ours can prevent. A trailing `::` matches a namespace.
1446
+ ExpectedErrorClasses:
1447
+ # concurrency verdicts — validation is point-in-time, the constraint is the check
1448
+ - "ActiveRecord::RecordNotUnique"
1449
+ - "ActiveRecord::Deadlocked"
1450
+ - "ActiveRecord::LockWaitTimeout"
1451
+ - "ActiveRecord::StaleObjectError"
1452
+ - "ActiveRecord::SerializationFailure"
1453
+ # I/O to another system
1454
+ - "ActiveRecord::ConnectionNotEstablished"
1455
+ - "ActiveRecord::NoDatabaseError"
1456
+ - "ActiveRecord::ConnectionTimeoutError"
1457
+ - "Errno::"
1458
+ - "Net::"
1459
+ - "Timeout::Error"
1460
+ - "IOError"
1461
+ - "EOFError"
1462
+ - "SocketError"
1463
+ - "OpenSSL::SSL::SSLError"
1464
+ Categories:
1465
+ bulkhead:
1466
+ Meaning: "one failure unit of a batch or async sweep must not abort the rest; one per unit of work, reported"
1467
+ side-effect:
1468
+ Meaning: "a secondary effect that must not fail the primary action it rides on"
1469
+ degrade:
1470
+ Meaning: "a user-facing path that degrades to a fallback and reports (01a item 5)"
1471
+ boundary-parse:
1472
+ Meaning: "untrusted external input parsed here; the parse is the validation"
1473
+ surface:
1474
+ Meaning: "a non-bang wrapper turning a bang method's exception into the contract's failure channel (false + errors)"
1475
+ delivery:
1476
+ Meaning: "a controller rendering a domain error raised below it"
1477
+ Path: "app/controllers/"
1319
1478
 
1320
1479
  DevDoc/Style/UseGLog:
1321
1480
  Description: "Route logging through GLog (glib-web) — flag Rails.logger.<any> and Rollbar's reporting methods (error/warning/info/debug/critical/log) outside the facade; Rollbar.configure and other setup calls are not reporting."
@@ -142,7 +142,7 @@ module DevDoc
142
142
  private
143
143
 
144
144
  def skip?(key, scope)
145
- head = Array(scope).first || key.to_s[/\A[^.]+/]
145
+ head = Array(scope).first || key.to_s[/\A[^.]+/] # rubocop:disable DevDoc/Style/AvoidKernelArray -- I18n's scope arg is one key or a key list by API contract
146
146
  SKIP_NAMESPACES.include?(head.to_s)
147
147
  end
148
148
 
@@ -102,7 +102,7 @@ module DevDoc
102
102
  end
103
103
 
104
104
  def normalize(emails)
105
- Array(emails).compact.map { |email| email.to_s.downcase }
105
+ Array(emails).compact.map { |email| email.to_s.downcase } # rubocop:disable DevDoc/Style/AvoidKernelArray -- recipients may be one address or a list
106
106
  end
107
107
  private_class_method :normalize
108
108
  end
@@ -71,20 +71,23 @@ module DevDoc
71
71
  leaked = CrossTenantCanaryCheck.leaked_markers(__dev_doc_response_body, foreign)
72
72
  return if leaked.empty?
73
73
 
74
- raise Minitest::Assertion, __dev_doc_canary_message(allowed, leaked)
74
+ allowed_list = Array(allowed).join(', ') # rubocop:disable DevDoc/Style/AvoidKernelArray -- a persona's allowed tenant keys are one or many by config
75
+ raise Minitest::Assertion, __dev_doc_canary_message(allowed_list, leaked)
75
76
  end
76
77
 
77
78
  def __dev_doc_response_body
78
79
  response&.body.to_s
79
80
  rescue StandardError
81
+ # rescue-reason: side-effect: the canary rides on every request test
82
+ # and must not fail it.
80
83
  # silent-rescue: the canary check must never fail on an unreadable
81
84
  # response body; an empty body simply carries no markers to match.
82
85
  ''
83
86
  end
84
87
 
85
- def __dev_doc_canary_message(allowed, leaked)
88
+ def __dev_doc_canary_message(allowed_list, leaked)
86
89
  <<~MSG
87
- Cross-tenant leak: this persona (allowed tenants: #{Array(allowed).join(', ')}) received a
90
+ Cross-tenant leak: this persona (allowed tenants: #{allowed_list}) received a
88
91
  response containing #{leaked.join(', ')}, which belongs to a tenant it must not see.
89
92
  Route: #{__dev_doc_route_label}
90
93
  Another tenant's data rendered into this persona's response — a cross-tenant read leak.
@@ -103,6 +103,8 @@ module DevDoc
103
103
  def __dev_doc_source_file
104
104
  method(name).source_location&.first
105
105
  rescue NameError
106
+ # rescue-reason: side-effect: the source file only labels the failure
107
+ # message; it must not replace the assertion with a NameError.
106
108
  # silent-rescue: an unresolvable test-method name means the source
107
109
  # file is unknown; the location line renders without it.
108
110
  nil
@@ -51,7 +51,7 @@ module DevDoc
51
51
  # Literal-path (non-glob, non-allowlisted) entries of one section's
52
52
  # `Exclude:` list.
53
53
  def literal_excludes(section_config)
54
- Array(section_config['Exclude']).select do |entry|
54
+ Array(section_config['Exclude']).select do |entry| # rubocop:disable DevDoc/Style/AvoidKernelArray -- a section's Exclude may be a bare string or a list (both spellings are flagged)
55
55
  entry.is_a?(String) && !entry.match?(GLOB_CHARACTERS) && !@allowed_files.include?(entry)
56
56
  end
57
57
  end
@@ -123,6 +123,8 @@ module DevDoc
123
123
  def parse_json(body)
124
124
  JSON.parse(body)
125
125
  rescue JSON::ParserError
126
+ # rescue-reason: boundary-parse: crawled response bodies are not
127
+ # known to be JSON until parsed.
126
128
  # silent-rescue: non-JSON bodies are expected here — scan_body only
127
129
  # wants the parseable ones and skips the rest.
128
130
  nil
@@ -172,6 +174,8 @@ module DevDoc
172
174
  data = YAML.safe_load_file(file, permitted_classes: [Date, Time], aliases: true)
173
175
  collect_strings(data, set)
174
176
  rescue Psych::Exception
177
+ # rescue-reason: bulkhead: one unparsable fixture file must not
178
+ # abort the scan of the rest.
175
179
  # silent-rescue: an unparsable fixture is skipped; its strings
176
180
  # then count as noise candidates instead of exclusions, which
177
181
  # shows up in the report rather than hiding anything.
@@ -19,39 +19,76 @@ module RuboCop
19
19
  # lines. Use this when the checked node is a class/module declaration:
20
20
  # there the "trailing comment on a preceding code line" rule would let a
21
21
  # marker trailing the PREVIOUS class's `end` silence the next class.
22
+ #
23
+ # `leading_body_marker?` adds the third placement the rescue cops
24
+ # accept: the body's leading comment block directly below a `rescue`
25
+ # keyword.
22
26
  module AdjacentJustification
23
27
  private
24
28
 
25
29
  def adjacent_justification?(node, standalone_only: false, marker: justification_marker)
30
+ adjacent_marker_comments(node, standalone_only: standalone_only, marker: marker).any?
31
+ end
32
+
33
+ # Every adjacent comment carrying the marker, for hosts that read
34
+ # what follows it (a category word).
35
+ def adjacent_marker_comments(node, standalone_only: false, marker: justification_marker)
36
+ marker = marker.downcase if marker.is_a?(String)
37
+ comments_by_line = processed_source.comments.group_by { |comment| comment.location.line }
38
+
39
+ select_markers(comments_by_line[node.first_line], marker) +
40
+ marker_comments_above(node.first_line - 1, comments_by_line, marker, standalone_only)
41
+ end
42
+
43
+ # The marker also counts in a rescue body's own leading comment
44
+ # block — the contiguous comment-only lines directly below the
45
+ # `rescue` keyword, where adopters naturally state the reason. A
46
+ # comment after the first body statement is not adjacent to the
47
+ # rescue.
48
+ def leading_body_marker?(node, marker: justification_marker)
49
+ leading_body_marker_comments(node, marker: marker).any?
50
+ end
51
+
52
+ def leading_body_marker_comments(node, marker: justification_marker)
26
53
  marker = marker.downcase if marker.is_a?(String)
27
54
  comments_by_line = processed_source.comments.group_by { |comment| comment.location.line }
55
+ line = rescue_header_last_line(node) + 1
56
+ found = []
57
+ while (line_comments = comments_by_line[line]) && comment_only_line?(line)
58
+ found.concat(select_markers(line_comments, marker))
59
+ line += 1
60
+ end
28
61
 
29
- return true if contains_marker?(comments_by_line[node.first_line], marker)
62
+ found
63
+ end
30
64
 
31
- marker_in_block_above?(node.first_line - 1, comments_by_line, marker, standalone_only)
65
+ # An exception list may wrap; the body starts below its last line.
66
+ def rescue_header_last_line(node)
67
+ (node.exception_variable || node.exceptions.last || node.loc.keyword).last_line
32
68
  end
33
69
 
34
70
  # Walk the contiguous comment block upward from the line directly
35
71
  # above. A trailing comment on a preceding code line also counts —
36
72
  # still adjacent, still a deliberate statement — except in
37
73
  # standalone_only mode.
38
- def marker_in_block_above?(line, comments_by_line, marker, standalone_only)
74
+ def marker_comments_above(line, comments_by_line, marker, standalone_only)
75
+ found = []
39
76
  while (line_comments = comments_by_line[line])
40
77
  break if standalone_only && !comment_only_line?(line)
41
- return true if contains_marker?(line_comments, marker)
42
78
 
79
+ found.concat(select_markers(line_comments, marker))
43
80
  line -= 1
44
81
  end
45
82
 
46
- false
83
+ found
47
84
  end
48
85
 
49
86
  def comment_only_line?(line)
50
87
  processed_source.lines[line - 1].lstrip.start_with?('#')
51
88
  end
52
89
 
53
- def contains_marker?(comments, marker)
54
- Array(comments).any? do |comment|
90
+ def select_markers(comments, marker)
91
+ (comments || []).select do |comment|
55
92
  text = comment.text.downcase
56
93
  marker.is_a?(Regexp) ? marker.match?(text) : text.include?(marker)
57
94
  end
@@ -132,11 +132,11 @@ module RuboCop
132
132
  private
133
133
 
134
134
  def load_resource_method_names
135
- Array(cop_config.fetch('LoadResourceMethodNames', ['glib_load_resource'])).map(&:to_sym)
135
+ Array(cop_config.fetch('LoadResourceMethodNames', ['glib_load_resource'])).map(&:to_sym) # rubocop:disable DevDoc/Style/AvoidKernelArray -- cop config accepts one method name or a list
136
136
  end
137
137
 
138
138
  def current_user_assertion_method_names
139
- Array(cop_config.fetch('CurrentUserAssertionMethodNames', ['assert_current_user_present'])).map(&:to_sym)
139
+ Array(cop_config.fetch('CurrentUserAssertionMethodNames', ['assert_current_user_present'])).map(&:to_sym) # rubocop:disable DevDoc/Style/AvoidKernelArray -- cop config accepts one method name or a list
140
140
  end
141
141
 
142
142
  def load_resource_method?(method_name)
@@ -152,7 +152,7 @@ module RuboCop
152
152
 
153
153
  def login_only_predicates
154
154
  @login_only_predicates ||=
155
- Array(cop_config.fetch('LoginOnlyPredicates', %w[user_signed_in? everyone])).map(&:to_sym)
155
+ Array(cop_config.fetch('LoginOnlyPredicates', %w[user_signed_in? everyone])).map(&:to_sym) # rubocop:disable DevDoc/Style/AvoidKernelArray -- cop config accepts one predicate or a list
156
156
  end
157
157
 
158
158
  def justification_marker
@@ -158,7 +158,7 @@ module RuboCop
158
158
 
159
159
  def non_enumerable_keys
160
160
  @non_enumerable_keys ||=
161
- Array(cop_config.fetch('NonEnumerableKeys', %w[uuid token secret_key])).map(&:to_sym)
161
+ Array(cop_config.fetch('NonEnumerableKeys', %w[uuid token secret_key])).map(&:to_sym) # rubocop:disable DevDoc/Style/AvoidKernelArray -- cop config accepts one key or a list
162
162
  end
163
163
 
164
164
  def offense_message(node)
@@ -181,7 +181,7 @@ module RuboCop
181
181
  end
182
182
 
183
183
  def finder_methods
184
- @finder_methods ||= Array(cop_config.fetch('FinderMethods', %w[find find_by find_by!])).map(&:to_sym)
184
+ @finder_methods ||= Array(cop_config.fetch('FinderMethods', %w[find find_by find_by!])).map(&:to_sym) # rubocop:disable DevDoc/Style/AvoidKernelArray -- cop config accepts one method name or a list
185
185
  end
186
186
 
187
187
  def justification_marker
@@ -0,0 +1,74 @@
1
+ module RuboCop
2
+ module Cop
3
+ module DevDoc
4
+ module Bundler
5
+ # Flags Gemfile gems that duplicate a concern glib already provides.
6
+ #
7
+ # ## Rationale
8
+ # glib-web ships the concerns a glib app needs: versioning and audit
9
+ # history via `Glib::SnapshotV2` (active_snapshot), authorization via
10
+ # Pundit, uploads via ActiveStorage. A second library for one of those
11
+ # concerns splits the codebase between two ways of doing one thing and
12
+ # loses glib's integration — snapshot diffs in the admin timeline,
13
+ # Pundit scopes on index pages, `fields_file` uploads binding to
14
+ # attachments. The `ConflictingGems` map is keyed by gem name and each
15
+ # offense names the glib replacement, so the author knows what to use
16
+ # instead of what to delete.
17
+ #
18
+ # ## Exception
19
+ # A migration period where both libraries coexist (moving records onto
20
+ # the glib concern one model at a time) is legitimate: disable for the
21
+ # duration, bounded to the gem's own line, naming why:
22
+ #
23
+ # # rubocop:disable DevDoc/Bundler/ConflictingGem -- SnapshotV2 backfill in progress
24
+ # gem 'paper_trail'
25
+ # # rubocop:enable DevDoc/Bundler/ConflictingGem
26
+ #
27
+ # NOTE: Only direct Gemfile entries are checked, never transitive
28
+ # dependencies in `Gemfile.lock` or gemspec `add_dependency` lines.
29
+ # The list only knows conflicts someone has named — a gem that
30
+ # overlaps a glib concern without being in the map is still a
31
+ # conflict; the residual guidance lives in
32
+ # `best_practices/backend/en/01_basic.md` item 7.
33
+ #
34
+ # Configure via `ConflictingGems` in .rubocop.yml: a consumer adds an
35
+ # entry by giving it a message, and drops one by setting its value to
36
+ # `null`, `false` or empty, without disabling the cop.
37
+ #
38
+ # @example
39
+ # # bad
40
+ # gem 'paper_trail', '~> 17.0'
41
+ #
42
+ # # good
43
+ # # nothing to add — include the glib concern in the model instead
44
+ # class Order < ApplicationRecord
45
+ # include Glib::SnapshotV2
46
+ # end
47
+ class ConflictingGem < Base
48
+ MSG = '`%<gem>s` conflicts with the glib way: %<replacement>s'.freeze
49
+
50
+ RESTRICT_ON_SEND = %i[gem].freeze
51
+
52
+ def on_send(node)
53
+ return if node.receiver
54
+
55
+ gem_name = node.first_argument
56
+ return unless gem_name&.str_type?
57
+
58
+ replacement = conflicting_gems[gem_name.value]
59
+ return unless replacement.is_a?(String) && !replacement.empty?
60
+
61
+ add_offense(gem_name, message: format(MSG, gem: gem_name.value, replacement: replacement))
62
+ end
63
+
64
+ private
65
+
66
+ def conflicting_gems
67
+ config = cop_config['ConflictingGems']
68
+ config.is_a?(Hash) ? config : {}
69
+ end
70
+ end
71
+ end
72
+ end
73
+ end
74
+ end
@@ -0,0 +1,32 @@
1
+ module RuboCop
2
+ module Cop
3
+ module DevDoc
4
+ # Shared exception-class matching for the rescue cops. RuboCop has no
5
+ # type information, so a rescued class is matched by its constant as
6
+ # written: the source, leading `::` stripped, either equals a list
7
+ # entry or starts with an entry ending in `::` (a namespace entry such
8
+ # as `Errno::`). Anything that is not a plain constant — a splat, a
9
+ # method call, a local — never matches, and neither does a bare
10
+ # `rescue` (an empty exception list), so callers fail closed.
11
+ module ExceptionClassList
12
+ private
13
+
14
+ def all_exceptions_listed?(resbody, entries)
15
+ exceptions = resbody.exceptions
16
+ return false if exceptions.empty?
17
+
18
+ exceptions.all? { |exception| listed_exception?(exception, entries) }
19
+ end
20
+
21
+ def listed_exception?(node, entries)
22
+ return false unless node.const_type?
23
+
24
+ name = node.source.delete_prefix('::')
25
+ entries.any? do |entry|
26
+ entry.end_with?('::') ? name.start_with?(entry) : name == entry
27
+ end
28
+ end
29
+ end
30
+ end
31
+ end
32
+ end
@@ -81,7 +81,7 @@ module RuboCop
81
81
  end
82
82
 
83
83
  def allowed_prefixes
84
- Array(cop_config['AllowedPrefixes'])
84
+ Array(cop_config['AllowedPrefixes']) # rubocop:disable DevDoc/Style/AvoidKernelArray -- cop config accepts one prefix or a list
85
85
  end
86
86
 
87
87
  def prefixes_display(prefixes)
@@ -0,0 +1,26 @@
1
+ module RuboCop
2
+ module Cop
3
+ module DevDoc
4
+ module Migration
5
+ # Shared by the reference-option cops: the `ActiveRecord::Migration
6
+ # [4.2]` compatibility layer flips the reference default to
7
+ # `index: false` (see compatibility.rb's V4_2), so inside such a
8
+ # class `index: true` is load-bearing and `index: false` restates
9
+ # the default. Those migrations are skipped entirely.
10
+ module LegacyMigration
11
+ private
12
+
13
+ def legacy_migration?(node)
14
+ node.each_ancestor(:class).any? do |klass|
15
+ superclass = klass.children[1]
16
+ next false unless superclass&.send_type? && superclass.method?(:[])
17
+
18
+ version = superclass.first_argument
19
+ version&.numeric_type? && version.value < 5.0
20
+ end
21
+ end
22
+ end
23
+ end
24
+ end
25
+ end
26
+ end
@@ -1,4 +1,5 @@
1
1
  require_relative '../hash_pair_removal'
2
+ require_relative 'legacy_migration'
2
3
 
3
4
  module RuboCop
4
5
  module Cop
@@ -14,8 +15,9 @@ module RuboCop
14
15
  # (and imply, wrongly, that references without it are unindexed).
15
16
  #
16
17
  # The option is only meaningful when it *overrides* the default:
17
- # `index: false` to opt out, or a hash to customize
18
- # (`index: { unique: true }`). Those forms pass untouched.
18
+ # a hash to customize (`index: { unique: true }`) passes untouched;
19
+ # a literal `index: false` removes the index and is banned by the
20
+ # sibling cop `DevDoc/Migration/RequireReferenceIndex`.
19
21
  #
20
22
  # ❌ Redundant — this index exists anyway
21
23
  # t.belongs_to :user, foreign_key: true, null: false, index: true
@@ -55,6 +57,7 @@ module RuboCop
55
57
  class RedundantReferenceIndex < Base
56
58
  extend AutoCorrector
57
59
  include HashPairRemoval
60
+ include LegacyMigration
58
61
 
59
62
  MSG = '`index: true` is redundant — references are indexed by default since Rails 5.'.freeze
60
63
 
@@ -70,19 +73,6 @@ module RuboCop
70
73
 
71
74
  private
72
75
 
73
- # `ActiveRecord::Migration[4.2]` compatibility flips the reference
74
- # default to `index: false` (see compatibility.rb's V4_2), so inside
75
- # such a class `index: true` is load-bearing, not redundant.
76
- def legacy_migration?(node)
77
- node.each_ancestor(:class).any? do |klass|
78
- superclass = klass.children[1]
79
- next false unless superclass&.send_type? && superclass.method?(:[])
80
-
81
- version = superclass.first_argument
82
- version&.numeric_type? && version.value < 5.0
83
- end
84
- end
85
-
86
76
  def check_pair(node, options, pair)
87
77
  return unless index_key?(pair.key) && pair.value.true_type?
88
78