Skip to content

Commit

Permalink
Raise exception when a duplicate key is found when reading from a file.
Browse files Browse the repository at this point in the history
Fixes #34 (#36)
  • Loading branch information
jwoertink authored Nov 26, 2024
1 parent 8bd2202 commit 7213dfd
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 1 deletion.
6 changes: 6 additions & 0 deletions spec/parser_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,12 @@ describe LuckyEnv::Parser do
data["DB_NAME"].should eq "my_app_development"
data["LITERAL"].should eq "${NOT_EXISTS_ENV}"
end

it "raises on duplicate keys detected" do
expect_raises(LuckyEnv::DuplicateKeyDetectedError, /Duplicate key HOST found in \.\/spec\/support\/\.badenv/) do
parser.read_file("./spec/support/.badenv")
end
end
end
end

Expand Down
2 changes: 2 additions & 0 deletions spec/support/.badenv
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
HOST=localhost
HOST=duplicate_key
3 changes: 3 additions & 0 deletions src/lucky_env/errors.cr
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,7 @@ module LuckyEnv

class MissingFileError < Exception
end

class DuplicateKeyDetectedError < Exception
end
end
11 changes: 10 additions & 1 deletion src/lucky_env/parser.cr
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,16 @@ module LuckyEnv
next if comment?(string)
key, value = parse_value(string)

hash[key] = value
if hash.has_key?(key)
raise LuckyEnv::DuplicateKeyDetectedError.new <<-ERROR
Duplicate key #{key} found in #{file_path}.
To ignore a key, place a # at the front of the line like this:
# YOUR_KEY=ignored_value
ERROR
else
hash[key] = value
end
end

keys = hash.keys
Expand Down

0 comments on commit 7213dfd

Please sign in to comment.