Created
September 27, 2022 13:45
-
-
Save svandragt/1332a13d002583136a0a52d0439e62df to your computer and use it in GitHub Desktop.
Python3 script that: Replaces a file with a symlink, pointing to the path-preserving backup, unique per hostname.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python3 | |
| """ | |
| Replaces a file with a symlink, pointing to the path-preserving backup, unique per hostname. | |
| version 2022-09-27 | |
| """ | |
| import os | |
| import sys | |
| import shutil | |
| import socket | |
| # must end in a slash | |
| BACKUP_PATH = "/Users/sander/Sync/Personal/backup/" | |
| def action(relpath): | |
| source = os.path.abspath(relpath) | |
| if not source or not os.path.exists(source): | |
| print(relpath, 'file does not exist!') | |
| return | |
| if os.path.islink(source): | |
| print(relpath, 'is a symlink!') | |
| return | |
| hostname = socket.gethostname() | |
| dirname = os.path.dirname(source) | |
| destpath = f'{BACKUP_PATH}{hostname}{dirname}' | |
| destination = f'{BACKUP_PATH}{hostname}{source}' | |
| try: | |
| os.makedirs(destpath) | |
| except FileExistsError: | |
| pass | |
| result = shutil.move(source, destination) | |
| if not result: | |
| print('Could not be moved!') | |
| return | |
| result = os.symlink(destination, source) | |
| print('Backed up to', destination) | |
| if __name__ == '__main__': | |
| relpath = sys.argv[1] | |
| action(relpath) |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
chmod +x backup.pyand put it in your path.