diff options
author | taro <taro> | 2022-05-30 18:30:15 +0000 |
---|---|---|
committer | taro <taro> | 2022-05-30 18:30:15 +0000 |
commit | 6822af82b8830ebe387a293c85d5bd35a90085ba (patch) | |
tree | ec7abc48a7f1bbe43849a4f8adc96a7d21e56a02 | |
parent | 529337424bdef90122e592edb64625c10aa0491c (diff) | |
download | gab-6822af82b8830ebe387a293c85d5bd35a90085ba.tar.gz |
Mejorado el formato en pantalla y la muestra de mensajes en gral
-rwxr-xr-x | gab | 171 |
1 files changed, 98 insertions, 73 deletions
@@ -1,11 +1,12 @@ -#!/usr/local/bin/bash +#!/usr/bin/env bash # Gab es un cliente alternativo al programa de chat en colorfield.space # Reemplace la variable $GAB_FILE con la ruta a su historial de chat # Se asume que cada línea de chat comienza con: "user_name >" # # # # # #-> -HELP_TEXT=$(cat << EOF +HELP_TEXT=$( + cat <<EOF GAB - Una simple interfaz de chat syntax: gab [bandera] [valor] @@ -18,54 +19,79 @@ bandera valor EOF ) +set -o errexit +set -o errtrace +set -o pipefail GAB_DEBUG=0 [[ $GAB_DEBUG -eq 0 ]] && GAB_LOG=/var/gab/chatlog.txt || GAB_LOG="$HOME/chatlog.txt" -TITLE="GAB v1.2 'Ese formato sí se puede ver!!'" +TITLE="GAB v1.3 'Qué elegancia la de Francia!!'" LAST_MSG_DATE=$(date -r $(stat -f %m $GAB_LOG)) SEPARATOR='>' +color_red='\033[31m' + +term_reset='\033[0m' +term_bold='\033[1m' +term_dim='\033[2m' +term_italic='\033[3m' +term_reverse='\033[7m' + +# Muestra un mensaje de error (se puede pasar por parámetro opcionalmente) +error() { + local msg=${1:-'Ha ocurrido un error'.} + echo -e "${term_bold}${color_red}ERROR: ${term_reset}${msg}" >&2 +} + +# Imprime un mensaje y termina la ejecución del script devolviendo un nro de +# error, por defecto -1 +#Parámetros: mensaje y nro de error +die() { + error $1 + exit ${2:-1} +} + +# Muestra un mensaje al usuario y termina el programa en paz +info() { + echo $1 + exit 0 +} + # chequeamos si se puede escribir en el chatlog -if [[ ! -w "$GAB_LOG" ]] -then - echo "No es posible escribir en $GAB_LOG" - exit 1 +if [[ ! -w $GAB_LOG ]]; then + die "No es posible escribir en $GAB_LOG" 1 fi - # https://github.com/dylanaraps/pure-sh-bible#trim-leading-and-trailing-white-space-from-string trim_string() { - # Usage: trim_string " example string " + # Usage: trim_string " example string " - # Remove all leading white-space. - # '${1%%[![:space:]]*}': Strip everything but leading white-space. - # '${1#${XXX}}': Remove the white-space from the start of the string. - trim=${1#${1%%[![:space:]]*}} + # Remove all leading white-space. + # '${1%%[![:space:]]*}': Strip everything but leading white-space. + # '${1#${XXX}}': Remove the white-space from the start of the string. + trim=${1#${1%%[![:space:]]*}} - # Remove all trailing white-space. - # '${trim##*[![:space:]]}': Strip everything but trailing white-space. - # '${trim%${XXX}}': Remove the white-space from the end of the string. - trim=${trim%${trim##*[![:space:]]}} + # Remove all trailing white-space. + # '${trim##*[![:space:]]}': Strip everything but trailing white-space. + # '${trim%${XXX}}': Remove the white-space from the end of the string. + trim=${trim%${trim##*[![:space:]]}} - printf '%s\n' "$trim" + printf '%s\n' "$trim" } - # Acá está la función que formatea las líneas y las imprime por pantalla # todas las cuestiones relacionadas con modificación de apariencia de la salida # de los mensajes debería ir por acá # https://github.com/dylanaraps/pure-sh-bible#parsing-a-keyval-file -output_beautiful_messages(){ - last_user='' - COLUMNS=$( tput cols ) - width=$(echo "$COLUMNS * 0.85" | bc | cut -d'.' -f1) +output_beautiful_messages() { + local last_user='' + local width=$(calculate_width) while IFS="$SEPARATOR" read -r user message; do - if [[ "$last_user" != "$user" ]] - then + if [[ $last_user != "$user" ]]; then last_user="$user" print_username "$user" fi @@ -73,18 +99,33 @@ output_beautiful_messages(){ done } - - -print_username(){ - printf '\033[7m\033[1m %s\033[0m\n' "$1" +# Toma el ancho de la terminal en columnas y le calcula un porcentaje a usar +# el porcentaje es 90% +# Devuelve la cantidad de columnas a usar +# por defecto 72 si no dispone de tput(1) +calculate_width() { + if ! type -p tput &>/dev/null; then + echo 72 + else + local COLUMNS=$(tput cols) + local width=$((COLUMNS * 9 / 10)) + echo "$width" + fi } - -print_message(){ - echo " $1" | fmt $2 +# Imprime el nombre de usuario con todo el style +# Parámetros: nombre y opcionalmente un mensaje para poner al lado +# por defecto es 'dice:' +print_username() { + printf "${term_reverse}${term_bold} %s ${term_reset}" $1 + printf "${term_dim}${term_italic} %s ${term_reset}\n" ${2:-'dice:'} } - +# Imprime un mensaje indentado y adaptado al ancho de columnas dado +# Parámetros: mensaje y ancho +print_message() { + printf '\t%s' "$1" | fmt $2 +} # Imprime las últimas n líneas del log de mensajes # parámetro 1 es la cantidad de líneas a leer @@ -93,7 +134,6 @@ print_last_n_lines() { tail -n "$1" "$GAB_LOG" | output_beautiful_messages } - # Imprime cabecera print_header() { echo $TITLE @@ -101,25 +141,20 @@ print_header() { echo "" } - # Agrega un mensaje al final del log de mensajes # Primer parámetro: el mensaje add_message() { IFS=' ' # necesario para $* msg=$(trim_string "$*") - echo "$USER $SEPARATOR $msg" >> "$GAB_LOG" - if [ $? -eq 0 ] - then - echo "Mensaje agregado exitosamente al chatlog" - exit 0 + echo "$USER $SEPARATOR $msg" >>"$GAB_LOG" + if [ $? -eq 0 ]; then + info "Mensaje agregado exitosamente al chatlog" else - echo "Error agregando mensaje al chatlog" - exit 1 + die "No se pudo agregar mensaje al chatlog" 1 fi } - # Imprime los últimos mensajes # Por defecto imprime 5 output_last_messages() { @@ -130,43 +165,33 @@ output_last_messages() { print_last_n_lines "$lines" } - - # --- MAIN --- -if [ -z "$1" ] -then +if [ -z "$1" ]; then output_last_messages else case "$1" in - -m | --msg) - if [ -z "$2" ] - then - echo "Debe incluir un mensaje" - exit 1 - else - add_message ${@:2} - fi + -m | --msg) + if [ -z "$2" ]; then + die "Debe incluir un mensaje" 1 + else + add_message ${@:2} + fi ;; - -l | --log) - if [ -z "$2" ] - then - output_last_messages - elif [[ "$2" =~ ^[0-9]+$ ]] - then - output_last_messages $2 - else - echo "Error: el valor debe ser un número entero" - exit 1 - fi + -l | --log) + if [ -z "$2" ]; then + output_last_messages + elif [[ $2 =~ ^[0-9]+$ ]]; then + output_last_messages $2 + else + die "El valor debe ser un número entero" 1 + fi ;; - -h | --help) - echo "$HELP_TEXT" - exit 0 + -h | --help) + info "$HELP_TEXT" ;; - *) - echo "Opción desconocida $1" - echo "$HELP_TEXT" - exit 1 + *) + echo "$HELP_TEXT" + die "Opción desconocida $1" 1 ;; esac fi |