Skip to content

Instantly share code, notes, and snippets.

@mverleg
Created October 26, 2019 21:34
Show Gist options
  • Save mverleg/6b28a0c3e597575567912a0a72c3bf82 to your computer and use it in GitHub Desktop.
Save mverleg/6b28a0c3e597575567912a0a72c3bf82 to your computer and use it in GitHub Desktop.
Bash wrapper for Runner, a cool tool to run Rust snippets, adding stdin, caching and standard flags https://github.com/stevedonovan/runner
function rsr() {(
##
## Use 'runner' on a string instead of a file.
##
## If code is on stdin, all arguments are passed on. Otherwise,
## arg1: the string to run
## arg2+: passed on to the executable
##
## Examples:
## rsr 'println!("{}", "hi");' my_arg
## rsr my_arg <<< 'println!("{}", "hi");'
## echo 'println!("{}", "hi");' | rsr my_arg
##
set -e # fail if a command fails
set -E # technical change so traps work with -E
set -o pipefail # also include intermediate commands in -e
if [[ -p /dev/stdin ]]
then
# stdin is coming from a pipe
input=$(cat -)
args="$@"
elif [[ -t 0 ]]
then
# code is coming from argument
input="$1"
args="${@:2}"
else
# stdin is coming from redirect
input=$(cat -)
args="$@"
fi
fdir="$HOME/.cache/runr"
fbasename="r$(sha1sum --text <<< "$input $(runner --crates)" | cut -c1-28)"
fname="${fbasename}.rs"
srcpth="$fdir/$fname"
binpth="$fdir/$fbasename"
cargopth="/home/$USER/.cargo/bin/$fbasename"
mkdir -m700 -p "$fdir"
if [[ ! -e "$binpth" ]]
then
printf "$input" > "$srcpth"
#prefix_comment="$(printf '// cached on %s as %s\n\n;' "$(date)" "$fname")"
runner --no-simplify --static --optimize "$srcpth" -- "$args"
else
"$binpth" "$args"
fi
)}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment