1
0
Fork 0
mirror of synced 2024-11-23 00:35:34 -05:00

Refactor Link._move into Link._backup

This commit is contained in:
c-c-k 2023-07-17 19:38:44 +03:00
parent 6b324328b6
commit 4121157c8d

View file

@ -2,7 +2,7 @@ import glob
import os import os
import shutil import shutil
import sys import sys
import errno import datetime
from ..plugin import Plugin from ..plugin import Plugin
from ..util import shell_command from ..util import shell_command
@ -121,26 +121,46 @@ class Link(Plugin):
self._log.debug("Test '%s' returned false" % command) self._log.debug("Test '%s' returned false" % command)
return ret == 0 return ret == 0
def _move(self, link_name, path): def _backup(self, link_name, backup_root):
if not backup_root:
return False
success = True success = True
source = os.path.expanduser(link_name) source = os.path.expanduser(link_name)
destination = os.path.join(self._context.base_directory(), path) timestamp = datetime.datetime.now().strftime(".%Y%m%dT%H%M%S.%f")
if os.path.isdir(source): backup_root = os.path.expandvars(os.path.expanduser(backup_root))
shutil.copytree(source, destination) backup_root = os.path.normpath(os.path.join(self._context.base_directory(), backup_root))
shutil.rmtree(source, ignore_errors=True) destination, ext = os.path.splitext(
os.path.normpath(os.path.splitdrive(source)[1]).strip("/")
)
destination = os.path.join(backup_root, destination + timestamp + ext)
success &= self._create(destination)
if os.path.islink(source):
try:
shutil.copy2(source, destination, follow_symlinks=False)
except OSError:
self._log.warning("Failed to backup symlink %s to %s" % (source, destination))
success = False
else:
self._log.lowinfo("Performed backup of symlink %s to %s" % (source, destination))
elif os.path.isdir(source):
try:
shutil.copytree(source, destination, symlinks=True)
except OSError:
self._log.warning("Failed to backup directory %s to %s" % (source, destination))
success = False
else:
self._log.lowinfo("performed backup of directory %s to %s" % (source, destination))
elif os.path.isfile(source): elif os.path.isfile(source):
try: try:
os.makedirs(os.path.split(destination)[0]) shutil.copy2(source, destination)
except OSError as exception: except OSError:
if exception.errno != errno.EEXIST: self._log.warning("Failed to backup file %s to %s" % (source, destination))
success = False success = False
# TODO: check what is eerno.EEXIST and replace above with pass if relevant
shutil.copy(source, destination)
os.unlink(source)
else: else:
self._log.warning("Config file missing %s" % source) self._log.lowinfo("Performed backup of file %s to %s" % (source, destination))
return False else:
self._log.info("Moved existing config %s" % source) self._log.warning("Failed to backup irregular file %s" % source)
success = False
return success return success
def _default_source(self, destination, source): def _default_source(self, destination, source):