Files
dotfiles/local/bin/t

113 lines
2.6 KiB
Bash
Executable File

#!/usr/bin/env bash
#
# Credit to ThePrimeagen, jessarcher
# https://github.com/jessarcher/dotfiles/blob/master/scripts/t
#
# Tweaks by Ismo Vuorinen <https://github.com/ivuorinen> 2025
# vim: ft=bash ts=2 sw=2 et
# Set environment variables for configuration with defaults
T_ROOT="${T_ROOT:-$HOME/Code}"
DOTFILES="${DOTFILES:-$HOME/.dotfiles}"
# Function to print an error message and exit
error_exit()
{
echo "Error: $1" >&2
exit 1
}
get_directories()
{
local dirs=''
dirs+='# Directories\n'
dirs+=$(
find "$T_ROOT" \
-maxdepth 3 \
-mindepth 1 \
-type d \
-not -path '*/dist/*' \
-not -path '*/dist' \
-not -path '*/node_modules/*' \
-not -path '*/node_modules' \
-not -path '*/vendor/*' \
-not -path '*/vendor' \
-not -path '*/.idea/*' \
-not -path '*/.idea' \
-not -path '*/.vscode/*' \
-not -path '*/.vscode' \
-not -path '*/.git/*' \
-not -path '*/.git' \
-not -path '*/.svn/*' \
-not -path '*/.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
if [[ $# -eq 1 ]]; then
selected="$1"
else
items+=$(get_sessions | sort)
items+='\n'
items+=$(get_directories | sort)
selected=$(echo -e "$items" | fzf) || exit 0 # Exit if no selection is made
fi
# If user selected a header, exit
[[ ${selected:0:1} == "#" ]] && error_exit "You selected a header, why?"
# Exit if no directory was selected
[[ -z $selected ]] && error_exit "No directory selected."
# Sanitize the session name
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
tmux switch-client -t "=$session_name"
active_session=$(tmux display-message -p -F '#{session_name}' 2> /dev/null)
# echo "active session: $active_session"
if [ -n "$active_session" ] && [ "$active_session" == "$session_name" ]; then
exit 0
fi
# Create a new tmux session or attach to an existing one
if tmux new-session -c "$selected" -d -s "$session_name" 2> /dev/null; then
tmux switch-client -t "$session_name"
else
tmux new -c "$selected" -A -s "$session_name"
fi