88import argparse
99import os
1010import re
11+ import shutil
1112import sys
1213
1314from abc import ABCMeta
@@ -204,6 +205,18 @@ def filename(self, name=None):
204205
205206 return self ._get_configfile (name ).filename
206207
208+ def backup (self , suffix = '.bak' ):
209+ """Back up the configuration file."""
210+
211+ for configfile in self .configfiles :
212+ configfile .backup (suffix )
213+
214+ def restore (self ):
215+ """Restore the configuration file."""
216+
217+ for configfile in self .configfiles :
218+ configfile .restore ()
219+
207220
208221class ConfigFile (metaclass = ABCMeta ):
209222 """Representation of a configuration file."""
@@ -224,6 +237,8 @@ def __init__(self, default_path, name, filename=None):
224237 self .current_section = None
225238 self .inclusion_guard = None
226239 self .modified = False
240+ self ._backupname = None
241+ self ._own_backup = False
227242
228243 _define_line_regexp = (r'(?P<indentation>\s*)' +
229244 r'(?P<commented_out>(//\s*)?)' +
@@ -334,6 +349,37 @@ def write(self, settings, filename=None):
334349 with open (filename , 'w' , encoding = 'utf-8' ) as output :
335350 self .write_to_stream (settings , output )
336351
352+ def backup (self , suffix = '.bak' ):
353+ """Back up the configuration file.
354+
355+ If the backup file already exists, it is presumed to be the desired backup,
356+ so don't make another backup.
357+ """
358+ if self ._backupname :
359+ return
360+
361+ self ._backupname = self .filename + suffix
362+ if os .path .exists (self ._backupname ):
363+ self ._own_backup = False
364+ else :
365+ self ._own_backup = True
366+ shutil .copy (self .filename , self ._backupname )
367+
368+ def restore (self ):
369+ """Restore the configuration file.
370+
371+ Only delete the backup file if it was created earlier.
372+ """
373+ if not self ._backupname :
374+ return
375+
376+ if self ._own_backup :
377+ shutil .move (self ._backupname , self .filename )
378+ else :
379+ shutil .copy (self ._backupname , self .filename )
380+
381+ self ._backupname = None
382+
337383
338384class ConfigTool (metaclass = ABCMeta ):
339385 """Command line config manipulation tool.
0 commit comments