Write the config to a tmp file before a final copy

(should prevent some conditions leading to config
corruption happenning when poezio cannot write anymore)
This commit is contained in:
Mathieu Pasquet 2013-12-04 01:14:28 +01:00
parent 4a7e18cd03
commit c0e010e2cd

View file

@ -14,12 +14,13 @@ DEFSECTION = "Poezio"
from gettext import gettext as _ from gettext import gettext as _
import sys import sys
import tempfile
import os
import logging import logging
log = logging.getLogger(__name__)
from configparser import RawConfigParser, NoOptionError, NoSectionError from configparser import RawConfigParser, NoOptionError, NoSectionError
from os import environ, makedirs, path from os import environ, makedirs, path, remove
from shutil import copy2 from shutil import copy2
from args import parse_args from args import parse_args
@ -178,12 +179,22 @@ class Config(RawConfigParser):
elif not written: elif not written:
result_lines.append('%s = %s' % (option, value)) result_lines.append('%s = %s' % (option, value))
try: try:
df = open(self.file_name, 'w', encoding='utf-8') prefix, file = path.split(self.file_name)
filename = path.join(prefix, '.%s.tmp' % file)
fd = os.fdopen(
os.open(
filename,
os.O_WRONLY | os.O_CREAT,
0o600),
'w')
for line in result_lines: for line in result_lines:
df.write('%s\n' % line) fd.write('%s\n' % line)
df.close() fd.close()
copy2(filename, self.file_name)
remove(filename)
except: except:
success = False success = False
log.error('Unable to save the config file.', exc_info=True)
else: else:
success = True success = True
return success return success
@ -333,3 +344,5 @@ else:
# it needs to be after logger configuration # it needs to be after logger configuration
from common import safeJID from common import safeJID
log = logging.getLogger(__name__)