Skip to content

Commit ac4c133

Browse files
Add backup support for config files
Move the backup functionality from `depends.py` Signed-off-by: Gabor Mezei <[email protected]>
1 parent 8c488b1 commit ac4c133

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

scripts/mbedtls_framework/config_common.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import argparse
99
import os
1010
import re
11+
import shutil
1112
import sys
1213

1314
from abc import ABCMeta
@@ -194,6 +195,18 @@ def filename(self, name=None):
194195

195196
return self._get_configfile(name).filename
196197

198+
def backup(self, suffix='.bak'):
199+
"""Back up the configuration file."""
200+
201+
for configfile in self.configfiles:
202+
configfile.backup(suffix)
203+
204+
def restore(self):
205+
"""Restore the configuration file."""
206+
207+
for configfile in self.configfiles:
208+
configfile.restore()
209+
197210

198211
class ConfigFile(metaclass=ABCMeta):
199212
"""Representation of a configuration file."""
@@ -214,6 +227,8 @@ def __init__(self, default_path, name, filename=None):
214227
self.current_section = None
215228
self.inclusion_guard = None
216229
self.modified = False
230+
self._backupname = None
231+
self._own_backup = False
217232

218233
_define_line_regexp = (r'(?P<indentation>\s*)' +
219234
r'(?P<commented_out>(//\s*)?)' +
@@ -324,6 +339,37 @@ def write(self, settings, filename=None):
324339
with open(filename, 'w', encoding='utf-8') as output:
325340
self.write_to_stream(settings, output)
326341

342+
def backup(self, suffix='.bak'):
343+
"""Back up the configuration file.
344+
345+
If the backup file already exists, it is presumed to be the desired backup,
346+
so don't make another backup.
347+
"""
348+
if self._backupname:
349+
return
350+
351+
self._backupname = self.filename + suffix
352+
if os.path.exists(self._backupname):
353+
self._own_backup = False
354+
else:
355+
self._own_backup = True
356+
shutil.copy(self.filename, self._backupname)
357+
358+
def restore(self):
359+
"""Restore the configuration file.
360+
361+
Only delete the backup file if it was created earlier.
362+
"""
363+
if not self._backupname:
364+
return
365+
366+
if self._own_backup:
367+
shutil.move(self._backupname, self.filename)
368+
else:
369+
shutil.copy(self._backupname, self.filename)
370+
371+
self._backupname = None
372+
327373

328374
class ConfigTool(metaclass=ABCMeta):
329375
"""Command line config manipulation tool.

0 commit comments

Comments
 (0)