1
0
Fork 0
mirror of https://github.com/notwa/rc synced 2024-07-01 03:07:13 -07:00
rc/sh/e
Connor Olding d2c686123e rewrite e, fixing bugs and improving compatibility
this also adds a `running` command that isn't quite finished.
2021-10-11 15:12:59 -07:00

69 lines
1.9 KiB
Bash
Executable File

#!/usr/bin/env sh
# YES_ZSH
# YES_BASH
# YES_DASH
# YES_ASH
# YES_BB_AWK
e() { ### @-
### wrap around `$EDITOR` to run it as root if necessary.
### this still needs some work to detect root-owned directories.
###
### ```
### $ e /etc/sudoers
### [sudo] password for notwa:
### ```
[ -z "$ZSH_OPTIONS" ] || setopt local_options sh_word_split
local f= d= running= editor= needroot=0
editor="${EDITOR%% *}"
(running pid cmd | while read -r pid cmd; do
if [ "$cmd" = "$editor" ]; then
printf "%s (%s)\n" "$editor is already running" "$pid" >&2
confirm
exit
fi
done) || return
for f in "$@"; do
f="$(readlink -f "$f")" || continue
[ -z "$MSYSTEM" ] || f="$(cygpath -u "$f")" || continue
# easy: file exists, we have write permissions
[ -w "$f" ] && continue
# easy: file exists, but no write permissions
[ -e "$f" ] && { needroot=1; break; }
# hard: file may be in a directory that we can't inspect
d="$f"
while [ "${d%/*}" != "$d" ]; do
d="${d%/*}"
# NOTE: this gets weird with the root directory, not sure how to handle
[ -e "$d" ] && [ ! -w "$d" ] && { needroot=1 && break; }
done
[ $needroot -eq 1 ] && break
# easy: file just doesn't exist
done
if [ $needroot -eq 1 ] && [ -n "$MSYSTEM" ]; then
# this pretty much never happens, because permissions are so busted, but...
printf "NOTE: you need root permissions, but this is Windows." >&2
printf " this probably isn't going to work." >&2
pause
$EDITOR "$@"
elif [ $needroot -eq 0 ]; then
$EDITOR "$@"
else
sudo -e "$@"
fi
}
[ -n "${preload+-}" ] || . ~/sh/preload || exit 2
eval ${preload:-preload} running confirm pause
[ -n "${preload+-}" ] || e "$@"