Skip to content

Instantly share code, notes, and snippets.

@TitouanT
Last active January 28, 2021 14:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TitouanT/43300fb82c31e3d159b714478f868071 to your computer and use it in GitHub Desktop.
Save TitouanT/43300fb82c31e3d159b714478f868071 to your computer and use it in GitHub Desktop.
A client to send request to a piston instance from the comfort of your terminal. If you send data through stdin then it will be sent along as stdin for your program.
#!/bin/sh
host=https://emkc.org/api/v1/piston
POST=$host/execute
GET=$host/versions
usage() {
echo "$0 [debug] {version OR FILENAME [ARG1 [ARG2 [...]]]}"
echo
echo "\tdebug : Display the json request sent to the api."
echo "\t It has no effect when used with version."
echo "\tversion : Get available languages, their version and aliases from $GET."
echo "\tFILENAME: The file containing the code to be run by piston,"
echo "\t if the file doesn't exist then vim is launched."
echo "\tARGs : Your program will run with those as command line arguments."
exit
}
debug=0
if [ "$1" = "debug" ]
then
debug=1
shift
fi
# if there is no more arguments, exit with usage information
[ $# = '0' ] && usage
# get the available versions for supported lgges.
if [ "$1" = "version" ]
then
curl $GET 2> /dev/null
exit
fi
req=$(mktemp reqXXXX.piston)
stdin=$(mktemp stdinXXXX.piston)
# get stdin if any
tty > /dev/null || dd of=$stdin status=none
# get the lgge from file extension
lgge=$(basename $1)
lgge=${lgge##*.}
# the file containing the source code
code=$1
[ ! -f "$code" ] && vim $code < /dev/tty > /dev/tty
# get the remaining args as a json array
shift
jsonargs="[]"
while [ $# != '0' ]
do
jsonargs=$(echo $jsonargs | jq -cr ". +[\"$1\"]")
shift
done
echo | jq -sc "{\
language: \"$lgge\",\
source: $(jq -Rsc "" $code),\
args: $jsonargs,\
stdin: $(jq -Rsc "" $stdin)\
}" > $req
[ $debug = '1' ] && cat $req
# send the request
curl -d "@$req" -X POST -H "Content-Type: application/json" $POST 2> /dev/null
rm $req
rm $stdin
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment