1
0
mirror of https://github.com/SAP/jenkins-library.git synced 2025-03-03 15:02:35 +02:00

extract map merging to MapUtils (#156)

* Update MapUtils.groovy

* Update ConfigurationMerger.groovy

* tests

* forward skipNull

* Fix indent in tests

* More tests.

* MapUtils simplified wrt deep merge and pruneNulls

* Add test for isMap with null value
This commit is contained in:
Christopher Fenner 2018-06-20 10:15:36 +02:00 committed by Marcus Holl
parent b98803fbba
commit 257308298d
3 changed files with 66 additions and 12 deletions

View File

@ -7,19 +7,9 @@ class ConfigurationMerger {
@NonCPS
static Map merge(Map configs, Set configKeys, Map defaults) {
Map filteredConfig = configKeys?configs.subMap(configKeys):configs
Map merged = [:]
defaults = defaults ?: [:]
merged.putAll(defaults)
for(String key : filteredConfig.keySet())
if(MapUtils.isMap(filteredConfig[key]))
merged[key] = merge(filteredConfig[key], null, defaults[key])
else if(filteredConfig[key] != null)
merged[key] = filteredConfig[key]
// else: keep defaults value and omit null values from config
return merged
return MapUtils.merge(MapUtils.pruneNulls(defaults),
MapUtils.pruneNulls(filteredConfig))
}
@NonCPS

View File

@ -7,4 +7,35 @@ class MapUtils implements Serializable {
static boolean isMap(object){
return object in Map
}
@NonCPS
static Map pruneNulls(Map m) {
Map result = [:]
m = m ?: [:]
for(def e : m.entrySet())
if(isMap(e.value))
result[e.key] = pruneNulls(e.value)
else if(e.value != null)
result[e.key] = e.value
return result
}
@NonCPS
static Map merge(Map base, Map overlay) {
Map result = [:]
base = base ?: [:]
result.putAll(base)
for(def e : overlay.entrySet())
result[e.key] = isMap(e.value) ? merge(base[e.key], e.value) : e.value
return result
}
}

View File

@ -9,5 +9,38 @@ class MapUtilsTest {
void testIsMap(){
Assert.assertTrue('Map is not recognized as Map', MapUtils.isMap([:]))
Assert.assertTrue('String is recognized as Map', !MapUtils.isMap('I am not a Map'))
Assert.assertFalse('Null value is recognized as Map', MapUtils.isMap(null))
}
@Test
void testMergeMapStraigtForward(){
Map a = [a: '1',
c: [d: '1',
e: '2']],
b = [b: '2',
c: [d: 'x']];
Map merged = MapUtils.merge(a, b)
assert merged == [a: '1',
b: '2',
c: [d: 'x', e: '2']]
}
@Test
void testPruneNulls() {
Map m = [a: '1',
b: 2,
c: [ d: 'abc',
e: '',
n2: null],
n1: null]
assert MapUtils.pruneNulls(m) == [ a: '1',
b: 2,
c: [ d: 'abc',
e: '']]
}
}