Use temporary files to prevent IO race conditions.

Refer to #260.
pull/185/head
William Ting 10 years ago
parent 4bd62e2293
commit 4826a0ef6b

@ -88,7 +88,6 @@ def set_defaults():
config['data_path'] = os.path.join(data_home, 'autojump.txt') config['data_path'] = os.path.join(data_home, 'autojump.txt')
config['backup_path'] = os.path.join(data_home, 'autojump.txt.bak') config['backup_path'] = os.path.join(data_home, 'autojump.txt.bak')
config['tmp_path'] = os.path.join(data_home, 'data.tmp')
return config return config

@ -7,6 +7,7 @@ from collections import namedtuple
import os import os
import shutil import shutil
import sys import sys
from tempfile import NamedTemporaryFile
from time import time from time import time
if sys.version_info[0] == 3: if sys.version_info[0] == 3:
@ -119,11 +120,9 @@ def save(config, data):
# atomically save by writing to temporary file and moving to destination # atomically save by writing to temporary file and moving to destination
try: try:
# write to temp file # write to temp file
with open( temp = NamedTemporaryFile(delete=False)
config['tmp_path'],
'w', with open(temp.name, 'w', encoding='utf-8', errors='replace') as f:
encoding='utf-8',
errors='replace') as f:
for path, weight in data.items(): for path, weight in data.items():
f.write(unico("%s\t%s\n" % (weight, path))) f.write(unico("%s\t%s\n" % (weight, path)))
@ -134,10 +133,9 @@ def save(config, data):
sys.exit(1) sys.exit(1)
# move temp_file -> autojump.txt # move temp_file -> autojump.txt
move_file(config['tmp_path'], config['data_path']) move_file(temp.name, config['data_path'])
# create backup file if it doesn't exist or is older than BACKUP_THRESHOLD # create backup file if it doesn't exist or is older than BACKUP_THRESHOLD
if not os.path.exists(config['backup_path']) or \ if not os.path.exists(config['backup_path']) or \
(time() - os.path.getmtime(config['backup_path']) (time() - os.path.getmtime(config['backup_path']) > BACKUP_THRESHOLD): #noqa
> BACKUP_THRESHOLD):
shutil.copy(config['data_path'], config['backup_path']) shutil.copy(config['data_path'], config['backup_path'])

Loading…
Cancel
Save