summaryrefslogtreecommitdiff
path: root/jive.sh
blob: 80789f947438528178af288649e0ec609a81380d (plain)
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#!/bin/sh
# shellcheck disable=1001,1012,2039,1090
# 1001,1012 stop complaints about '\awk' syntax to bypass aliases.
# 2039 stops complaints about array references not being POSIX.
# 1090 stops complaints about sourcing non-constant paths.

__shell="$(\ps -p $$ | \awk 'NR > 1 { sub(/^-/, "", $4); print $4 }')"
__shellname="$(basename "${__shell}")"

case "${__shellname}" in
  bash)
    __jive_root_dir="$(builtin cd "$(\dirname "${BASH_SOURCE[0]}")" && \pwd)"
    ;;
  zsh)
    __jive_root_dir="$(\dirname "$0:A")"
    ;;
  *)
    >&2 \echo "jive is not compatible with your shell (${__shell})"
    \return 1
    ;;
esac

__jive_exe_dir="${__jive_root_dir}/exe"
__jive_lib_dir="${__jive_root_dir}/lib"
__jive_script="${__jive_root_dir}/jive.sh"

__mtime_of_jive_script="$(\date -r "${__jive_script}" +%s)"
__jive_auto_reload() {
  local current_mtime
  current_mtime="$(\date -r "${__jive_script}" +%s)"

  if [[ "${current_mtime}" != "${__mtime_of_jive_script}" ]]; then
    echo "Reloading... ${__jive_script}"
    . "${__jive_script}"
  fi
}

__jive_exec() {
  /usr/bin/env -S ruby -I "${__jive_lib_dir}" "${__jive_exe_dir}/jive" "$@"
}

__jive_open_pipe() {
  local tmpfile
  tmpfile="$(\mktemp -u)"

  exec 42>"${tmpfile}" # Open the tempfile for writing on FD 42.
  exec 8<"${tmpfile}" # Open the tempfile for reading on FD 8.
  \rm -f "${tmpfile}" # Unlink the tempfile. (we've already opened it).
}

__jive_execute_task() {
  local task=$1

  case "${task}" in
    cd:*)
      # shellcheck disable=SC2164
      cd "${task//cd:/}"
      ;;
    ctags:*)
      # shellcheck disable=SC2164
      ctags -R "${task//ctags:/}"
      ;;
    setenv:*)
      export "${task//setenv:/}"
      ;;
    *)
      echo "Woof! ${task}"
      ;;
  esac
}

__jive_flush_tasks() {
  local task
  while \read -r task; do
    __jive_execute_task "${task}"
  done <&8

  __jive_close_pipe
}

__jive_close_pipe() {
  exec 8<&- # close FD 8.
  exec 42<&- # close FD 42.
}

jive() {
  __jive_auto_reload
  __jive_open_pipe
  __jive_exec "$@"
  __jive_flush_tasks
}