# Bash integration for TUI. # This file is sourced automatically by the installer from ~/.bashrc. # Actions are executed by this Bash process, not by a child shell in Python. tui() { local tui_python tui_python="${TUI_PYTHON:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/tui.py}" if [[ ! -f "$tui_python" ]]; then echo "tui: cannot find $tui_python" >&2 return 127 fi local tui_dir="." local show_all=0 local arg for arg in "$@"; do case "$arg" in -a|--all) show_all=1 ;; -v|--version) python3 "$tui_python" --version; return $? ;; *) tui_dir="$arg" ;; esac done local command_file local cwd_file local all_file local rc local cmd local tui_cwd local tui_all local -a tui_commands command_file="$(mktemp)" cwd_file="$(mktemp)" all_file="$(mktemp)" printf '%s\n' "$show_all" > "$all_file" while :; do : > "$command_file" : > "$cwd_file" : > "$all_file" if (( show_all )); then TUI_COMMAND_FILE="$command_file" \ TUI_CWD_FILE="$cwd_file" \ TUI_ALL_FILE="$all_file" \ python3 "$tui_python" -a "$tui_dir" else TUI_COMMAND_FILE="$command_file" \ TUI_CWD_FILE="$cwd_file" \ TUI_ALL_FILE="$all_file" \ python3 "$tui_python" "$tui_dir" fi rc=$? tui_cwd="$(<"$cwd_file")" tui_all="$(<"$all_file")" if [[ "$tui_all" == "1" ]]; then show_all=1 elif [[ "$tui_all" == "0" ]]; then show_all=0 fi # Ctrl+C exits TUI. Apply the last directory in the parent Bash # process, then return to the caller. if (( rc == 43 )); then if [[ -n "$tui_cwd" && -d "$tui_cwd" ]]; then cd -- "$tui_cwd" || { rm -f "$command_file" "$cwd_file" "$all_file" return 1 } fi rm -f "$command_file" "$cwd_file" "$all_file" return 0 fi if (( rc != 42 )); then rm -f "$command_file" "$cwd_file" "$all_file" return "$rc" fi if [[ -z "$tui_cwd" || ! -d "$tui_cwd" ]]; then echo "tui: invalid TUI working directory" >&2 rm -f "$command_file" "$cwd_file" "$all_file" return 1 fi # Execute all commands belonging to one TUI action before starting # TUI again. Each command remains a normal Bash command and gets its # own history entry. If a command fails, stop the action and pause so # the user has time to see the error. pushd "$tui_cwd" >/dev/null || { rm -f "$command_file" "$cwd_file" "$all_file" return 1 } mapfile -t tui_commands < "$command_file" for cmd in "${tui_commands[@]}"; do [[ -z "$cmd" ]] && continue history -s -- "$cmd" eval "$cmd" rc=$? if (( rc != 0 )); then printf '\nTUI: command failed (exit %d)\n' "$rc" >&2 read -rp 'Tryck Enter för att fortsätta...' _ break fi done popd >/dev/null || true # Re-enter TUI at the directory in which the action was created. tui_dir="$tui_cwd" done }