@@ 1,4 1,8 @@
-#!/usr/bin/env dash
+#!/usr/bin/env sh
+
+err() {
+ printf 'error: %s\n' "$1" >&2
+}
has() {
# check if a command exists
@@ 70,10 74,35 @@ mkbody() {
}
get_field() {
- # get a field from a json string by grepping
+ # get a field from a json string
# $1 - json string
# $2 - field to grep
- printf '%s\n' "$1" | grep -o "\"$2\":\"[^\"]*" | sed "s/\"$2\":\"//"
+ case $1 in
+ *"$2"*);;
+ *) return;;
+ esac
+
+ tmp="${1#*\"$2\":\"}"
+ while [ -n "$tmp" ]; do
+ rest="${tmp#?}"
+ char="${tmp%"$rest"}"
+ tmp="$rest"
+ case $char in
+ '"')
+ break
+ ;;
+ '\')
+ printf '%s' "$char"
+ i=$((i + 1))
+ rest="${tmp#?}"
+ char="${tmp%"$rest"}"
+ tmp="$rest"
+ ;;
+ *);;
+ esac
+ printf '%s' "$char"
+ i=$((i + 1))
+ done
}
process_event() {
@@ 98,8 127,8 @@ stream_events() {
fi
process_event "$event"
done
+ printf '\n'
else
- printf '%s\n' "Error: curl not found"
cleanup
err "curl not found"
exit 1
@@ 119,6 148,21 @@ term() {
trap term INT TERM
main() {
+ case "$1" in
+ -h|--help)
+ printf '%s\n' "Usage: shatgpt [prompt]"
+ exit 0
+ ;;
+ -e|--edit)
+ prompt=$(mktemp)
+ printf '%s' "$*" > $prompt
+ $(editor) "$prompt"
+ prompt="$(mkprompt "$(cat $prompt)")"
+ ;;
+ *)
+ prompt="$(mkprompt "$*")"
+ ;;
+ esac
stream_events "https://api.openai.com/v1/chat/completions" "$(mkbody "$prompt")"
}