officer_neetzsche 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 100c19f093b3f8972a0c73262ea4d1020057aea94a4835ac2a3e573d6b4d95c6
4
- data.tar.gz: 7d267e9d2cd3c091223b63c65243aa9f369d3cc8356de4346772188edcfdd681
3
+ metadata.gz: 7a43403b5afe1dda6db1ada7ebcbed1edfcedf20b74310ae26418ad2476caaa4
4
+ data.tar.gz: 2852001bdaba6f54726cba1ff1381a001a78827c201ec3a0fb91da9b181da443
5
5
  SHA512:
6
- metadata.gz: 8cf5f9105e71d0044dbbe8267db688767ea642f73ef6a00bc4272930e2bd8cecd3e42a6529b195e5b9ba905917345021447a701164372616e8c2fa214ae78b6c
7
- data.tar.gz: b4fafbac860b255990358dfc15e95a4463358b3106a72fdb54627908f5484516722c0a616299e862c28241fef26e4a438d2cd1d3026d82c3d0e6b81bdb7c285d
6
+ metadata.gz: b6306713c14f1fc76bbb93341985a1de4e98a6ef49d5a168bb14ab9373cfd381ca0c0d0efab2ce866fc8f36df15090fdb95534561e9e9bbacf4fefe337b832b3
7
+ data.tar.gz: cedd62f5afe1fc618b2da479f3b93fc39f4d585008fd41d1bc5dda9a73601c1df160d159407b7cd85ce8fccaf6f4cbf56329e1f368b0e2177a1645d213436efb
data/CHANGELOG.md CHANGED
@@ -1,6 +1,16 @@
1
1
  # Changelog
2
2
 
3
- ## 0.2.0 (unreleased)
3
+ ## 0.3.0 (unreleased)
4
+
5
+ ### Added
6
+
7
+ - `NEETzsche/StatementModifier`: rewrites an `if`, `unless`, `while`, `until`, or `rescue` whose body is one statement on one line as a statement modifier, whatever the resulting line length. Method-level and block-level `rescue` clauses count. Bodies that are themselves conditionals or rescues, comments inside the block, heredocs, and conditions or bodies whose meaning would change when the body is parsed first are left alone. Autocorrects, adding parentheses where the value is used.
8
+
9
+ ### Changed
10
+
11
+ - **Breaking:** the plugin now disables `Style/IfUnlessModifier` and `Style/WhileUntilModifier`, which `NEETzsche/StatementModifier` subsumes, and `Style/RescueModifier`, which forbids what it demands. Re-enable them in your own `.rubocop.yml` if you want them back; `Style/IfUnlessModifier` will then fight over modifier lines that exceed `Layout/LineLength`.
12
+
13
+ ## 0.2.0 (2026-09-09)
4
14
 
5
15
  ### Added
6
16
 
data/README.md CHANGED
@@ -10,6 +10,7 @@ RuboCop cops that enforce NEETzsche-isms. Every cop ships enabled: register the
10
10
  | --- | --- | --- |
11
11
  | `NEETzsche/GeneratedMigrationTimestamp` | Migration timestamps come from `bin/rails generate migration`, not a keyboard. | No |
12
12
  | `NEETzsche/NoComments` | No comments. The code explains itself. | Yes |
13
+ | `NEETzsche/StatementModifier` | An `if`, `unless`, `while`, `until`, or `rescue` around one statement is a modifier. | Yes |
13
14
 
14
15
  ## Requirements
15
16
 
@@ -132,6 +133,62 @@ Comments that change how Ruby or RuboCop behaves are allowed:
132
133
 
133
134
  `Style/Documentation` demands the class and module comments this cop forbids, so the plugin disables it. Re-enable it in your own `.rubocop.yml` if you want the two to fight.
134
135
 
