From 6bd28cd6ae3c7f7e485ee35cc1a3ce7e397dda74 Mon Sep 17 00:00:00 2001 From: ge Date: Sat, 14 May 2022 20:08:16 +0300 Subject: [PATCH] feat: Add common.sh --- src/lib/common.sh | 50 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 src/lib/common.sh diff --git a/src/lib/common.sh b/src/lib/common.sh new file mode 100644 index 0000000..89c4e87 --- /dev/null +++ b/src/lib/common.sh @@ -0,0 +1,50 @@ +#! /usr/bin/env bash + +# common.sh - common functions. +# Copyright (c) 2022 ge +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +log() { + # Logger. Write message to __log_file. + # + # Usage: log [-p] MESSAGE + # + # Can read from STDIN. Removes ANSI escape codes from log message. + # Echo message to STDOUT with '-p' option. + + local message + local print + local log_file + + log_file="$__log_file" + + # If no arguments passed OR '0' descriptor is open, then read from descriptor. + # If no arguments AND '0' descriptor is closed, then 'message' will not be set. + [[ "$#" == 0 || -t 0 ]] || message="$(cat <&0)" + + while (( "$#" )); do + case "$1" in + -p|--print) print=1; shift;; + -) message="$(cat <&0)"; shift "$#";; + *) message="$@"; shift "$#";; + esac + done + + [[ "$print" == 1 ]] && echo "$message" + + while read line; do + printf '[%s] [%s] %s\n' "$(date +'%d %b %Y %H:%M:%S %z')" "$0" "$line" >> "$log_file" + done <<< "$(sed -r 's/\x1B\[(([0-9]+)(;[0-9]+)*)?[m,K,H,f,J]//g' <<< "$message")" +}