1
0
Fork 0
dotfiles/.config/zsh/functions/readwwwlog

72 lines
2.2 KiB
Bash
Executable File

#!/usr/bin/env zsh
# Open log files from paste services in a terminal. If the URL doesn't seem to
# be plain text, open in ${default_cmd} instead
setopt LOCAL_OPTIONS ERR_RETURN NO_UNSET PIPE_FAIL
zmodload zsh/zutil
local -a o_help=()
zparseopts -D -K -- h=o_help
if [[ ${#o_help} -ne 0 || ! -v 1 ]]; then
local ret=$(( ${#o_help} ^ 1 ))
print -u $(( 1 + ${ret} )) "usage: ${0} [-h] <URL> …"
return ${ret}
fi
local -a urls=(${@})
local default_cmd="firefox"
local termopts=""
for url in ${urls}; do
if [[ ${url} =~ 'dpaste\.com' && ! ${url[-4,-1]} == ".txt" ]]; then
url+=".txt"
elif [[ ${url} =~ 'pastebin\.com' && ! ${url} =~ '/raw/' ]]; then
url="https://pastebin.com/raw/${url##*/}"
elif [[ ${url} =~ 'irccloud\.com' && ! ${url} =~ '/raw/' ]]; then
local id=${${(@s:/:)url}[4]}
url="https://www.irccloud.com/pastebin/raw/${id}"
elif [[ ${url} =~ 'bpa\.st' && ! ${url} =~ '/download-archive/' ]]; then
local id=${url##*/}
url="https://bpa.st/download-archive/${id}"
fi
if [[ ${TERMINAL} =~ "alacritty|xfce4-terminal" ]]; then
termopts="--title=${url}"
fi
local curl="$(curl --silent --location --head ${url})"
local -a headers=(${(ps:\r\n:)curl})
local file="$(mktemp --suffix='.readwwwlog')"
local -a cmd=(less +1 --LINE-NUMBERS --ignore-case \
--pattern='(error|fail):')
if [[ -o NO_INTERACTIVE ]]; then
cmd=(${TERMINAL} ${termopts} -e ${cmd})
fi
if [[ ${headers[(I)*text/plain]} -ne 0 ]] || \
[[ ${headers[(I)*HTTP/1.1 405*]} -ne 0 ]]; then # No HEAD allowed
sleep 1 # dpaste.com workaround
curl --silent --location --output ${file} ${url}
${cmd} ${file}
rm ${file}
elif [[ ${headers[(I)*application/zip]} -ne 0 ]]; then
rm ${file}
local dir=${file}
mkdir ${dir}
file=${dir}/archive.zip
curl --silent --location --output ${file} ${url}
unzip -qd ${dir} ${file}
for txt in ${dir}/*; do
if [[ ${txt} != "${dir}/archive.zip" ]]; then
${cmd} ${txt}
fi
done
rm -r ${dir}
else
${default_cmd} ${url}
fi
done