#!/usr/bin/env bash # Automatically reloads your tmux configuration files on change. # # Copyright 2021 Maddison Hellstrom , MIT License. set -Eeuo pipefail if [[ ${BASH_VERSINFO[0]} -ge 5 || (${BASH_VERSINFO[0]} -eq 4 && ${BASH_VERSINFO[1]} -ge 4) ]]; then shopt -s inherit_errexit fi function years_from() { local from="$1" to to="${2:-$(date +%Y)}" if [[ "$from" == "$to" ]]; then echo "$from" else echo "$from-$to" fi } declare -g self prog name self="$(realpath -e "${BASH_SOURCE[0]}")" prog="$(basename "$self")" name="${prog%.tmux}" declare -gr version="0.0.1" declare -gr authors=("$(years_from 2021) Maddison Hellstrom ") declare -gr repo_short="b0o/$name" declare -gr repository="https://github.com/$repo_short" declare -gr issues="https://github.com/$repo_short/issues" declare -gr license="MIT" declare -gr license_url="https://mit-license.org" function usage() { cat </dev/null; then echo "$instance_pid" return 0 fi return 1 } function reload() { local -a entrypoints mapfile -t entrypoints < <(get_entrypoints) if [[ ${#entrypoints[@]} -eq 0 ]]; then entrypoints=("$@") fi if msg="$(tmux source-file "${entrypoints[@]}")"; then display_message "Reloaded $( printf '%s\n' "${entrypoints[@]}" | xargs -n1 basename | tr '\n' ',' | sed 's/,$/\n/; s/,/, /g' )" else display_message -d 0 "#[fg=white,bg=red,bold]ERROR: $msg" fi } function onexit() { local -i code=$? local -i entr_pid=$1 display_message "$name exited with code $code" || true if [[ -v entr_pid && $entr_pid -gt 1 ]] && ps "$entr_pid" &>/dev/null; then kill "$entr_pid" || true fi tmux set-option -gu "@$name-pid" & return "$code" } function kill_instance() { local -i instance_pid if instance_pid="$(get_instance)"; then kill "$instance_pid" return $? fi echo "$name -k: kill failed: no instance found" >&2 return 1 } function get_status() { local -i instance_pid if instance_pid="$(get_instance)"; then echo "running: $instance_pid" return 0 fi echo "not running" return 1 } function main() { if ! [[ "${1:-}" =~ ^-[hvfksr]$ ]]; then "$self" -f "$@" &>/dev/null & disown exit $? fi local opt OPTARG local -i OPTIND while getopts "hvfksr:" opt "$@"; do case "$opt" in h) usage return 0 ;; v) usage_version return 0 ;; f) # Silently ignore -f ;; k) kill_instance return ;; s) get_status return ;; r) reload "$OPTARG" return ;; \?) return 1 ;; esac done shift $((OPTIND - 1)) if get_instance &>/dev/null; then return 0 fi command -v entr &>/dev/null || { echo "Command not found: entr" >&2 display_message -d 0 "Failed to start $name: Command not found: entr" return 1 } tmux set-option -g "@$name-pid" $$ # shellcheck disable=2016 entr -np sh -c '"$0" -r "$1"' "$self" /_ <<<"$(printf '%s\n' "$(get_base_configs)" "$(get_user_configs)")" & # shellcheck disable=2064 trap "onexit $!" EXIT wait } main "$@"