Skip to content

consider adding a merge mode deep_merge_patch #147

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions lib/travis/yml/parts/part.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ class Part
deep_merge
deep_merge_append
deep_merge_prepend
deep_merge_patch
replace
)

Expand Down
26 changes: 26 additions & 0 deletions lib/travis/yml/support/merge.rb
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,21 @@ def deep_merge_prepend(lft, rgt)
end
end

def deep_merge_patch(lft, rgt)
keys(lft, rgt).inject(lft) do |hash, key|
hash[key] = if hashes?(lft[key], rgt[key])
send(mode(lft[key]) || :deep_merge_patch, lft[key], rgt[key])
elsif arrays?(lft[key], rgt[key])
send(mode(lft[key]) || :patch, lft[key], rgt[key])
elsif lft.key?(key)
lft[key]
else
rgt[key]
end
hash
end
end

def prepend(lft, rgt)
lft.replace(rgt + lft)
end
Expand All @@ -74,6 +89,17 @@ def append(lft, rgt)
lft.replace(lft + rgt)
end

def patch(lft, rgt)
lft.each.with_index do |_, ix|
rgt[ix] = if hashes?(rgt[ix], lft[ix])
deep_merge_patch(lft[ix], rgt[ix])
else
lft[ix] || rgt[ix]
end
end
rgt
end

def mode(obj)
obj.merge_mode if obj.respond_to?(:merge_mode)
end
Expand Down
32 changes: 32 additions & 0 deletions spec/travis/yml/support/merge_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,38 @@
it { expect(subject.keys.first.line).to eq 2 }
end

describe 'deep_merge_append' do
let(:mode) { :deep_merge_append }
it { should eq 'foo' => { 'one' => ['one', 'two'], 'two' => 'two' }, 'bar' => 'bar' }
it { expect(subject.keys.first).to be_a Key }
it { expect(subject.keys.first.line).to eq 2 }
end

describe 'deep_merge_patch' do
let(:mode) { :deep_merge_patch }

let(:lft) do
parse %(
foo:
bar:
- one: two
-
- three: three
)
end

let(:rgt) do
parse %(
foo:
bar:
- one: one
- two: two
)
end

it { should eq 'foo' => { 'bar' => [{ 'one' => 'two' }, { 'two' => 'two' }, { 'three' => 'three'}] } }
end

describe 'merge tags (1)' do
let(:lft) do
parse %(
Expand Down