Last active
June 30, 2020 06:26
-
-
Save GiowGiow/37fa19ad763017bba18da16238448876 to your computer and use it in GitHub Desktop.
Switches Symlink and Target location, useful when using pools of disks like mergerfs that don't allow hardlinks
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
| from pathlib import Path | |
| import os | |
| import sys | |
| from shutil import copyfile | |
| def try_to_copy_file(src, dest): | |
| try: | |
| copyfile(src, dest) | |
| return True | |
| except: | |
| print("An error has occurred when copying the file...") | |
| # Recreate deleted Symlink | |
| os.remove(dest) | |
| os.symlink(dest, src) | |
| return False | |
| def reverse_symlink(symlink_path, original_file_path): | |
| if not os.path.exists(original_file_path): | |
| print("Original file path is broken, can't reverse symlink\n".format(original_file_path)) | |
| print("Removing Broken Symlink") | |
| os.remove(symlink_path) | |
| return | |
| os.remove(symlink_path) | |
| ret = try_to_copy_file(original_file_path, symlink_path) | |
| if not ret: | |
| return | |
| os.remove(original_file_path) | |
| os.symlink(symlink_path, original_file_path) | |
| if len(sys.argv) == 2: | |
| folder_dir = sys.argv[1] | |
| if os.path.exists(folder_dir): | |
| p = Path(folder_dir) | |
| print (p) | |
| root = p | |
| links = [link for link in root.rglob('*') if link.is_symlink()] | |
| files = [os.readlink(str(pointed_file)) for pointed_file in links] | |
| if (len(links) == len(files)) and len(links) > 0: | |
| print("Invertendo Symlinks:\n") | |
| for i in range(len(links)): | |
| print("\nInvertendo:\n\n(Symlink)\n{}\n\n(File Original)\n{}\n\n".format(links[i], files[i])) | |
| reverse_symlink(links[i],files[i]) | |
| elif len(links) == 0: | |
| print("No symlinks to reverse") | |
| else: | |
| print("Something happened that the links and files list have a mismatch") | |
| else: | |
| print("Use a path as argument") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment