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.
Files changed (36) hide show
  1. checksums.yaml +4 -4
  2. data/config/default.yml +184 -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/create_or_find_by.rb +66 -0
  21. data/lib/rubocop/cop/dev_doc/rails/find_or_create_by_justification.rb +106 -0
  22. data/lib/rubocop/cop/dev_doc/rails/no_error_message_comparison.rb +178 -0
  23. data/lib/rubocop/cop/dev_doc/rails/no_form_param_lookup_in_controller.rb +1 -1
  24. data/lib/rubocop/cop/dev_doc/rails/rescue_record_not_unique_index.rb +212 -0
  25. data/lib/rubocop/cop/dev_doc/rails/unique_index_backing.rb +205 -0
  26. data/lib/rubocop/cop/dev_doc/style/avoid_kernel_array.rb +103 -0
  27. data/lib/rubocop/cop/dev_doc/style/no_silent_rescue.rb +36 -26
  28. data/lib/rubocop/cop/dev_doc/style/no_unscoped_method_definitions.rb +1 -1
  29. data/lib/rubocop/cop/dev_doc/style/rescue_justification.rb +330 -0
  30. data/lib/rubocop/cop/dev_doc/test/justification_covers.rb +216 -0
  31. data/lib/rubocop/cop/dev_doc/test/justification_header.rb +86 -5
  32. data/lib/rubocop/cop/dev_doc/test/require_job_invocation_in_job_tests.rb +154 -0
  33. data/lib/rubocop/cop/dev_doc/test/require_unit_test_justification.rb +5 -24
  34. data/lib/rubocop/cop/dev_doc/test/test_file_placement.rb +30 -2
  35. data/lib/rubocop/dev_doc/version.rb +1 -1
  36. metadata +16 -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: 34e773b91c19e7fcf99043ec8241ccfda6fedddd52bc17e11b3693852a226710
4
+ data.tar.gz: cd2f7c295e98c4963c0914ecf1131a192d69a905315e533f3f4e9571245c01af
5
5
  SHA512:
6
- metadata.gz: 3b4be761462f9974fa8caa317e1df9d71ead56160dc4d9d0e7b98407af11a8835f09a888e4b8677448981c6e8e032129312d6e469f7134426714351e594cdc64
7
- data.tar.gz: 5aca39f093385aae489a8c1a18fcf43eff4995dd7a5d575d237e5a472a8477457789a9cb201ce5ba09abdc6c49fcbf80fbd761467ee2d46447f5ee943111292f
6
+ metadata.gz: f517e4d2f400bd915fd40eb9efde0e4cfd30c13f2e4fb289a2cf1bf489dc27a2888db2d0ab3482c3648f4e33397274fdae4262ba593bf31ed5c1720b073637b9
7
+ data.tar.gz: 62751bf6320874a8834de4bff344bf2fd2e905d71371c03aa7402812c7909528d25acaf3ccbb1f31490c0b8adf30b6a77376de399c83384efba2588639b21380
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
@@ -108,6 +132,29 @@ DevDoc/Rails/AvoidBypassingValidation:
108
132
  - "spec/**/*"
109
133
  - "test/**/*"
110
134
 
135
+ DevDoc/Rails/CreateOrFindBy:
136
+ Description: "`create_or_find_by` / `create_or_find_by!` are banned — their preconditions are the exception, not the rule. Use the two rules of 03_model.md item 14 instead."
137
+ Enabled: true
138
+ Include:
139
+ - "app/**/*.rb"
140
+ - "lib/**/*.rb"
141
+
142
+ DevDoc/Rails/FindOrCreateByJustification:
143
+ Description: "`find_or_create_by` is the rule-1 exception of 03_model.md item 14 and needs an adjacent `unique-write:` comment; strict mode flags literal attributes a unique index already covers (that site is rule 2)."
144
+ Enabled: true
145
+ Include:
146
+ - "app/**/*.rb"
147
+ - "lib/**/*.rb"
148
+ JustificationMarker: "unique-write:"
149
+ Strict: true
150
+
151
+ DevDoc/Rails/RescueRecordNotUniqueIndex:
152
+ Description: "A `rescue ActiveRecord::RecordNotUnique` must guard a write inside `transaction(requires_new: true)` that a unique index backs (literal attributes against the schema, or a `# unique_index: <name>` tag) — 03_model.md item 14, rule 2."
153
+ Enabled: true
154
+ Include:
155
+ - "app/**/*.rb"
156
+ - "lib/**/*.rb"
157
+
111
158
  DevDoc/Migration/DateColumnNaming:
112
159
  Description: "Date columns should end with `_on`; datetime columns should end with `_at`."
113
160
  Enabled: true
@@ -222,6 +269,20 @@ DevDoc/Rails/NoErrorsAddInController:
222
269
  Include:
223
270
  - "app/controllers/**/*.rb"
224
271
 
272
+ # The text of an error message is written in two places — the `errors.add`
273
+ # that produces it and the branch that matches it — and only both copies
274
+ # staying identical keeps the branch alive; rewording, translating, or a
275
+ # second error silently breaks it. Add the error with a symbol type and
276
+ # branch on the type (`errors.of_kind?` / `errors.added?`), not the text.
277
+ # Measured over 13 consuming apps (one clone per origin, plus one non-glib
278
+ # Rails app): one offense, a true positive.
279
+ DevDoc/Rails/NoErrorMessageComparison:
280
+ 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?`."
281
+ Enabled: true
282
+ Include:
283
+ - "app/**/*.rb"
284
+ - "app/**/*.jbuilder"
285
+
225
286
  DevDoc/Rails/EnumMustBeSymbolized:
226
287
  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
288
  Enabled: true
@@ -359,11 +420,13 @@ DevDoc/Migration/NoBulkChangeTable:
359
420
  - "db/migrate/*.rb"
360
421
  - "db/migrate/**/*.rb"
361
422
 
362
- # The reference-options trio. Each of a reference's three options gets the
423
+ # The reference-option cops. Each of a reference's options gets the
363
424
  # enforcement shape its house position calls for:
364
425
  # - foreign_key: has one right value (constrain) -> enforce the VALUE.
365
426
  # - null: both values are legitimate -> enforce EXPLICITNESS (either passes).
366
- # - index: the default is already correct -> enforce SILENCE (flag redundancy).
427
+ # - index: the default is already correct -> enforce SILENCE (flag
428
+ # redundancy), and opting out is banned — every FK column carries its
429
+ # own index (see RequireReferenceIndex below for why).
367
430
  # Net effect: everything written on a reference line is a decision, everything
368
431
  # omitted is doctrine.
369
432
  DevDoc/Migration/RequireReferenceForeignKey:
@@ -373,6 +436,17 @@ DevDoc/Migration/RequireReferenceForeignKey:
373
436
  - "db/migrate/*.rb"
374
437
  - "db/migrate/**/*.rb"
375
438
 
439
+ # No autocorrect: removing `index: false` changes the migration's resulting
440
+ # schema (the index comes back), which is the developer's decision to make.
441
+ # Migration[4.2] classes are skipped (the default there is `index: false`, so
442
+ # the written option restates it rather than opting out).
443
+ DevDoc/Migration/RequireReferenceIndex:
444
+ Description: "References must not opt out of their default index (`index: false` is banned) — every FK column carries its own index."
445
+ Enabled: true
446
+ Include:
447
+ - "db/migrate/*.rb"
448
+ - "db/migrate/**/*.rb"
449
+
376
450
  DevDoc/Migration/ExplicitNullOnReference:
377
451
  Description: "References must state `null:` explicitly — optional and mandatory are both legitimate."
378
452
  Enabled: true
@@ -458,6 +532,22 @@ DevDoc/Style/AvoidSymbolizingBoundaryInput:
458
532
  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
533
  Enabled: true
460
534
 
535
+ # Measured on one consuming app's app/ (2026-11-08: 21 hits in 1191 files —
536
+ # 17 drift/risky, 4 justified scalar-or-list inputs to keep via inline
537
+ # disables there) and on this repo's own lib (17 hits: 1 true positive
538
+ # converted to `|| []`, 16 genuine one-or-many shapes kept with inline
539
+ # disables — I18n scope args, mail recipients, persona tenant keys,
540
+ # cop-config values, an Exclude section). Tests are excluded because there `Array()` mostly
541
+ # walks rendered JSON output, where a silent coercion hides at worst a bad
542
+ # assertion, not data corruption (same Exclude shape as
543
+ # DevDoc/Rails/AvoidBypassingValidation).
544
+ DevDoc/Style/AvoidKernelArray:
545
+ Description: "Avoid `Array()` coercion; use `x || []` when nil is the only alternative. Do not enable stock Style/ArrayCoercion alongside."
546
+ Enabled: true
547
+ Exclude:
548
+ - "spec/**/*"
549
+ - "test/**/*"
550
+
461
551
  DevDoc/Style/LiteralOrInWhenClause:
462
552
  Description: "`||`/`&&` between literals in a `when` clause folds to one value — the other literal silently never matches; use comma-separated alternatives."
463
553
  Enabled: true
@@ -737,6 +827,22 @@ DevDoc/Test/RequireGlibIntegrationBase:
737
827
  - "test/mailers/**/*_test.rb"
738
828
  - "test/channels/**/*_test.rb"
739
829
 
830
+ # The entry-point check for the inbound-edge directory: a *Test class under
831
+ # test/jobs that never invokes the job (perform / perform_now / perform_later /
832
+ # perform_enqueued_jobs) is a service-flow test parked where the lints trust
833
+ # it — dispatch, guards and follow-up enqueues never run (observed 2026-10:
834
+ # ~18 integration-base cases in one consumer file drove a service .call and
835
+ # never the job). Same-file ancestor classes satisfy via their own bodies.
836
+ # The entry-point set lives in code, not here: config lists are droppable,
837
+ # code baselines are not. An enqueue-routing test whose trigger is not a
838
+ # job send (a request, a service call) takes an inline disable with a
839
+ # rationale.
840
+ DevDoc/Test/RequireJobInvocationInJobTests:
841
+ 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."
842
+ Enabled: true
843
+ Include:
844
+ - "test/jobs/**/*_test.rb"
845
+
740
846
  # Previews render on every GET in development — persistence inside one mutates
741
847
  # the dev DB as a side effect of viewing an email. Also guards the preview
742
848
  # harness as a relocation target: mailer-body variants staged for snapshots
@@ -851,6 +957,32 @@ DevDoc/Test/RequireUnitTestJustification:
851
957
  Include:
852
958
  - "test/**/*_test.rb"
853
959
 
960
+ DevDoc/Test/JustificationCovers:
961
+ Description: "A justification header must list the methods its claim covers (Covers: line), and every test in the file must call one of them."
962
+ Enabled: true
963
+ CoversPhrase: "covers:"
964
+ # The marker phrase gates this cop: files without it are
965
+ # RequireUnitTestJustification's to report — this cop never double-reports
966
+ # a missing header.
967
+ MarkerPhrase: "deliberate exception"
968
+ # Applicability is the shared justification_header_required? predicate
969
+ # (in the cops' TestFilePlacement module), which reads the base and
970
+ # directory keys below — mirror them from
971
+ # DevDoc/Test/RequireUnitTestJustification and keep the two entries in
972
+ # sync, or the cops police different file sets.
973
+ NonHttpBaseClasses:
974
+ - Glib::NonHttpIntegrationTest
975
+ UnitTestDirectories:
976
+ - models
977
+ - services
978
+ - helpers
979
+ NonHttpDirectories:
980
+ - jobs
981
+ - mailers
982
+ - channels
983
+ Include:
984
+ - "test/**/*_test.rb"
985
+
854
986
  Naming/PredicatePrefix:
855
987
  Enabled: false
856
988
 
@@ -1316,6 +1448,56 @@ DevDoc/Style/NoSilentRescue:
1316
1448
  - "alert"
1317
1449
  - "breadcrumb"
1318
1450
  - "handle"
1451
+ # A clause rescuing only these is an expected outcome (a lost race), not a
1452
+ # swallowed failure, and may stay silent. I/O failures are not here: they
1453
+ # are still failures and must be reported.
1454
+ ExpectedOutcomeClasses:
1455
+ - "ActiveRecord::RecordNotUnique"
1456
+ - "ActiveRecord::Deadlocked"
1457
+ - "ActiveRecord::LockWaitTimeout"
1458
+ - "ActiveRecord::StaleObjectError"
1459
+ - "ActiveRecord::SerializationFailure"
1460
+
1461
+ DevDoc/Style/RescueJustification:
1462
+ 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."
1463
+ Enabled: true
1464
+ Include:
1465
+ - "app/**/*.rb"
1466
+ - "lib/**/*.rb"
1467
+ JustificationMarker: "rescue-reason:"
1468
+ # Failures no validator of ours can prevent. A trailing `::` matches a namespace.
1469
+ ExpectedErrorClasses:
1470
+ # concurrency verdicts — validation is point-in-time, the constraint is the check
1471
+ - "ActiveRecord::RecordNotUnique"
1472
+ - "ActiveRecord::Deadlocked"
1473
+ - "ActiveRecord::LockWaitTimeout"
1474
+ - "ActiveRecord::StaleObjectError"
1475
+ - "ActiveRecord::SerializationFailure"
1476
+ # I/O to another system
1477
+ - "ActiveRecord::ConnectionNotEstablished"
1478
+ - "ActiveRecord::NoDatabaseError"
1479
+ - "ActiveRecord::ConnectionTimeoutError"
1480
+ - "Errno::"
1481
+ - "Net::"
1482
+ - "Timeout::Error"
1483
+ - "IOError"
1484
+ - "EOFError"
1485
+ - "SocketError"
1486
+ - "OpenSSL::SSL::SSLError"
1487
+ Categories:
1488
+ bulkhead:
1489
+ Meaning: "one failure unit of a batch or async sweep must not abort the rest; one per unit of work, reported"
1490
+ side-effect:
1491
+ Meaning: "a secondary effect that must not fail the primary action it rides on"
1492
+ degrade:
1493
+ Meaning: "a user-facing path that degrades to a fallback and reports (01a item 5)"
1494
+ boundary-parse:
1495
+ Meaning: "untrusted external input parsed here; the parse is the validation"
1496
+ surface:
1497
+ Meaning: "a non-bang wrapper turning a bang method's exception into the contract's failure channel (false + errors)"
1498
+ delivery:
1499
+ Meaning: "a controller rendering a domain error raised below it"
1500
+ Path: "app/controllers/"
1319
1501
 
1320
1502
  DevDoc/Style/UseGLog:
1321
1503
  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