Created
February 23, 2024 11:58
-
-
Save aparatext/e1d8e14b763228a18f25037e73725771 to your computer and use it in GitHub Desktop.
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
| function mv.ln --description 'Move a file/directory, create symlink in old location. Includes undo flag.' | |
| argparse 'u/undo' -- $argv | |
| or return | |
| if [ (count $argv) -ne 2 ] | |
| and [ not $_flag_undo ] | |
| echo "Usage: mv.ln [-u|--undo] <source> <destination>" | |
| return 1 | |
| end | |
| set source (realpath $argv[1]) | |
| set destination (realpath $argv[2]) | |
| if set -q _flag_undo | |
| if not test -L $argv[1] | |
| echo "mv.ln: Undo failed, $argv[1] is not a symlink or doesn't exist." | |
| return 1 | |
| end | |
| set symlink_target (readlink -- $argv[1]) | |
| set resolved_symlink_target (realpath $symlink_target) | |
| if [ "$resolved_symlink_target" != "$destination" ] | |
| echo "mv.ln: Undo failed, $argv[1] symlink does not point to the canonicalized $destination." | |
| return 1 | |
| end | |
| command rm -- $argv[1] | |
| command mv -- $destination $argv[1] | |
| echo "mv.ln: Moved $destination back to $argv[1]" | |
| return 0 | |
| end | |
| if test -e $destination | |
| echo "mv.ln: $destination exists. Aborting." | |
| return 1 | |
| else if not test -e $source | |
| echo "mv.ln: $source does not exist. Aborting." | |
| return 1 | |
| end | |
| if command mv -- $source $destination | |
| if command ln -s -- $destination $source | |
| echo "mv.ln: Moved $source to $destination and created symlink." | |
| return 0 | |
| else | |
| echo "mv.ln: Failed to create symlink, attempting to undo move." | |
| if not command mv -- $destination $source | |
| echo "mv.ln: Critical error, undo move failed. Manual recovery required." | |
| end | |
| return 1 | |
| end | |
| else | |
| echo "mv.ln: Operation failed." | |
| return 1 | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment