Add backup system

This commit is contained in:
ItsDrike 2020-10-23 01:08:01 +02:00
parent c08e720c2b
commit a87f8b83dd
No known key found for this signature in database
GPG key ID: F4E8FF4F6AC7F3B4
2 changed files with 62 additions and 0 deletions

View file

@ -1,6 +1,7 @@
import os
from src.packages import install_packages
from src.dotfiles import install_dotfiles
from src.util.user import Input, Print
@ -11,6 +12,8 @@ def main():
if Input.yes_no("Do you wish to perform package install (from `packages.yaml`)?"):
install_packages()
if Input.yes_no("Do you wish to install dotfiles (sync `home/` and `root/` directories accordingly)? You can make a backup."):
install_dotfiles()
try:

59
src/dotfiles.py Normal file
View file

@ -0,0 +1,59 @@
import os
import shutil
from datetime import datetime
from contextlib import suppress
from src.util.user import Print, Input
def _backup_file(backup_dir: str, subdir: str, file: str):
"""
Backup given `file` in given `subdir`
"""
origin_subdir = subdir.replace("home/", f"{os.environ['HOME']}/").replace("root/", "/")
origin_path = os.path.join(origin_subdir, file)
# Only backup files which exists in origin destination (real system destination)
if os.path.exists(origin_path):
backup_subdir = os.path.join(backup_dir, subdir)
backup_path = os.path.join(backup_subdir, file)
# Ensure directory existence in the new backup directory
with suppress(FileExistsError):
os.makedirs(backup_subdir)
if file != "placeholder":
Print.comment(f"Backing up {origin_path}")
shutil.copyfile(origin_path, backup_path)
def make_backup() -> None:
"""
Find all files which will be replaced and back them up.
Files which doesn't exist in the real system destination
will be ignored.
"""
Print.action("Creating current dotfiles backup")
time = str(datetime.now()).replace(" ", "--")
backup_dir = os.path.join(os.getcwd(), "backup", time)
os.makedirs(backup_dir)
# backup files in `home` directory
for subdir, _, files in os.walk("home"):
for file in files:
_backup_file(backup_dir, subdir, file)
# backup files in `root` directory
for subdir, _, files in os.walk("root"):
for file in files:
_backup_file(backup_dir, subdir, file)
Print.action("Backup complete")
def install_dotfiles():
if Input.yes_no("Do you want to backup current dotfiles? (Recommended)"):
make_backup()
if __name__ == "__main__":
install_dotfiles()