1
0
mirror of https://github.com/wting/autojump synced 2024-10-27 20:34:07 +00:00

Use temporary files to prevent IO race conditions.

Refer to #260.
This commit is contained in:
William Ting 2014-03-09 19:56:13 -07:00
parent 4bd62e2293
commit 4826a0ef6b
2 changed files with 6 additions and 9 deletions

View File

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

View File

@ -7,6 +7,7 @@ from collections import namedtuple
import os
import shutil
import sys
from tempfile import NamedTemporaryFile
from time import time
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
try:
# write to temp file
with open(
config['tmp_path'],
'w',
encoding='utf-8',
errors='replace') as f:
temp = NamedTemporaryFile(delete=False)
with open(temp.name, 'w', encoding='utf-8', errors='replace') as f:
for path, weight in data.items():
f.write(unico("%s\t%s\n" % (weight, path)))
@ -134,10 +133,9 @@ def save(config, data):
sys.exit(1)
# 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
if not os.path.exists(config['backup_path']) or \
(time() - os.path.getmtime(config['backup_path'])
> BACKUP_THRESHOLD):
(time() - os.path.getmtime(config['backup_path']) > BACKUP_THRESHOLD): #noqa
shutil.copy(config['data_path'], config['backup_path'])