docs(usage): add more documentation
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful

This commit is contained in:
Simon Vieille 2023-01-02 08:42:29 +01:00
parent 82cc3737a0
commit 705e2416bc

107
timeout
View file

@ -1,76 +1,101 @@
#!/bin/sh #!/bin/sh
usage() { usage() {
printf "Usage: %s [-t TIMEOUT] [-c COMMAND]\n\n" "$0" printf "Usage: %s [-v] [-h] [-t TIMEOUT] [-c COMMAND]\n\n" "$0"
printf "TIMEOUT and COMMAND can be set as env vars.\n" }
help() {
cat << EOH
SYNOPSIS
$0 [-v] [-h] [-t TIMEOUT] [-c COMMAND]
DESCRIPTION
\`Timeout\` executes a command until the timeout is over.
When the command is finished before the timeout then the exit code is \`0\` else it's \`1\`.
OPTIONS
-h Show this help
-v Display the command output (stderr)
-c COMMAND
The command to execute
\`COMMAND=... $0\` works to.
-t TIMEOUT
The timeout in seconds (default: 10)
\`TIMEOUT=... $0\` works to.
EOH
} }
on_interrupt() { on_interrupt() {
print "Process aborted!\n" print "Process aborted!\n"
exit 130 exit 130
} }
create_script() { create_script() {
printf "#!/bin/sh\n%s\n" "$1" > "$2" printf "#!/bin/sh\n%s\n" "$1" > "$2"
chmod +x "$SCRIPT_FILE" chmod +x "$SCRIPT_FILE"
} }
run_script() { run_script() {
if [ "$2" -eq 0 ]; then if [ "$2" -eq 0 ]; then
"$SCRIPT_FILE" >/dev/null 2>&1 & "$SCRIPT_FILE" >/dev/null 2>&1 &
else else
"$SCRIPT_FILE" >&2 & "$SCRIPT_FILE" >&2 &
fi fi
printf "%d" $! printf "%d" $!
} }
stop_delete_script() { stop_delete_script() {
kill -9 "$1" kill -9 "$1"
rm -f "$2" rm -f "$2"
} }
check_pid() { check_pid() {
PID=$1 PID=$1
LOOP=$2 LOOP=$2
for _ in $(seq 1 "$((LOOP*2))"); do for _ in $(seq 1 "$((LOOP*2))"); do
test -d "/proc/$PID/" && sleep 0.5 || STATUS=0 test -d "/proc/$PID/" && sleep 0.5 || STATUS=0
done done
printf "%d" ${STATUS:-1} printf "%d" ${STATUS:-1}
} }
main() { main() {
while getopts "ht:c:v" option; do while getopts "ht:c:v" option; do
case "${option}" in case "${option}" in
h) usage; exit 0;; h) help; exit 0;;
t) TIMEOUT="$OPTARG";; t) TIMEOUT="$OPTARG";;
c) COMMAND="$OPTARG";; c) COMMAND="$OPTARG";;
v) VERBOSE=1;; v) VERBOSE=1;;
*) usage; exit 1;; *) usage; exit 1;;
esac esac
done done
TIMEOUT="${TIMEOUT:-10}" TIMEOUT="${TIMEOUT:-10}"
VERBOSE="${VERBOSE:-0}" VERBOSE="${VERBOSE:-0}"
if [ -z "$COMMAND" ]; then if [ -z "$COMMAND" ]; then
printf "Command is required!\n" printf "Command is required!\n"
exit 1 exit 1
fi fi
SCRIPT_FILE="$(mktemp)" SCRIPT_FILE="$(mktemp)"
create_script "$COMMAND" "$SCRIPT_FILE" create_script "$COMMAND" "$SCRIPT_FILE"
SCRIPT_PID=$(run_script "$SCRIPT_FILE" "$VERBOSE") SCRIPT_PID=$(run_script "$SCRIPT_FILE" "$VERBOSE")
EXIT_STATUS=$(check_pid "$SCRIPT_PID" "$TIMEOUT") EXIT_STATUS=$(check_pid "$SCRIPT_PID" "$TIMEOUT")
stop_delete_script "$SCRIPT_PID" "$SCRIPT_FILE" stop_delete_script "$SCRIPT_PID" "$SCRIPT_FILE"
exit "$EXIT_STATUS" exit "$EXIT_STATUS"
} }
trap on_interrupt INT trap on_interrupt INT