dots-of-war/files/scripts/nix_stash

76 lines
1.5 KiB
Text
Raw Normal View History

2020-10-30 22:02:38 +02:00
#! /bin/sh
2020-07-07 18:38:33 +02:00
2020-07-07 18:44:58 +02:00
NIX_STASH_DIR="$XDG_CONFIG_HOME/nix_stash"
FILE_STACK_PATH="$NIX_STASH_DIR/nix_stash_stack"
2020-07-07 18:38:33 +02:00
# pop the last line from the file-stack and return it
2020-10-30 22:02:38 +02:00
pop_from_file_stack () {
2020-07-07 18:38:33 +02:00
line="$(tail -n 1 "$FILE_STACK_PATH")"
2020-10-30 22:02:38 +02:00
[ -z "$line" ] && \
exit 1
2020-07-07 18:38:33 +02:00
sed -i "$ d" "$FILE_STACK_PATH"
echo "$line"
}
2020-10-30 22:02:38 +02:00
do_pop () {
2020-07-07 18:38:33 +02:00
last_file="$(pop_from_file_stack)" || exit 1
echo "restoring $last_file"
trash "$last_file"
2020-07-07 18:44:58 +02:00
[ ! -s "$FILE_STACK_PATH" ] && home-manager switch
2020-07-07 18:38:33 +02:00
}
2020-10-30 22:02:38 +02:00
do_stash () {
2020-07-07 18:38:33 +02:00
config_file="$(realpath --no-symlinks "$1")"
2020-10-30 22:02:38 +02:00
[ ! -L "$config_file" ] && \
echo "Given file is not a symlink into the nix-store" && \
2020-07-07 18:38:33 +02:00
exit 1
file_in_store="$(readlink -f "$config_file")"
2020-10-30 22:02:38 +02:00
[ ! "$(echo "$file_in_store" | grep -iq "/nix/store")" ] && \
echo "file is not a symlink into the nix store" && \
2020-07-07 18:38:33 +02:00
exit 1
# remove the symlink and write the path to the stack
2020-07-07 18:44:58 +02:00
mkdir -p "$NIX_STASH_DIR"
2020-07-07 18:38:33 +02:00
rm -rf "$config_file"
echo "$config_file" >> "$FILE_STACK_PATH"
# replace the file with the contents of the generated config file
cp -rp "$file_in_store" "$config_file"
chmod 777 "$config_file"
# open the file in nvim
"$EDITOR" "$config_file"
}
2020-10-30 22:02:38 +02:00
do_list () {
2020-07-07 18:38:33 +02:00
cat "$FILE_STACK_PATH"
}
2020-10-30 22:02:38 +02:00
print_usage () {
2020-07-07 18:38:33 +02:00
echo "usage: $0 {<filepath> | pop | list}"
echo " to stash a file: $0 <filepath>"
echo " to restore a file: $0 pop"
echo " list the stack: $0 pop"
exit 1
}
case "$1" in
"")
print_usage
;;
2020-10-30 22:02:38 +02:00
pop)
do_pop
2020-07-07 18:38:33 +02:00
;;
list)
do_list
;;
2020-10-30 22:02:38 +02:00
*)
do_stash "$1"
2020-07-07 18:38:33 +02:00
;;
esac