~tardypad/dotfiles

ref: 00c0c349a1b8960152233f11caa9ea1a40e395a3 dotfiles/files/scripts/shell/http-env -rwxr-xr-x 1.3 KiB
00c0c349 — Damien Tardy-Panis Add presentation mode to mako to hide notifications 4 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#!/bin/sh

init_variables() {
  COMMAND=${0##*/}

  ENV_DIR_PATH="${XDG_DATA_HOME:-$HOME/.local/share}/env/http"

  HTTP_OPTIONS=
  ENV_ID=
  REQUEST_METHOD=
  REQUEST_PATH=
  REQUEST_ITEMS=

  ENV_PATH=
}

parse_command_line() {
  ENV_ID="$1"
  REQUEST_METHOD="$2"
  REQUEST_PATH="$3"
  shift 3 2> /dev/null

  while [ "$#" -gt 0 ] && [ "$1" != '--' ]; do
    REQUEST_ITEMS="${REQUEST_ITEMS} '$1'"
    shift
  done

  shift 2> /dev/null
  HTTP_OPTIONS="$*"
}

validate_command_line() {
  if [ -z "${ENV_ID}" ]; then
    exit_error 'missing environment identifier'
  fi

  if [ -z "${REQUEST_METHOD}" ]; then
    exit_error 'missing request method'
  fi

  if [ -z "${REQUEST_PATH}" ]; then
    exit_error 'missing request path'
  fi

  ENV_PATH="${ENV_DIR_PATH}/${ENV_ID}"

  if [ ! -f "${ENV_PATH}" ]; then
    exit_error 'invalid environment'
  fi
}

exit_error() {
  [ -z "$1" ] || echo "${COMMAND}: $1"
  exit 1
} >&2

run_http() {
  URL="$( head -n 1 "${ENV_PATH}" )/${REQUEST_PATH}"

  OPTIONS=$( grep '^-' "${ENV_PATH}" | tr '\n' ' ' )
  OPTIONS="${OPTIONS} ${HTTP_OPTIONS}"

  ITEMS=$( tail -n +2 "${ENV_PATH}" | grep -v '^-' | tr '\n' ' ' )
  ITEMS="${ITEMS} ${REQUEST_ITEMS}"

  eval http "${OPTIONS}" "${REQUEST_METHOD}" "${URL}" "${ITEMS}"
}

init_variables
parse_command_line "$@"
validate_command_line

run_http