1 package org.apache.maven.toolchain.merge;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import java.util.ArrayList;
23 import java.util.LinkedHashMap;
24 import java.util.List;
25 import java.util.Map;
26
27 import org.apache.maven.api.xml.Dom;
28 import org.apache.maven.api.toolchain.PersistedToolchains;
29 import org.apache.maven.api.toolchain.ToolchainModel;
30
31
32
33
34
35
36 public class MavenToolchainMerger
37 {
38
39 public PersistedToolchains merge( PersistedToolchains dominant, PersistedToolchains recessive,
40 String recessiveSourceLevel )
41 {
42 if ( dominant == null || recessive == null )
43 {
44 return dominant;
45 }
46
47 recessive.setSourceLevel( recessiveSourceLevel );
48
49 return shallowMerge( dominant.getToolchains(), recessive.getToolchains(), recessiveSourceLevel );
50 }
51
52 private PersistedToolchains shallowMerge( List<ToolchainModel> dominant, List<ToolchainModel> recessive,
53 String recessiveSourceLevel )
54 {
55 Map<Object, ToolchainModel> merged = new LinkedHashMap<>();
56
57 for ( ToolchainModel dominantModel : dominant )
58 {
59 Object key = getToolchainModelKey( dominantModel );
60
61 merged.put( key, dominantModel );
62 }
63
64 for ( ToolchainModel recessiveModel : recessive )
65 {
66 Object key = getToolchainModelKey( recessiveModel );
67
68 ToolchainModel dominantModel = merged.get( key );
69 if ( dominantModel == null )
70 {
71 recessiveModel.setSourceLevel( recessiveSourceLevel );
72 merged.put( key, recessiveModel );
73 }
74 else
75 {
76 merged.put( key, mergeToolchainModelConfiguration( dominantModel, recessiveModel ) );
77 }
78 }
79 return PersistedToolchains.newBuilder()
80 .toolchains( new ArrayList<>( merged.values() ) )
81 .build();
82 }
83
84 protected ToolchainModel mergeToolchainModelConfiguration( ToolchainModel target,
85 ToolchainModel source )
86 {
87 Dom src = source.getConfiguration();
88 Dom tgt = target.getConfiguration();
89 Dom merged = Dom.merge( tgt, src );
90 return target.withConfiguration( merged );
91 }
92
93 protected Object getToolchainModelKey( ToolchainModel model )
94 {
95 return model;
96 }
97
98 }