Files

39 lines
1.7 KiB
Bash

#!/bin/bash
# A simple helper tool to create valid Gophermap info lines from the standard input
# Features:
# - implemented in pure Bash and doesn't depend on wc (that can have a non-standard implementation)
# - aligns the spaces according to the longest line so that the output would look nice in plaintext too
# - doesn't do any heuristics but allows you to specify the amount of leading and trailing spaces (0 by default)
# - allows visual selector/host placeholder customization (';' by default)
# - converts LF-only line endings to CRLF (as required by the RFC) without unix2dos dependency
# - only outputs to stdout (but you can redirect it into a file if you need to)
#
# Usage: cat [file] | gopherinfo.sh [leading_spaces] [trailing_spaces] [placeholder_char]
#
# Created by Luxferre in 2023, released into public domain
LSPACES="$1"
TSPACES="$2"
DELIM="$3"
TAB=$'\t'
CRLF=$'\r\n'
[[ -z "$LSPACES" ]] && LSPACES=0
[[ -z "$TSPACES" ]] && TSPACES=0
[[ -z "$DELIM" ]] && DELIM=';'
readarray -t LINES -d $'\n' # read the input line array (split by LF)
LINECOUNT=${#LINES[@]} # get the array length
MAXLEN=0 # initialize the maximum length variable
for ((idx=0;idx<LINECOUNT;idx++)); do # first pass to filter out inconsistent newlines and to detect maximum length
line="${LINES[$idx]%%$'\r'}" # remove a trailing CR if it is there
llen=${#line} # get the line length
(( llen > MAXLEN )) && MAXLEN=$llen # update the current maximum length
LINES[$idx]="$line" # update the element by index
done
fmtstr="%-$(( LSPACES + 1 ))s%-$(( MAXLEN + TSPACES ))s${TAB}%s${TAB}%s${TAB}0${CRLF}" # params: i, line, DELIM, DELIM
for line in "${LINES[@]}"; do # second pass to actually output the formatted lines
printf "$fmtstr" 'i' "$line" "$DELIM" "$DELIM"
done