Fix FileStore.backup_file() not to backup same file

FileStore.backup_file() docstring claimed not to store a
copy of the same file but the behavior of the method did not
match this description.

This commit makes the backed-up file filename derivation
deterministic by hashing its content by SHA-256, thus it
should not back up two files with the same filename and content.

Reviewed-By: Aleksei Slaikovskii <aslaikov@redhat.com>
This commit is contained in:
Stanislav Laznicka 2018-02-19 09:50:41 +01:00
parent 631d3152fe
commit 364ffd5a0f
No known key found for this signature in database
GPG Key ID: C98C414936B1A7F3

View File

@ -29,6 +29,8 @@ import os.path
import shutil
import random
from hashlib import sha256
import six
# pylint: disable=import-error
if six.PY3:
@ -111,7 +113,7 @@ class FileStore(object):
p.write(f)
def backup_file(self, path):
"""Create a copy of the file at @path - so long as a copy
"""Create a copy of the file at @path - as long as an exact copy
does not already exist - which will be restored to its
original location by restore_files().
"""
@ -126,11 +128,11 @@ class FileStore(object):
_reldir, backupfile = os.path.split(path)
filename = ""
for _i in range(8):
h = "%02x" % self.random.randint(0,255)
filename += h
filename += "-"+backupfile
with open(path, 'rb') as f:
cont_hash = sha256(f.read()).hexdigest()
filename = "{hexhash}-{bcppath}".format(
hexhash=cont_hash, bcppath=backupfile)
backup_path = os.path.join(self._path, filename)
if os.path.exists(backup_path):