summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authortaro <taro>2021-09-24 18:22:27 +0000
committertaro <taro>2021-09-24 18:22:27 +0000
commitbe7c0f518b0feafcd18df75e3ab148f5f00c8f14 (patch)
treeda1cbef8f251f55f934e38180d67780e980bd311
parent11483560ba54a5c9c87accb0048596889ef01f46 (diff)
downloadgab-be7c0f518b0feafcd18df75e3ab148f5f00c8f14.tar.gz
Se realizaron las siguientes cosas
* No dependencia de awk * mejora de documentación * posibilidad de debugging * un poco mejorada la cuestión con el chequeo de errores * variables con valores por defecto * etc.
-rwxr-xr-xgab160
1 files changed, 123 insertions, 37 deletions
diff --git a/gab b/gab
index 5a0876d..30c103a 100755
--- a/gab
+++ b/gab
@@ -1,66 +1,152 @@
#!/usr/local/bin/bash
+
# Gab es un cliente alternativo al programa de chat en colorfield.space
-# Reemplace la variable $file_path con la ruta a tu historial de chat
+# 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 >"
-# otros esquemas y formatos requerirán una modificación del script de awk
-# que se encuentra en las líneas 40 y 46
# # # # # #->
-help_text=$'GAB - Una simple interfaz de chat\n\nsyntax: gab [bandera] [valor]\n\nbandera valor\n---------- ---------------\n-h, --help ninguno\n-m, --msg Mensaje entre comillas a enviar al chat\n-l, --log Un número entero con la cantidad de filas que quieres ver, por defecto 5'
+HELP_TEXT=$(cat << EOF
+GAB - Una simple interfaz de chat
-file_path=/var/gab/chatlog.txt
-title="GAB v1.0"
-last_date="Último mensaje: $(date -r $(stat -f %m $file_path))"
+syntax: gab [bandera] [valor]
-if [ -z "$1" ]
+bandera valor
+---------- ---------------
+-h, --help ninguno
+-m, --msg Mensaje entre comillas a enviar al chat\n
+-l, --log Un número entero con la cantidad de filas que quieres ver, por defecto 5
+EOF
+)
+
+
+GAB_DEBUG=0
+
+[[ $GAB_DEBUG -eq 0 ]] && GAB_LOG=/var/gab/chatlog.txt || GAB_LOG="$HOME/chatlog.txt"
+
+TITLE="GAB v1.1 'Mirá mamá, sin comillas!!'"
+
+LAST_MSG_DATE=$(date -r $(stat -f %m $GAB_LOG))
+
+SEPARATOR='>'
+
+# chequeamos si se puede escribir en el chatlog
+if [[ ! -w "$GAB_LOG" ]]
then
- echo $title
- echo $last_date
+ echo "No es posible escribir en $GAB_LOG"
+ exit 1
+fi
+
+# https://github.com/dylanaraps/pure-sh-bible#trim-leading-and-trailing-white-space-from-string
+trim_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 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"
+}
+
+# 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(){
+ while IFS="$SEPARATOR" read -r user message; do
+ printf '\033[7m\033[1m%s\033[0m %s\n' $(trim_string "$user") "$message"
+ printf '\t---\n'
+ done
+}
+
+
+# Imprime las últimas n líneas del log de mensajes
+# parámetro 1 es la cantidad de líneas a leer
+# parámetro 2 es el path del archivo a leer
+print_last_n_lines() {
+ tail -n "$1" "$GAB_LOG" | output_beautiful_messages
+}
+
+
+# Imprime cabecera
+print_header() {
+ echo $TITLE
+ echo "Último mensaje: $LAST_MSG_DATE"
echo ""
- tail -n 5 $file_path | awk '{out="\033[7m " $1 " \033[0m "; for (i=3; i<=NF; i++) {out=out" "$i}; print out ORS "- - -"}'
+}
+
+
+# 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
+ else
+ echo "Error agregando mensaje al chatlog"
+ exit 1
+ fi
+}
+
+# Imprime los últimos mensajes
+# Por defecto imprime 5
+output_last_messages() {
+ # configuramos por defecto 5 líneas
+ lines=${1:-5}
+
+ print_header
+ print_last_n_lines "$lines"
+}
+
+
+
+# --- MAIN ---
+if [ -z "$1" ]
+then
+ output_last_messages
else
case "$1" in
-m | --msg)
if [ -z "$2" ]
then
- echo "Debe incluir un mensaje entre comillas dobles"
+ echo "Debe incluir un mensaje"
exit 1
else
- msg=$(echo $2 | sed -e 's/\r$//g')
- echo "$USER > $msg" >> $file_path
- if [ $? -eq 0 ]
- then
- echo "Mensaje agregado exitosamente al chatlog"
- exit 0
- else
- echo "Error agregando mensaje al chatlog"
- exit 1
- fi
- fi;;
+ add_message ${@:2}
+ fi
+ ;;
-l | --log)
if [ -z "$2" ]
then
- echo $title
- echo $last_date
- echo ""
- tail -n 5 $file_path | awk '{out="\033[7m " $1 " \033[0m "; for (i=3; i<=NF; i++) {out=out" "$i}; print out ORS "- - -"}'
+ output_last_messages
elif [[ "$2" =~ ^[0-9]+$ ]]
then
- echo $title
- echo $last_date
- echo ""
- tail -n $2 $file_path | awk '{out="\033[7m " $1 " \033[0m "; for (i=3; i<=NF; i++) {out=out" "$i}; print out ORS "- - -"}'
+ output_last_messages $2
else
- echo "Invalido: el valor debe ser entero"
+ echo "Error: el valor debe ser un número entero"
exit 1
- fi;;
+ fi
+ ;;
-h | --help)
- echo "$help_text"
- exit 0;;
+ echo "$HELP_TEXT"
+ exit 0
+ ;;
*)
- echo "Unknown flag $1"
- exit 1;;
+ echo "Opción desconocida $1"
+ echo "$HELP_TEXT"
+ exit 1
+ ;;
esac
fi
Un proyecto texto-plano.xyz