~kmaasrud/shatgpt

58ebc41644d474f954bbebf6d485183c68beb933 — Knut Magnus Aasrud 1 year, 6 months ago ed0f4b9
make better arg parser
1 files changed, 51 insertions(+), 16 deletions(-)

M shatgpt
M shatgpt => shatgpt +51 -16
@@ 87,7 87,7 @@ mkbody() {
get_field() {
    # get a field from a json string
    # $1 - json string
    # $2 - field to grep
    # $2 - field to get
    case $1 in
      *"$2"*);;
      *) return;;


@@ 118,6 118,7 @@ get_field() {

process_event() {
    # process each streaming event
    # $1 - event
    delta=$(get_field "$1" content)
    if [ -n "$delta" ]; then
	printf '%b' "$delta"


@@ 158,22 159,56 @@ 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 "$*")"
        ;;
show_help() {
  printf '%s\n' "usage: $0 [-h|--help] [-e|--edit] [-s|--shell] prompt"
  printf '%s\n' "options:"
  printf '%s\n' "  -h, --help     show this help message and exit."
  printf '%s\n' "  -e, --edit     open an editor to enter the prompt interactively."
  printf '%s\n' "  -s, --shell    output only shell commands to the terminal."
}

parse_args() {
  while [ $# -gt 0 ]; do
    case $1 in
      -h|--help)
        show_help
        term
      ;;
      -e|--edit)
        editor_mode=true
        shift
      ;;
      -s|--shell)
        shell_mode=true
        shift
      ;;
      *)
        break
      ;;
    esac
  done

  prompt="$*"
}

main() {
    editor_mode=false
    shell_mode=false

    parse_args $*

    if [ $editor_mode = true ]; then
      tmp=$(mktemp)
      printf '%s' "$prompt" > $tmp
      $(editor) "$tmp"
      prompt="$(cat $tmp)"
    fi

    if [ $shell_mode = true ]; then
      prompt="$(mkprompt_shell "$prompt")"
    else
      prompt="$(mkprompt_default "$prompt")"
    fi

    stream_events "https://api.openai.com/v1/chat/completions" "$(mkbody "$prompt")"
}