From 9e2ab9c00211cf0eb30b626a5b8b33f55dea3922 Mon Sep 17 00:00:00 2001 From: Vitalii Elenhaupt Date: Thu, 12 Apr 2018 19:18:33 +0300 Subject: [PATCH] Show hash duplicated keys in error message closes #45 --- spec/ameba/rule/hash_duplicated_key_spec.cr | 11 ++++++++++- src/ameba/rule/hash_duplicated_key.cr | 10 ++++++---- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/spec/ameba/rule/hash_duplicated_key_spec.cr b/spec/ameba/rule/hash_duplicated_key_spec.cr index 188cec6e..65a50c2b 100644 --- a/spec/ameba/rule/hash_duplicated_key_spec.cr +++ b/spec/ameba/rule/hash_duplicated_key_spec.cr @@ -35,7 +35,16 @@ module Ameba::Rule error = s.errors.first error.rule.should_not be_nil error.location.to_s.should eq "source.cr:2:13" - error.message.should eq "Duplicated keys in hash literal." + error.message.should eq %(Duplicated keys in hash literal: "a") + end + + it "reports multiple duplicated keys" do + s = Source.new %q( + h = {"key1" => 1, "key1" => 2, "key2" => 3, "key2" => 4} + ) + subject.catch(s).should_not be_valid + error = s.errors.first + error.message.should eq %(Duplicated keys in hash literal: "key1","key2") end end end diff --git a/src/ameba/rule/hash_duplicated_key.cr b/src/ameba/rule/hash_duplicated_key.cr index 12a9939b..f8d9fcfa 100644 --- a/src/ameba/rule/hash_duplicated_key.cr +++ b/src/ameba/rule/hash_duplicated_key.cr @@ -30,15 +30,17 @@ module Ameba::Rule end def test(source, node : Crystal::HashLiteral) - return unless duplicated_keys?(node.entries) + return unless (keys = duplicated_keys(node.entries)).any? - source.error self, node.location, "Duplicated keys in hash literal." + source.error self, node.location, + "Duplicated keys in hash literal: #{keys.join(",")}" end - private def duplicated_keys?(entries) + private def duplicated_keys(entries) entries.map(&.key) .group_by(&.itself) - .any? { |_, v| v.size > 1 } + .select { |_, v| v.size > 1 } + .map { |k, _| k } end end end