diff --git a/.bin/.e b/.bin/.e index 3f31313..2e15569 100755 --- a/.bin/.e +++ b/.bin/.e @@ -13,6 +13,7 @@ declare -A mapper=( ["git"]="$HOME/.config/git/config" ["git-ignore"]="$HOME/.config/git/ignore" ["home-manager"]="$HOME/.config/home-manager/home.nix" + ["hyprland"]="$HOME/.config/hypr/hyprland.conf" ["nvim"]="$HOME/.config/nvim/" ["nvim.packer"]="$HOME/.config/nvim/lua/plugins.lua" ["polybar"]="$HOME/.config/polybar" diff --git a/.bin/edit b/.bin/edit index 4457ba9..9b623f9 100755 --- a/.bin/edit +++ b/.bin/edit @@ -2,31 +2,89 @@ set -e -edit_directory="$HOME/.cache/edit/" +edit_dir_base="$HOME/.cache/edit/" -filehash=$(readlink -fn "$1" | md5sum | awk '{ print $1 }') -filedirectory="$edit_directory/$filehash/" +_pre_checks() { + if [ -z "$EDITOR" ]; then + echo "EDITOR is not set" + exit 1 + fi +} -mkdir -p "$filedirectory" +_pre_checks_file() { + if [ -z "$1" ]; then + echo "No file specified" + exit 1 + fi + if sudo test -d "$1"; then + echo "Cannot edit directory" + exit 1 + fi +} -basename=$(basename "$1") -filepath=$(realpath -s "$filedirectory/$basename") +_get_edit_directory() { + target_dir=$(dirname "$1") + edit_dir_sub=$(readlink -fn "$target_dir" | md5sum | awk '{ print $1 }') -user=$(id -un) -group=$(id -gn) + edit_directory="$edit_dir_base/$edit_dir_sub/" + echo "$edit_directory" +} -echo "Editing $1 in $filepath as $user:$group" +_get_edit_file() { + target=$(readlink -fn "$1") + target_name=$(basename "$target") + edit_directory=$(_get_edit_directory "$target") -sudo test -e "$1" && ( - sudo cp -i "$1" "$filepath" - sudo chown "$user":"$group" "$filepath" -) || ( - touch "$filepath" + edit_file=$(realpath -s "$edit_directory/$target_name") + echo "$edit_file" +} + +_prepare_for_edit() { + target=$(readlink -fn "$1") + + _pre_checks_file "$target" + + edit_directory=$(_get_edit_directory "$target") + edit_file=$(_get_edit_file "$target") + + mkdir -p "$edit_directory" + + user=$(id -un) + group=$(id -gn) + + if sudo test -e "$target"; then + sudo cp -i "$target" "$edit_file" + sudo chown "$user":"$group" "$edit_file" + else + touch "$edit_file" + fi + + echo "$edit_file" +} + +_pre_checks + +# Prepare all files for editing and collect the names of the edit files +all_edit_files="" +for arg in "$@"; do + edit_file=$(_prepare_for_edit "$arg") + all_edit_files="$all_edit_files $edit_file" +done + +# Use a subshell to avoid overwriting $@ +( + for file in $all_edit_files; do + set -- "$file" "$@" + done + $EDITOR "$@" ) -$EDITOR "$filepath" +# Copy all edit files back +for arg in "$@"; do + edit_file=$(_get_edit_file "$arg") + sudo cp "$edit_file" "$arg" && rm "$edit_file" -sudo cp "$filepath" "$1" - -rm "$filepath" -rm -rd "$filedirectory" + edit_directory=$(_get_edit_directory "$target") + # Try to remove the directory, but don't fail if it's not empty + rm -d "$edit_directory" 2>/dev/null || true +done