nix/modules/home-manager/cli/tmux/files/create-tmux-session.sh
Yorick Barbanneau d355e9bc01
fix(tmux): avoid index error creating new window
And ensure new windows is created after the last one
2025-05-05 10:35:15 +02:00

147 lines
2.9 KiB
Bash
Executable file

#!/usr/bin/env bash
set -e
set -o pipefail
DEBUG=0
declare -a COMMANDS
error() {
local message
printf -v message "\e[31mERROR:\e[0m %s\n" "$1"
>&2 printf "%b" "${message}"
}
debug() {
local message
if [[ $DEBUG -eq 1 ]]; then
printf -v message "\e[3;34mDEBUG:\e[0m %s\n" "$*"
>&2 printf "%b" "$message"
fi
}
process_args() {
until [[ -z $1 ]]; do
case $1 in
-s | --session-name | --session)
SESSION="$2"
shift
;;
-p | --project-name | --window)
PROJECT="$2"
shift
;;
-d | --debug)
DEBUG=1
;;
*)
COMMANDS+=("$1")
;;
esac
shift
done
}
has_session() {
local session_name="${1}"
tmux has-session -t "${session_name}" 2>/dev/null
}
get_project_path() {
local identifier="${1}"
debug "get project path with identifier '$identifier'"
if [[ -z "$identifier" ]]; then
CURRENT_PATH=$(ghq list -p | fzf)
else
CURRENT_PATH=$(ghq list -p -e "$identifier")
fi
}
is_running_in_tmux() {
debug "check if running in tmux"
if [[ -z $TMUX ]]; then
error "This script should run in a running instance of Tmux"
exit 10
fi
}
check_script_inputs() {
debug "check script inputs"
if [[ -z "$SESSION" ]]; then
error "You must provide a session name"
exit 5
fi
}
process_commands() {
local input="$1"
debug "Process command '$input'"
local cmd arg
if [[ "$input" =~ ^.*:.*$ ]]; then
debug "command and parameter found"
arg=${input##*:}
cmd=${input%%:*}
else
debug "command found without parameter"
cmd="$input"
fi
if ! "tmux_${cmd}" "${arg}"; then
error "Command \`$cmd\` not exist"
fi
}
tmux_vsplit() {
local size="${1:-20}"
debug "execute vsplit with size '${size}'"
tmux split-window -t "$SESSION" -c "$CURRENT_PATH" -v -p "$size"
}
tmux_hsplit() {
local size="${1:-20}"
debug "execute hsplit with size '${size}'"
tmux split-window -t "$SESSION" -c "$CURRENT_PATH" -h -p "$size"
}
tmux_neww() {
local name="$1"
debug "execute neww with name '${name}'"
local command=(tmux new-window -t "${SESSION}:$" -c "$CURRENT_PATH" -a)
if [[ -n "$name" ]]; then
command+=(-n "$name")
fi
"${command[@]}"
}
tmux_run() {
local shell_command="$1"
debug "execute run with command '${shell_command}'"
if [[ -z "$shell_command" ]]; then
error "tmux-run need a command"
else
tmux send-keys -t "$SESSION" "$shell_command" "C-m"
fi
}
project() {
local arg="$1"
debug "execute project with arg '${arg}'"
get_project_path "$arg"
}
main() {
process_args "$@"
is_running_in_tmux
check_script_inputs
if ! has_session "$SESSION"; then
get_project_path "${PROJECT:-$SESSION}"
tmux new-session -ds "${SESSION}" -c "${CURRENT_PATH}" -n "${PROJECT}"
# Process commands passed with command line
for command in "${COMMANDS[@]}"; do
process_commands "$command"
done
fi
tmux switch-client -t "${SESSION}"
}
main "${@}"