Skip to content

Commit 64bbb30

Browse files
committed
add graceful error handling for YAML import
1 parent e9d688c commit 64bbb30

File tree

4 files changed

+30
-3
lines changed

4 files changed

+30
-3
lines changed

lib/bashly/refinements/compose_refinements.rb

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ def compose(keyword = 'import')
66
result = {}
77
each do |k, v|
88
if k.to_s == keyword
9-
sub = YAML.load_file(v).compose keyword
9+
sub = safe_load_yaml(v).compose keyword
1010
if sub.is_a? Array
1111
result = sub
1212
else
@@ -20,6 +20,15 @@ def compose(keyword = 'import')
2020
end
2121
result
2222
end
23+
24+
def safe_load_yaml(path)
25+
loaded = YAML.load_file path
26+
return loaded if loaded.is_a? Array or loaded.is_a? Hash
27+
raise Bashly::ConfigurationError, "Cannot find a valid YAML in '#{path}'"
28+
29+
rescue Errno::ENOENT
30+
raise Bashly::ConfigurationError, "Cannot find import file '#{path}'"
31+
end
2332
end
2433

2534
refine Array do
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
#<Bashly::ConfigurationError: Cannot find a valid YAML in 'examples/minimal/src/root_command.sh'>
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
#<Bashly::ConfigurationError: Cannot find import file 'no-such-file.yml'>

spec/bashly/refinements/compose_refinements_spec.rb

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
require 'spec_helper'
22

3-
describe ComposeRefinements, :focus do
3+
describe ComposeRefinements do
44
using ComposeRefinements
55

66
subject do
@@ -19,6 +19,22 @@
1919
describe '#compose' do
2020
it "calls #compose on all elements that respond to #compose" do
2121
expect(subject.compose.to_yaml).to match_approval "refinements/compose/array"
22-
end
22+
end
23+
24+
context "when the import path does not exist" do
25+
subject { { import: "no-such-file.yml" } }
26+
27+
it "raises ConfigurationError" do
28+
expect { subject.compose }.to raise_approval("refinements/compose/error-not-found")
29+
end
30+
end
31+
32+
context "when the import path does not contain a valid YAML front matter" do
33+
subject { { import: "examples/minimal/src/root_command.sh" } }
34+
35+
it "raises ConfigurationError" do
36+
expect { subject.compose }.to raise_approval("refinements/compose/error-invalid")
37+
end
38+
end
2339
end
2440
end

0 commit comments

Comments
 (0)