feat(bin): t, add support for existing sessions

This commit is contained in:
2025-01-14 05:56:19 +02:00
parent 2a76a414a0
commit ad166e8012

View File

@@ -4,6 +4,7 @@
# https://github.com/jessarcher/dotfiles/blob/master/scripts/t # https://github.com/jessarcher/dotfiles/blob/master/scripts/t
# #
# Tweaks by Ismo Vuorinen <https://github.com/ivuorinen> 2025 # Tweaks by Ismo Vuorinen <https://github.com/ivuorinen> 2025
# vim: ft=bash ts=2 sw=2 et
# Set environment variables for configuration with defaults # Set environment variables for configuration with defaults
T_ROOT="${T_ROOT:-$HOME/Code}" T_ROOT="${T_ROOT:-$HOME/Code}"
@@ -16,30 +17,73 @@ error_exit()
exit 1 exit 1
} }
get_directories()
{
local dirs=''
dirs+='# Directories\n'
dirs+=$(find "$T_ROOT" -maxdepth 2 -mindepth 1 -type d ! -name '.git' ! -name '.svn')
dirs+="$(printf "\n%s" "$DOTFILES")"
echo "$dirs"
}
check_tmux()
{
if ! command -v tmux &> /dev/null; then
error_exit "tmux is not installed."
fi
# check to see that tmux server is running
if ! tmux info &> /dev/null; then
tmux start-server
fi
}
get_sessions()
{
check_tmux
local sessions=''
sessions+='# Sessions\n'
sessions+=$(tmux list-sessions -F "#{session_name}" 2> /dev/null)
echo "$sessions"
}
items=''
# Select the directory # Select the directory
if [[ $# -eq 1 ]]; then if [[ $# -eq 1 ]]; then
selected="$1" selected="$1"
else else
items=$(find "$T_ROOT" -maxdepth 2 -mindepth 1 -type d) items+=$(get_sessions)
items+="$(printf "\n%s" "$DOTFILES")" items+='\n'
items+="$(printf "\n/tmp")" items+=$(get_directories)
selected=$(echo -e "$items" | fzf) || exit 0 # Exit if no selection is made selected=$(echo -e "$items" | fzf) || exit 0 # Exit if no selection is made
fi fi
# If user selected a header, exit
[[ ${selected:0:1} == "#" ]] && error_exit "You selected a header, why?"
# Exit if no directory was selected # Exit if no directory was selected
[[ -z $selected ]] && error_exit "No directory selected." [[ -z $selected ]] && error_exit "No directory selected."
# Sanitize the session name # Sanitize the session name
dirname=$(basename "$selected" | tr '.' '_') session_name=$(basename "$selected")
# If we get nothing, we are dealing with a session
[[ $session_name == "" ]] && session_name="$selected"
# Remove dots from the session name as tmux doesn't like them
session_name="${session_name//./}"
# Try to switch to the tmux session # Try to switch to the tmux session
if tmux switch-client -t "=$dirname" 2> /dev/null; then if tmux switch-client -t "=$session_name" 2> /dev/null; then
exit 0 exit 0
fi fi
# Create a new tmux session or attach to an existing one # Create a new tmux session or attach to an existing one
if tmux new-session -c "$selected" -d -s "$dirname" 2> /dev/null; then if tmux new-session -c "$selected" -d -s "$session_name" 2> /dev/null; then
tmux switch-client -t "$dirname" tmux switch-client -t "$session_name"
else else
tmux new -c "$selected" -A -s "$dirname" tmux new -c "$selected" -A -s "$session_name"
fi fi