2020-12-29 08:38:07 -08:00
|
|
|
#!/usr/bin/env zsh
|
2021-07-29 00:37:35 -07:00
|
|
|
# YES_ZSH
|
2021-07-29 05:44:12 -07:00
|
|
|
# NO_BASH
|
|
|
|
# NO_DASH
|
2021-09-23 06:48:05 -07:00
|
|
|
# NO_ASH
|
2021-07-29 00:37:35 -07:00
|
|
|
|
2021-10-01 12:00:23 -07:00
|
|
|
# works with busybox awk.
|
|
|
|
|
2021-07-30 17:57:08 -07:00
|
|
|
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:
|
|
|
|
### ```
|
2021-07-29 00:37:35 -07:00
|
|
|
local editor=(${=EDITOR})
|
|
|
|
local running=0
|
|
|
|
|
|
|
|
if [ -n "$MSYSTEM" ]; then
|
|
|
|
if ps -f | awk '{print $6}' \
|
|
|
|
| grep -o '[^/]*$' | grep -qFx "${editor[1]}"; then
|
|
|
|
running=1
|
|
|
|
fi
|
|
|
|
elif ps -o comm | grep -qFx "${editor[1]}"; then
|
|
|
|
running=1
|
|
|
|
fi
|
2013-06-28 05:22:14 -07:00
|
|
|
|
2021-07-29 00:37:35 -07:00
|
|
|
if [ $running -eq 1 ]; then
|
|
|
|
printf "%s\n" "${editor[1]} is already running" >&2
|
|
|
|
read -q '?Continue? [y/N] ' _ || { echo; return; }
|
|
|
|
echo
|
|
|
|
fi
|
2019-06-05 20:14:29 -07:00
|
|
|
|
2021-07-29 00:37:35 -07:00
|
|
|
if [ $# -eq 0 ] || [ -n "$MSYSTEM" ]; then
|
|
|
|
$=EDITOR "$@"
|
|
|
|
return
|
2019-06-05 20:14:29 -07:00
|
|
|
fi
|
2021-07-29 00:37:35 -07:00
|
|
|
|
2021-10-01 11:00:09 -07:00
|
|
|
local f= needroot=0
|
2021-07-29 00:37:35 -07:00
|
|
|
for f in "$@"; do
|
|
|
|
# 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
|
|
|
|
local d="$f"
|
|
|
|
while expr index "$d" / >/dev/null; 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
|
2019-06-05 20:14:29 -07:00
|
|
|
done
|
|
|
|
|
2021-07-29 00:37:35 -07:00
|
|
|
if [ $needroot -eq 0 ]; then
|
|
|
|
$=EDITOR "$@"
|
|
|
|
else
|
|
|
|
sudo -e "$@"
|
|
|
|
fi
|
|
|
|
}
|
2013-06-28 05:22:14 -07:00
|
|
|
|
2021-08-02 13:48:46 -07:00
|
|
|
[ -n "${preload+-}" ] || e "$@"
|