From 4b7f3ba6ee5ba425bef6987080b4bb3327019d9e Mon Sep 17 00:00:00 2001 From: Sijawusz Pur Rahnama Date: Sat, 30 Jan 2021 18:22:10 +0100 Subject: [PATCH] Add MaxLineLength option to Style/VerboseBlock rule --- spec/ameba/rule/style/verbose_block_spec.cr | 15 +++++++++++++++ src/ameba/rule/style/verbose_block.cr | 13 +++++++++++++ 2 files changed, 28 insertions(+) diff --git a/spec/ameba/rule/style/verbose_block_spec.cr b/spec/ameba/rule/style/verbose_block_spec.cr index bca8cf03..60e5f676 100644 --- a/spec/ameba/rule/style/verbose_block_spec.cr +++ b/spec/ameba/rule/style/verbose_block_spec.cr @@ -90,6 +90,21 @@ module Ameba::Rule::Style .catch(source).should_not be_valid end + it "#max_line_length" do + source = Source.new %( + (1..3).tap &.tap &.tap &.tap &.tap &.tap &.tap do |i| + i.to_s.reverse.strip.blank? + end + ) + rule = VerboseBlock.new + rule + .tap(&.max_line_length = 60) + .catch(source).should be_valid + rule + .tap(&.max_line_length = nil) + .catch(source).should_not be_valid + end + it "#max_length" do source = Source.new %( (1..3).tap { |i| i.to_s.split.reverse.join.strip.blank? } diff --git a/src/ameba/rule/style/verbose_block.cr b/src/ameba/rule/style/verbose_block.cr index f36728f2..5a09f372 100644 --- a/src/ameba/rule/style/verbose_block.cr +++ b/src/ameba/rule/style/verbose_block.cr @@ -23,6 +23,7 @@ module Ameba::Rule::Style # ExcludeCallsWithBlocks: false # ExcludeOperators: false # ExcludeSetters: false + # MaxLineLength: ~ # MaxLength: 50 # use ~ to disable # ``` class VerboseBlock < Base @@ -34,6 +35,7 @@ module Ameba::Rule::Style exclude_operators false exclude_setters false + max_line_length : Int32? = nil # 100 max_length : Int32? = 50 end @@ -68,6 +70,16 @@ module Ameba::Rule::Style true end + protected def valid_line_length?(node, code) + if max_line_length = self.max_line_length + if location = node.name_location + final_line_length = location.column_number + code.size + return final_line_length <= max_line_length + end + end + true + end + protected def node_to_s(node : Crystal::Call) case name = node.name when "[]" @@ -141,6 +153,7 @@ module Ameba::Rule::Style call_code = call_code(node, body) + return unless valid_line_length?(node, call_code) return unless valid_length?(call_code) issue_for node.name_location, node.end_location,