Implement backing up before overwriting files

This commit is contained in:
Juno Takano 2024-09-01 22:48:34 -03:00
parent 7b2f1494b9
commit 4b6a956995
4 changed files with 37 additions and 0 deletions

28
src/file/backup.sh Normal file
View file

@ -0,0 +1,28 @@
# takes a list of space-separated absolute paths
# backs each path up, creating canonical or ephemeral copies as needed
backup_paths() {
local paths="$1"
local canonical_path=
local ephemeral_path=
for path in $paths; do
canonical_path="$BACKUP_ROOT/canonical$path"
timestamp="$(date +'%Y-%m-%dT%H-%M-%S')"
ephemeral_path="$BACKUP_ROOT/ephemeral${path}_$timestamp"
if [ -f "$canonical_path" ]; then
log debug "[backup] Creating ephemeral copy for $path"
mkdir -p "$(dirname "$ephemeral_path")"
if [ -f "$ephemeral_path" ]; then
log debug "[backup] Overwriting ephemeral copy for $path"
cp -f "$path" "$ephemeral_path"
else
cp "$path" "$ephemeral_path"
fi
else
log debug "[backup] Creating canonical copy for $path"
mkdir -p "$(dirname "$canonical_path")"
cp "$path" "$canonical_path"
fi
done
}

View file

@ -53,9 +53,11 @@ file_merge_tree() {
if [ "$strategy" -eq 0 ]; then if [ "$strategy" -eq 0 ]; then
return 0 return 0
elif [ "$strategy" -eq 1 ]; then elif [ "$strategy" -eq 1 ]; then
backup_paths "$absolute_path"
cp -vi "$config_path" "$absolute_path" cp -vi "$config_path" "$absolute_path"
return 1 return 1
elif [ "$strategy" -eq 2 ]; then elif [ "$strategy" -eq 2 ]; then
backup_paths "$config_path"
cp -vi "$absolute_path" "$config_path" cp -vi "$absolute_path" "$config_path"
return 1 return 1
elif [ "$strategy" -eq 3 ]; then elif [ "$strategy" -eq 3 ]; then

View file

@ -11,3 +11,4 @@
. "$TORI_ROOT/src/package/update_package_cache.sh" . "$TORI_ROOT/src/package/update_package_cache.sh"
. "$TORI_ROOT/src/file/file_merge.sh" . "$TORI_ROOT/src/file/file_merge.sh"
. "$TORI_ROOT/src/file/backup.sh"

View file

@ -134,6 +134,12 @@ prepare_directories() {
if ! [ -d "$BACKUP_ROOT" ]; then if ! [ -d "$BACKUP_ROOT" ]; then
mkdir -p "$BACKUP_ROOT" mkdir -p "$BACKUP_ROOT"
if ! [ -d "$BACKUP_ROOT/canonical" ]; then
mkdir "$BACKUP_ROOT/canonical"
fi
if ! [ -d "$BACKUP_ROOT/ephemeral" ]; then
mkdir "$BACKUP_ROOT/ephemeral"
fi
fi fi
if ! [ -d "$CONFIG_ROOT" ]; then if ! [ -d "$CONFIG_ROOT" ]; then