dots-of-war/files/scripts/nix_stash

82 lines
1.5 KiB
Text
Raw Normal View History

2020-07-07 16:38:33 +00:00
#!/bin/sh
2020-07-07 16:44:58 +00:00
NIX_STASH_DIR="$XDG_CONFIG_HOME/nix_stash"
FILE_STACK_PATH="$NIX_STASH_DIR/nix_stash_stack"
2020-07-07 16:38:33 +00:00
# pop the last line from the file-stack and return it
pop_from_file_stack() {
line="$(tail -n 1 "$FILE_STACK_PATH")"
if [ -z "$line" ]; then
exit 1
fi
sed -i "$ d" "$FILE_STACK_PATH"
echo "$line"
}
do_pop() {
last_file="$(pop_from_file_stack)" || exit 1
echo "restoring $last_file"
trash "$last_file"
2020-07-07 16:44:58 +00:00
[ ! -s "$FILE_STACK_PATH" ] && home-manager switch
2020-07-07 16:38:33 +00:00
}
do_stash() {
config_file="$(realpath --no-symlinks "$1")"
if [ ! -L "$config_file" ]; then
echo "Given file is not a symlink into the nix-store"
exit 1
fi
file_in_store="$(readlink -f "$config_file")"
if ! echo "$file_in_store" | grep -q "/nix/store"; then
echo "file is not a symlink into the nix store"
exit 1
fi
# remove the symlink and write the path to the stack
2020-07-07 16:44:58 +00:00
mkdir -p "$NIX_STASH_DIR"
2020-07-07 16:38:33 +00: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"
}
do_list() {
cat "$FILE_STACK_PATH"
}
print_usage() {
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
;;
pop)
do_pop
;;
list)
do_list
;;
*)
do_stash "$1"
;;
esac