dotfiles/zsh/preserve-cwd-ssh.zsh

85 lines
2.5 KiB
Bash
Raw Normal View History

2024-06-21 16:28:36 +01:00
if [ "$PRESERVE_SSH_CWD" = "true" ]; then
2024-06-21 17:16:54 +01:00
2024-06-23 15:31:17 +01:00
# Ensure the directory where we store terminal cwds and ssh exists
2024-06-21 16:28:36 +01:00
mkdir -p $HOME/.config/terminalscwd/
2024-06-23 15:31:17 +01:00
# Alias for cd: when we change directory, we write the new cwd in the file corresponding to the terminal uuid
2024-06-21 16:28:36 +01:00
cd() {
2024-07-31 09:01:49 +01:00
if [ -z "$1" ]; then
directory=$HOME
2024-09-07 20:06:30 +01:00
elif [[ "$1" == "-P" ]] && [ -z $2 ]; then
directory="$HOME"
option="$1"
elif [[ "$1" == "-P" ]]; then
directory="$2"
option="$1"
2024-07-31 09:01:49 +01:00
else
directory="$1"
fi
2024-09-07 20:06:30 +01:00
if [ -z "$option" ]; then
builtin cd "$directory"
else
builtin cd "$option" "$directory"
fi
2024-06-23 15:31:17 +01:00
pwd > $HOME/.config/terminalscwd/$TERMINAL_UUID.cwd
2024-06-21 16:28:36 +01:00
}
2024-06-23 15:31:17 +01:00
# Alias for ssh: when we ssh somewhere, we write it so that we know we should ssh when cloning terminal
2024-06-21 16:28:36 +01:00
ssh() {
echo $1 > $HOME/.config/terminalscwd/$TERMINAL_UUID.ssh
/usr/bin/ssh $@
rm $HOME/.config/terminalscwd/$TERMINAL_UUID.ssh
2024-06-23 15:31:17 +01:00
pwd > $HOME/.config/terminalscwd/$TERMINAL_UUID.cwd
}
# If terminal uuid does not exit
if [ -z $TERMINAL_UUID ]; then
# Generate one
export TERMINAL_UUID=$(uuidgen)
fi
# Copy state for new terminal
if [ ! -z $PARENT_TERMINAL ]; then
if [ -f $HOME/.config/terminalscwd/$PARENT_TERMINAL.cwd ]; then
cp $HOME/.config/terminalscwd/$PARENT_TERMINAL.cwd $HOME/.config/terminalscwd/$TERMINAL_UUID.cwd
fi
if [ -f $HOME/.config/terminalscwd/$PARENT_TERMINAL.ssh ]; then
cp $HOME/.config/terminalscwd/$PARENT_TERMINAL.ssh $HOME/.config/terminalscwd/$TERMINAL_UUID.ssh
fi
2024-06-23 15:31:17 +01:00
fi
# When we're done, delete the uuid files
preserve_ssh_cleanup() {
rm -rf $HOME/.config/terminalscwd/$TERMINAL_UUID.cwd
rm -rf $HOME/.config/terminalscwd/$TERMINAL_UUID.ssh
2024-06-21 16:28:36 +01:00
}
2024-06-23 15:31:17 +01:00
trap preserve_ssh_cleanup EXIT
# If there already is a file corresponding to the current uuid
if [ -f $HOME/.config/terminalscwd/$TERMINAL_UUID.cwd ]; then
# Go the the right directory
2024-07-24 10:32:23 +01:00
cd "$(cat $HOME/.config/terminalscwd/$TERMINAL_UUID.cwd)"
2024-06-23 15:31:17 +01:00
else
# Use our custom alias to go to home, and set the file cwd
cd
fi
# If we're running in an ssh session
if [ -f $HOME/.config/terminalscwd/$TERMINAL_UUID.ssh ]; then
# Run the ssh command, and exec shell in the end so the terminal doesn't exit at end of ssh
ssh $(cat $HOME/.config/terminalscwd/$TERMINAL_UUID.ssh)
fi
2024-06-21 16:28:36 +01:00
fi