|
| 1 | +#!/usr/bin/env bash |
| 2 | + |
| 3 | +if [ -z "$BASH_IT_COMMAND_DURATION" ] || [ "$BASH_IT_COMMAND_DURATION" != true ]; then |
| 4 | + _command_duration() { |
| 5 | + echo -n |
| 6 | + } |
| 7 | + return |
| 8 | +fi |
| 9 | + |
| 10 | +# Define tmp dir and file |
| 11 | +COMMAND_DURATION_TMPDIR="${TMPDIR:-/tmp}" |
| 12 | +COMMAND_DURATION_FILE="${COMMAND_DURATION_FILE:-$COMMAND_DURATION_TMPDIR/bashit_theme_execution_$BASHPID}" |
| 13 | + |
| 14 | +COMMAND_DURATION_ICON=${COMMAND_DURATION_ICON:-' '} |
| 15 | +COMMAND_DURATION_MIN_SECONDS=${COMMAND_DURATION_MIN_SECONDS:-'1'} |
| 16 | + |
| 17 | +trap _command_duration_delete_temp_file EXIT HUP INT TERM |
| 18 | + |
| 19 | +_command_duration_delete_temp_file() { |
| 20 | + if [[ -f "$COMMAND_DURATION_FILE" ]]; then |
| 21 | + rm -f "$COMMAND_DURATION_FILE" |
| 22 | + fi |
| 23 | +} |
| 24 | + |
| 25 | +_command_duration_pre_exec() { |
| 26 | + date +%s.%1N > "$COMMAND_DURATION_FILE" |
| 27 | +} |
| 28 | + |
| 29 | +_command_duration() { |
| 30 | + local command_duration command_start current_time |
| 31 | + local minutes seconds deciseconds |
| 32 | + local command_start_sseconds current_time_seconds command_start_deciseconds current_time_deciseconds |
| 33 | + current_time=$(date +%s.%1N) |
| 34 | + |
| 35 | + if [[ -f "$COMMAND_DURATION_FILE" ]]; then |
| 36 | + command_start=$(< "$COMMAND_DURATION_FILE") |
| 37 | + command_start_sseconds=${command_start%.*} |
| 38 | + current_time_seconds=${current_time%.*} |
| 39 | + |
| 40 | + command_start_deciseconds=$((10#${command_start#*.})) |
| 41 | + current_time_deciseconds=$((10#${current_time#*.})) |
| 42 | + |
| 43 | + # seconds |
| 44 | + command_duration=$(( current_time_seconds - command_start_sseconds )) |
| 45 | + |
| 46 | + if (( current_time_deciseconds >= command_start_deciseconds )); then |
| 47 | + deciseconds=$(( (current_time_deciseconds - command_start_deciseconds) )) |
| 48 | + else |
| 49 | + ((command_duration-=1)) |
| 50 | + deciseconds=$(( 10 - ( (command_start_deciseconds - current_time_deciseconds) ) )) |
| 51 | + fi |
| 52 | + command rm "$COMMAND_DURATION_FILE" |
| 53 | + else |
| 54 | + command_duration=0 |
| 55 | + fi |
| 56 | + |
| 57 | + if (( command_duration > 0 )); then |
| 58 | + minutes=$(( command_duration / 60 )) |
| 59 | + seconds=$(( command_duration % 60 )) |
| 60 | + fi |
| 61 | + |
| 62 | + if (( minutes > 0 )); then |
| 63 | + printf "%s%s%dm %ds" "$COMMAND_DURATION_ICON" "$COMMAND_DURATION_COLOR" "$minutes" "$seconds" |
| 64 | + elif (( seconds >= COMMAND_DURATION_MIN_SECONDS )); then |
| 65 | + printf "%s%s%d.%01ds" "$COMMAND_DURATION_ICON" "$COMMAND_DURATION_COLOR" "$seconds" "$deciseconds" |
| 66 | + fi |
| 67 | +} |
| 68 | + |
| 69 | +preexec() ( |
| 70 | + _command_duration_pre_exec |
| 71 | +) |
| 72 | + |
| 73 | +preexec_install |
0 commit comments