136
+ ## NEETzsche/StatementModifier
137
+
138
+ Flags an `if`, `unless`, `while`, `until`, or `rescue` whose body is one statement on one line, and rewrites it as a statement modifier. How long the modifier line ends up does not matter.
139
+
140
+ ```ruby
141
+ # bad
142
+ if condition?
143
+ do_thing
144
+ end
145
+
146
+ until queue.empty?
147
+ queue.pop.call
148
+ end
149
+
150
+ begin
151
+ fetch
152
+ rescue
153
+ fallback
154
+ end
155
+
156
+ def call
157
+ fetch
158
+ rescue StandardError
159
+ fallback
160
+ end
161
+
162
+ # good
163
+ do_thing if condition?
164
+ queue.pop.call until queue.empty?
165
+ fetch rescue fallback
166
+
167
+ def call
168
+ fetch rescue fallback
169
+ end
170
+
171
+ # good, because the body is more than one statement
172
+ if condition?
173
+ do_this
174
+ do_that
175
+ end
176
+ ```
177
+
178
+ The offense sits on the keyword. A `rescue` counts when it is the only clause, rescues `StandardError` (bare, or named, since that is what the modifier rescues), binds no variable, and has no `else`; the `begin`/`end` around it goes away, while a `def`, a block, or an `ensure` around it stays. Parentheses are added where the value is used, so `value = if condition? then compute end` becomes `value = (compute if condition?)` and `call(begin; fetch; rescue; fallback; end)` becomes `call((fetch rescue fallback))`. An assigned `rescue` needs none: `value = fetch rescue fallback` already binds that way.
179
+
180
+ Left alone, because the block form is the only correct one:
181
+
182
+ - A body of more than one statement, a statement that spans lines, or a condition that spans lines.
183
+ - `else`, `elsif`, ternaries, and `begin ... end while` loops.
184
+ - A body that is itself an `if`, `unless`, `while`, `until`, `case`, or `rescue`, in either form. No chained modifiers.
185
+ - A `rescue` that names another class, lists several, binds a variable, has several clauses, an `else`, or an empty body or handler.
186
+ - A comment on any line of the block other than the first. A comment on the keyword line moves to the end of the modifier line.
187
+ - A heredoc anywhere inside.
188
+ - Anything whose meaning changes when the body is parsed before the condition, which is what the modifier form does: a condition that assigns a local variable, matches a pattern, or captures a named group; a body that assigns a name the condition calls as a method, as in `if name.nil?` followed by `name = default`; and an endless method definition, which would swallow the modifier.
189
+
190
+ The plugin disables `Style/IfUnlessModifier` and `Style/WhileUntilModifier`, which this cop subsumes, and `Style/RescueModifier`, which forbids what this cop demands. Re-enable them in your own `.rubocop.yml` if you want them back; `Style/IfUnlessModifier` will then fight over any modifier line longer than `Layout/LineLength` allows. `Layout/LineLength` itself is not consulted. If a modifier line is too long for it, shorten the statement or the condition, or exclude the file. Under `rubocop --autocorrect`, `Layout/LineLength` may instead wrap the arguments of a call on that line, after which `Style/MultilineIfModifier` restores the block form around the now multi-line body, and this cop leaves it there. `Style/GuardClause` and `Style/SoleNestedConditional` may flag the same block with a different fix; whichever corrects first wins, and the result satisfies both.
191
+
135
192
  ## Configuration
136
193
 
137
194
  Disable one cop:
data/config/default.yml CHANGED
@@ -14,5 +14,19 @@ NEETzsche/NoComments:
14
14
  Enabled: true
15
15
  VersionAdded: "0.1.0"
16
16
 
17
+ NEETzsche/StatementModifier:
18
+ Description: "Writes an `if`, `unless`, `while`, `until`, or `rescue` whose body is one statement as a modifier, whatever the line length."
19
+ Enabled: true
20
+ VersionAdded: "0.3.0"
21
+
17
22
  Style/Documentation:
18
23
  Enabled: false
24
+
25
+ Style/IfUnlessModifier:
26
+ Enabled: false
27
+
28
+ Style/RescueModifier:
29
+ Enabled: false
30
+
31
+ Style/WhileUntilModifier:
32
+ Enabled: false
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module OfficerNEETzsche
4
- VERSION = "0.2.0"
4
+ VERSION = "0.3.0"
5
5
  end
