Last active
October 24, 2021 09:32
-
-
Save dhamidi/e4c471f0241f5cfe509ada352be27f8c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
[[ -v REPL_FILES ]] || declare -a REPL_FILES=() | |
[[ -v REPL_CHECKSUM ]] || declare REPL_CHECKSUM | |
repl.install() { | |
local command | |
declare -ga PROMPT_COMMAND | |
for command in "${PROMPT_COMMAND[@]}"; do | |
if [[ "$command" == "repl.load_if_changed" ]]; then | |
return | |
fi | |
done | |
PROMPT_COMMAND+=(repl.load_if_changed) | |
repl.install_prompt | |
} | |
repl.watch() { | |
local f r | |
for f in "$@"; do | |
for r in "${REPL_FILES[@]}"; do | |
if [[ "$r" == "$f" ]]; then | |
continue 2 | |
fi | |
done | |
REPL_FILES+=("$f") | |
printf "repl.watch: %s\n" "$f" >&2 | |
repl.load "$f" | |
done | |
REPL_CHECKSUM=$(repl.checksum) | |
} | |
repl.checksum() { | |
if [[ "${#REPL_FILES[@]}" -eq 0 ]]; then | |
return | |
fi | |
sha1sum "${REPL_FILES[@]}" 2>/dev/null | |
} | |
repl.parse_checksum() { | |
local sha1 filename | |
local -n destination_dict="$1" | |
while read sha1 filename; do | |
[[ -z "$filename" ]] && continue | |
destination_dict["$filename"]="$sha1" | |
done | |
} | |
repl.load() { | |
printf "repl.load: %s\n" "$1" >&2 | |
source "$1" | |
} | |
repl.load_if_changed() { | |
local filename new_checksum | |
local -A old new | |
new_checksum=$(repl.checksum) | |
repl.parse_checksum old <<<"${REPL_CHECKSUM}" | |
repl.parse_checksum new <<<"$new_checksum" | |
for filename in "${!new[@]}"; do | |
if [[ "${new[$filename]}" != "${old[$filename]:-}" ]]; then | |
repl.load "$filename" | |
fi | |
done | |
REPL_CHECKSUM="$new_checksum" | |
} | |
repl.install_prompt() { | |
if [[ "$PS1" =~ repl: ]]; then | |
return | |
fi | |
PS1="\[repl:\$(repl.prompt_info)\] $PS1" | |
} | |
repl.prompt_info() { | |
local IFS=, | |
printf '[%s]' "${REPL_FILES[*]}" | |
} | |
repl.enter() { | |
bash --rcfile <(printf "%s\n" \ | |
"$(< $HOME/.bashrc)" \ | |
'source repl.sh' \ | |
'repl.install' \ | |
) -i | |
} | |
case ${0##*/} in | |
repl.sh) repl.enter;; | |
-bash) repl.install;; | |
esac |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment