Skip to content

Instantly share code, notes, and snippets.

@artem-bez
Last active October 29, 2015 08:20
Show Gist options
  • Save artem-bez/ce27e856a951a4026130 to your computer and use it in GitHub Desktop.
Save artem-bez/ce27e856a951a4026130 to your computer and use it in GitHub Desktop.
Local pastebin service to quickly share some code snippet with other people on your network. To share what is in your clipboard use $ pst.sh [lang]
#!/bin/bash
set -o nounset
set -o errexit
TMP_DIR_PREFIX='pst'
TMP_FILE_SUFFIX='.html'
TMPDIR=${TMPDIR:-'/tmp'}
DEFAULT_LEXER='python' # change this to your preferred language
DEFAULT_PORT='8000'
check_deps() {
# 2>- is eqvivalent to 2>/dev/null
if hash xsel 2>-; then
get_clipboard() { xsel -b; }
elif hash xclip 2>-; then
get_clipboard() { xclip -o -selection clipboard; }
else
echo 'xsel or xclip is required but not found. Aborting.' >&2
exit 1
fi
if hash python3 2>-; then
serve_http() { python3 -m http.server; }
elif hash python2 2>-; then
serve_http() { python2 -m SimpleHTTPServer; }
else
echo 'python3 or python2 is required but not found. Aborting.' >&2
exit 1
fi
}
create_pst_dir() {
mktemp --tmpdir="$1" --directory ${TMP_DIR_PREFIX}-XXX
}
create_pst_file() {
mktemp --tmpdir="$1" XXX${TMP_FILE_SUFFIX}
}
get_or_create_pst_dir() {
local dir
for d in "${TMPDIR}/${TMP_DIR_PREFIX}-"*; do
[[ -d ${d} ]] && dir=$d && break
done
echo "${dir:-$(create_pst_dir ${TMPDIR})}"
}
highlight_code() {
if ! curl --data "lexer=${1}" --data-urlencode "code=${2}" \
--silent -S --fail http://hilite.me/api; then
echo "Probably unknown lexer '${1}'" >&2
echo "For available lexers check http://pygments.org/docs/lexers/" >&2
exit 1
fi
}
main() {
check_deps
local pst_dir=$(get_or_create_pst_dir)
local lexer=${1:-$DEFAULT_LEXER}
local pst_path=$(create_pst_file "$pst_dir")
local pst_name=${pst_path##*/}
local code=$(get_clipboard)
highlight_code "$lexer" "$code" > $pst_path
local ipaddrs=$(
ip -o -4 addr show | \
awk '$3=="inet" && $4 !~ /^127/ {split($4,inet,"/"); print inet[1] }'
)
for ip in $ipaddrs; do
echo "Serving paste at http://$ip:${DEFAULT_PORT}/${pst_name}"
done
cd "$pst_dir"
serve_http "${DEFAULT_PORT}"
}
main "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment