From dcf2f1c08503f75828e1a98b55dfdd85906174ec Mon Sep 17 00:00:00 2001 From: Kaan Ozkan Date: Wed, 6 Mar 2024 12:24:23 -0500 Subject: [PATCH] Handle spaces in type definitions --- lib/rubocop/cop/sorbet/forbid_t_struct.rb | 3 +- .../cop/sorbet/forbid_t_struct_spec.rb | 57 +++++++++++++++++++ 2 files changed, 59 insertions(+), 1 deletion(-) diff --git a/lib/rubocop/cop/sorbet/forbid_t_struct.rb b/lib/rubocop/cop/sorbet/forbid_t_struct.rb index 72ba824..9b74281 100644 --- a/lib/rubocop/cop/sorbet/forbid_t_struct.rb +++ b/lib/rubocop/cop/sorbet/forbid_t_struct.rb @@ -153,7 +153,8 @@ def nilable? end def type - @type.gsub(/[[:space:]]+/, "").strip + copy = @type.gsub(/[[:space:]]+/, "").strip # Remove newlines and spaces + copy.gsub(",", ", ") # Add a space after each comma end end diff --git a/spec/rubocop/cop/sorbet/forbid_t_struct_spec.rb b/spec/rubocop/cop/sorbet/forbid_t_struct_spec.rb index ddc4a76..289f414 100644 --- a/spec/rubocop/cop/sorbet/forbid_t_struct_spec.rb +++ b/spec/rubocop/cop/sorbet/forbid_t_struct_spec.rb @@ -409,6 +409,63 @@ def initialize(baz:, foo: nil, bar: nil) expect(autocorrect_source(source)).to(eq(corrected)) end + it "handles spaces in types" do + source = <<~RUBY + class Foo < T::Struct + const :foo, T.any(Integer, String) + const :bar, T.nilable( + T.any(Integer, String) + ) + const :baz, T::Hash[Integer, String] + const :qux, T::Hash[Symbol, T.any(Integer, String)] + const :quux, T.any( + T::Hash[Integer, String], + String + ) + end + RUBY + + corrected = <<~RUBY + class Foo + extend T::Sig + + sig { returns(T.any(Integer, String)) } + attr_reader :foo + + sig { returns(T.nilable(T.any(Integer, String))) } + attr_reader :bar + + sig { returns(T::Hash[Integer, String]) } + attr_reader :baz + + sig { returns(T::Hash[Symbol, T.any(Integer, String)]) } + attr_reader :qux + + sig { returns(T.any(T::Hash[Integer, String], String)) } + attr_reader :quux + + sig do + params( + foo: T.any(Integer, String), + baz: T::Hash[Integer, String], + qux: T::Hash[Symbol, T.any(Integer, String)], + quux: T.any(T::Hash[Integer, String], String), + bar: T.nilable(T.any(Integer, String)) + ).void + end + def initialize(foo:, baz:, qux:, quux:, bar: nil) + @foo = foo + @bar = bar + @baz = baz + @qux = qux + @quux = quux + end + end + RUBY + + expect(autocorrect_source(source)).to(eq(corrected)) + end + it "strips new lines from type definitions" do source = <<~RUBY class Foo < T::Struct