1
0
Fork 0
dotfiles/common/.local/bin/dotsync

74 lines
2.0 KiB
Bash
Executable File

#!/bin/sh
BOLD="$(tput bold)"
RED="$(tput setaf 1)"
GREEN="$(tput setaf 2)"
BLUE="$(tput setaf 4)"
NC="$(tput sgr0)"
stow_git() {
git -C "$STOW_DIR" "$@"
}
multi_stow() {
ret=0
for package in common "$(hostname)"; do
[ -n "$package" ] && [ -e "${STOW_DIR}/${package}" ] && {
stow --no-folding -d "$STOW_DIR" -t "$HOME" "$@" "$package"
ret=$((ret + $?))
}
done
return $ret
}
{ [ -n "$STOW_DIR" ] && [ -n "$STOW_REPO" ] && [ -n "$STOW_BRANCH" ]; } || {
echo "Please set STOW_DIR, STOW_REPO, and STOW_BRANCH"
exit 1
}
mkdir -p "$STOW_DIR"
# First run
if [ ! -e "$STOW_DIR/.git" ]; then
printf "%b" "${BOLD}${BLUE}Cloning dotfiles...$NC\n\n"
git clone -j4 --recursive "$STOW_REPO" "$STOW_DIR"
multi_stow || printf "%b" "${RED}Failed to run stow!$NC\n"
exit 0
fi
printf "%b" "${BOLD}${BLUE}Removing dotfile symlinks...$NC\n\n"
multi_stow -D || printf "%b" "${RED}Failed to run stow!$NC\n"
printf "%b" "${BOLD}${BLUE}Stashing existing changes...$NC\n"
stash_result=$(stow_git stash push)
needs_pop=1
if [ "$stash_result" = "No local changes to save" ]; then
needs_pop=0
fi
printf "\n"
printf "%b" "${BOLD}${BLUE}Pulling updates from dotfiles repo...$NC\n"
old_commit="$(stow_git rev-parse HEAD)"
stow_git pull origin "$STOW_BRANCH"
stow_git submodule update --remote --merge
printf "\n"
if [ $needs_pop -eq 1 ]; then
printf "%b" "${BOLD}${BLUE}Popping stashed changes...$NC\n"
stow_git stash pop
fi
printf "\n"
unmerged_files=$(stow_git diff --name-only --diff-filter=U)
if [ -n "$unmerged_files" ]; then
printf "%b" "${RED}The following files have merge conflicts after popping the stash:$NC\n\n"
printf "%s" "$unmerged_files\n\n"
printf "%s" "${BOLD}${BLUE}Reverting to previous commit...$NC"
stow_git checkout "$old_commit"
fi
printf "%b" "${BOLD}${BLUE}Symlinking dotfiles...$NC\n\n"
multi_stow || printf "%b" "${RED}Failed to run stow!$NC\n"
printf "%b" "${BOLD}${GREEN}Dotfiles synced successfully!$NC\n"