Skip to content

Instantly share code, notes, and snippets.

@svandragt
Created September 27, 2022 13:45
Show Gist options
  • Select an option

  • Save svandragt/1332a13d002583136a0a52d0439e62df to your computer and use it in GitHub Desktop.

Select an option

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.
#!/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)
@svandragt

svandragt commented Sep 27, 2022

Copy link
Copy Markdown
Author

chmod +x backup.py and put it in your path.

bla/something git:(develop)$  backup.py wp-tests-config.php
Backed up to /Users/sander/Sync/Personal/backup/sander-mbp.local/Users/sander/dev/bla/something/wp-tests-config.php

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment