dotfiles/script/utils
2024-01-28 11:55:11 -08:00

141 lines
2.5 KiB
Fish
Executable file

#!/usr/bin/env fish
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
function print_in_color
printf '%b' \
"$(tput setaf $argv[2] 2> /dev/null)" \
$argv[1] \
"$(tput sgr0 2> /dev/null)"
end
function print_in_red
print_in_color $argv[1] 1
end
function print_in_yellow
print_in_color $argv[1] 3
end
function print_in_green
print_in_color $argv[1] 2
end
function print_in_purple
print_in_color $argv[1] 5
end
function print_title
print_in_purple "\n • $argv[1]\n\n"
end
function print_success
print_in_green " [✔] $argv[1]\n"
end
function print_warning
print_in_yellow " [!] $argv[1]\n"
end
function print_error
print_in_red " [✖] $argv[1] $argv[2]\n"
end
function print_question
print_in_yellow " [?] $argv[1]\n"
end
function print_result
if [ "$argv[1]" -eq 0 ]
print_success $argv[2]
else
print_error $argv[2]
end
return $argv[1]
end
function print_error_stream
while read -r line
print_error "↳ ERROR: $line"
end
end
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
function show_spinner
set -l frames '/-\|'
set -l number_of_frames (string length $FRAMES)
set -l pid $argv[1]
set -l cmds $argv[2]
set -l msg $argv[3]
set -l i 0
set -l frame_text ""
printf "\n\n\n"
tput cuu 3
tput sc
while kill -0 "$pid" &> /dev/null
set i math $i + 1
set -l num math % $number_of_frames
set -l frame (string sub -s $num -l 1)
set frame_text " [$frame] $msg"
printf '%s' $frame_text
sleep 0.2
tput rc
end
end
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
function set_trap
trap -p "$argv[1]" | grep "$argv[2]" &> /dev/null \
|| trap "$argv[2]" "$argv[1]"
end
function kill_all_subproccesses
set -l i ""
for i in (jobs -p)
kill "$i"
wait "$i" &> /dev/null
end
end
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
function execute
set -l cmds $argv[1]
set -q $argv[2] and set -l msg $argv[2] or set -l msg $argv[1]
set -l tmp_file "$(mktmp /tmp/XXXXX)"
set -l exit_code 0
set_trap 'EXIT' 'kill_all_subproccesses'
eval "$cmds" &> /dev/null 2> $tmp_file &
set cmds_pid $last_pid
show_spinner $cmds_pid $cmds $msg
wait $cmds_pid &> /dev/null
set exit_code $status
print_result $exit_code $msg
if [ $exit_code -ne 0 ]
print_error_stream < $tmp_file
end
rm -rf "$tmp_file"
return $exit_code
end