Skip to content

Commit 092e231

Browse files
committed
[fix] Deduplicate files
If a file is present in multiple places (templates, configuration) The last definition wins. eg: - the configuration overrides the template - the second template overrides the first
1 parent 5182887 commit 092e231

2 files changed

Lines changed: 45 additions & 0 deletions

File tree

netjsonconfig/backends/base/backend.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,15 @@ def _render_files(self):
107107
output += file_output
108108
return output
109109

110+
def _deduplicate_files(self):
111+
files = self.config.get('files', [])
112+
if not files:
113+
return
114+
files_dict = OrderedDict()
115+
for file in files:
116+
files_dict[file['path']] = file
117+
self.config['files'] = list(files_dict.values())
118+
110119
def validate(self):
111120
try:
112121
Draft4Validator(self.schema, format_checker=draft4_format_checker).validate(self.config)
@@ -125,6 +134,7 @@ def render(self, files=True):
125134
# convert NetJSON config to intermediate data structure
126135
if self.intermediate_data is None:
127136
self.to_intermediate()
137+
self._deduplicate_files()
128138
# support multiple renderers
129139
renderers = getattr(self, 'renderers', None) or [self.renderer]
130140
# convert intermediate data structure to native configuration

tests/openwrt/test_backend.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -408,3 +408,38 @@ def test_value_error(self):
408408
OpenWrt(templates=[])
409409
with self.assertRaises(ValueError):
410410
OpenWrt(context=[])
411+
412+
def test_override_file(self):
413+
o = OpenWrt({
414+
"files": [
415+
{
416+
"path": "/etc/crontabs/root",
417+
"mode": "0644",
418+
"contents": "*/5 * * * * /command1\n*/5 * * * * /command2"
419+
}
420+
]
421+
}, templates=[
422+
{
423+
"files": [
424+
{
425+
"path": "/etc/crontabs/root",
426+
"mode": "0644",
427+
"contents": "*/5 * * * * /command1"
428+
}
429+
]
430+
}
431+
])
432+
expected = """
433+
# ---------- files ---------- #
434+
435+
# path: /etc/crontabs/root
436+
# mode: 0644
437+
438+
*/5 * * * * /command1
439+
*/5 * * * * /command2
440+
441+
"""
442+
self.assertEqual(o.render(), expected)
443+
# ensure the additional files are there present in the tar.gz archive
444+
tar = tarfile.open(fileobj=o.generate(), mode='r')
445+
self.assertEqual(len(tar.getmembers()), 1)

0 commit comments

Comments
 (0)