@@ -0,0 +1,196 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RuboCop
4
+ module Cop
5
+ module NEETzsche
6
+ class StatementModifier < Base
7
+ include RangeHelp
8
+ extend AutoCorrector
9
+
10
+ MSG = "Write a one-statement `%<keyword>s` as a modifier."
11
+
12
+ CHAIN_TYPES = %i[if while until while_post until_post for case case_match rescue kwbegin].freeze
13
+ CALLS = %i[send csend super yield].freeze
14
+
15
+ def self.autocorrect_incompatible_with
16
+ [Style::Next, Style::SoleNestedConditional]
17
+ end
18
+
19
+ def on_if(node)
20
+ return if node.modifier_form? || node.ternary? || node.elsif? || node.else?
21
+
22
+ check_conditional(node)
23
+ end
24
+
25
+ def on_while(node)
26
+ return if node.modifier_form?
27
+
28
+ check_conditional(node)
29
+ end
30
+ alias on_until on_while
31
+
32
+ def on_rescue(node)
33
+ resbody = node.resbody_branches.first
34
+ return unless bare_rescue?(node, resbody)
35
+
36
+ target = node.parent&.kwbegin_type? ? node.parent : node
37
+ return unless one_liner?(target, [node.body, resbody.body])
38
+
39
+ add_offense(resbody.loc.keyword, message: format(MSG, keyword: "rescue")) do |corrector|
40
+ rewrite(corrector, target, rescue_statement(node, resbody), Precedence.parenthesize_rescue?(target))
41
+ end
42
+ end
43
+
44
+ private
45
+
46
+ def check_conditional(node)
47
+ return unless eligible_conditional?(node)
48
+
49
+ add_offense(node.loc.keyword, message: format(MSG, keyword: node.keyword)) do |corrector|
50
+ rewrite(corrector, node, conditional_statement(node), Precedence.parenthesize_conditional?(node))
51
+ end
52
+ end
53
+
54
+ def eligible_conditional?(node)
55
+ node.condition.single_line? && one_liner?(node, [node.body]) &&
56
+ !Precedence.endless_def?(node.body) && !ParseOrder.hazard?(node)
57
+ end
58
+
59
+ def conditional_statement(node)
60
+ "#{statement_source(node.body)} #{node.keyword} #{node.condition.source}"
61
+ end
62
+
63
+ def rescue_statement(node, resbody)
64
+ "#{statement_source(node.body)} rescue #{statement_source(resbody.body)}"
65
+ end
66
+
67
+ def rewrite(corrector, node, statement, parenthesize)
68
+ statement = "(#{statement})" if parenthesize
69
+ corrector.replace(node, [statement, first_line_comment(node)&.source].compact.join(" "))
70
+ end
71
+
72
+ def bare_rescue?(node, resbody)
73
+ !rescue_modifier?(resbody) && node.resbody_branches.one? && !node.else? &&
74
+ resbody.exception_variable.nil? && standard_error_only?(resbody.exceptions)
75
+ end
76
+
77
+ def rescue_modifier?(resbody)
78
+ processed_source.tokens.any? { |token| token.rescue_modifier? && token.pos == resbody.loc.keyword }
79
+ end
80
+
81
+ def standard_error_only?(exceptions)
82
+ return true if exceptions.empty?
83
+ return false unless exceptions.one? && exceptions.first.const_type?
84
+
85
+ namespace, name = *exceptions.first
86
+ name == :StandardError && (namespace.nil? || namespace.cbase_type?)
87
+ end
88
+
89
+ def one_liner?(node, statements)
90
+ statements.all? { |statement| single_statement?(statement) } &&
91
+ !modifier_body?(node) && !heredoc?(node) && comments_movable?(node)
92
+ end
93
+
94
+ def single_statement?(statement)
95
+ return false if statement.nil? || statement.begin_type? || CHAIN_TYPES.include?(statement.type)
96
+ return false if statement.source.end_with?(":") && !CALLS.include?(statement.type)
97
+
98
+ statement.single_line?
99
+ end
100
+
101
+ def modifier_body?(node)
102
+ parent = node.parent
103
+ return false unless parent && (parent.if_type? || parent.while_type? || parent.until_type?)
104
+
105
+ parent.modifier_form? && parent.body.equal?(node)
106
+ end
107
+
108
+ def heredoc?(node)
109
+ node.each_descendant(:str, :dstr, :xstr).any?(&:heredoc?)
110
+ end
111
+
112
+ def comments_movable?(node)
113
+ return false if processed_source.each_comment_in_lines((node.first_line + 1)..node.last_line).any?
114
+
115
+ first_line_comment(node).nil? || code_after(node).nil?
116
+ end
117
+
118
+ def first_line_comment(node)
119
+ processed_source.comment_at_line(node.first_line)
120
+ end
121
+
122
+ def code_after(node)
123
+ line_end = first_line_comment(node)&.source_range&.begin_pos if node.single_line?
124
+ line_end ||= processed_source.buffer.line_range(node.last_line).end_pos
125
+ code = range_between(node.source_range.end_pos, line_end).source.strip
126
+ code unless code.empty?
127
+ end
128
+
129
+ def statement_source(statement)
130
+ return statement.source unless statement.source.end_with?(":")
131
+
132
+ head = range_between(statement.source_range.begin_pos, statement.first_argument.source_range.begin_pos)
133
+ "#{head.source.rstrip}(#{statement.arguments.map(&:source).join(", ")})"
134
+ end
135
+
136
+ module ParseOrder
137
+ CAPTURING_CONDITIONS = %i[lvasgn match_with_lvasgn match_pattern match_pattern_p].freeze
138
+
139
+ module_function
140
+
141
+ def hazard?(node)
142
+ condition = node.condition
143
+ return true if condition.each_node(*CAPTURING_CONDITIONS).any?
144
+
145
+ assigned = node.body.each_node(:lvasgn).map { |assignment| assignment.children.first }
146
+ return false if assigned.empty?
147
+
148
+ condition.each_node(:send).any? { |call| bare_identifier?(call) && assigned.include?(call.method_name) }
149
+ end
150
+
151
+ def bare_identifier?(call)
152
+ call.receiver.nil? && call.arguments.empty? && !call.parenthesized? && call.block_node.nil?
153
+ end
154
+ end
155
+
156
+ module Precedence
157
+ STATEMENT_PARENTS = %i[begin kwbegin def defs block numblock itblock class module sclass
158
+ ensure rescue resbody preexe postexe].freeze
159
+ ASSIGNMENTS = %i[lvasgn ivasgn cvasgn gvasgn casgn masgn op_asgn or_asgn and_asgn indexasgn].freeze
160
+
161
+ module_function
162
+
163
+ def parenthesize_conditional?(node)
164
+ !statement_position?(node)
165
+ end
166
+
167
+ def parenthesize_rescue?(node)
168
+ !statement_position?(node) && !assignment_value?(node)
169
+ end
170
+
171
+ def endless_def?(body)
172
+ %i[def defs].include?(body.type) && body.endless?
173
+ end
174
+
175
+ def statement_position?(node)
176
+ parent = node.parent
177
+ return true if parent.nil? || STATEMENT_PARENTS.include?(parent.type)
178
+
179
+ case parent.type
180
+ when :if, :while, :until, :case, :case_match then !parent.children.first.equal?(node)
181
+ when :for, :when, :in_pattern then parent.body.equal?(node)
182
+ else false
183
+ end
184
+ end
185
+
186
+ def assignment_value?(node)
187
+ parent = node.parent
188
+ return false unless parent.children.last.equal?(node)
189
+
190
+ ASSIGNMENTS.include?(parent.type) || (parent.send_type? && parent.assignment_method?)
191
+ end
192
+ end
193
+ end
194
+ end
195
+ end
196
+ end
@@ -2,3 +2,4 @@
2
2
 
3
3
  require_relative "neetzsche/generated_migration_timestamp"
4
4
  require_relative "neetzsche/no_comments"
5
+ require_relative "neetzsche/statement_modifier"
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: officer_neetzsche
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.2.0
4
+ version: 0.3.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - TheStranjer
@@ -53,6 +53,7 @@ files:
53
53
  - lib/officer_neetzsche/version.rb
54
54
  - lib/rubocop/cop/neetzsche/generated_migration_timestamp.rb
55
55
  - lib/rubocop/cop/neetzsche/no_comments.rb
56
+ - lib/rubocop/cop/neetzsche/statement_modifier.rb
56
57
  - lib/rubocop/cop/neetzsche_cops.rb
57
58
  homepage: https://github.com/TheStranjer/OfficerNEETzsche
58
59
  licenses: []