Last active
March 17, 2018 18:56
-
-
Save nojvek/24c270d1f17ffee30437809250f2c510 to your computer and use it in GitHub Desktop.
Sync git branch + changes from one machine to another continuosly
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/local/bin/bash | |
USAGE=$'Usage: sync.sh <user@host> <dest_dir> e.g ./sync.sh user@host \'~/dest_dir\'' | |
SSH_HOST=${1:?$USAGE} | |
DEST_DIR=${2:-"~/`basename $PWD`"} | |
sync_files() { | |
declare -A file_hash_map | |
while IFS= read -r file; do | |
file=${file#"$PWD/"} # get relative path | |
if [ -f $file ]; then | |
file_hash=`md5 -q $file` | |
# if file's md5 hash sum is different then last time, copy it | |
if [ "${file_hash_map[$file]}" != "$file_hash" ]; then | |
echo `date +%r` "Updating $file" | |
(time scp -C -q $file $SSH_HOST:$DEST_DIR/$file) 2> >(grep real) | |
file_hash_map["$file"]=$file_hash | |
fi | |
elif [ -d $file ]; then | |
# if it's a directory then recursively copy it | |
echo `date +%r` "Copying dir $file" | |
(time scp -C -r -q $file $SSH_HOST:$DEST_DIR/$file) 2> >(grep real) | |
elif [ ! -e $file ]; then | |
# if file or dir doesn't exist locally, then delete it on ssh host too | |
echo `date +%r` Deleting $file | |
unset file_hash_map["$file"] | |
(time ssh -n $SSH_HOST "rm -rf $DEST_DIR/$file") 2> >(grep real) | |
fi | |
done | |
} | |
########## | |
## MAIN ## | |
########## | |
LOCAL_BRANCH=`git rev-parse --abbrev-ref HEAD` | |
# Don't push to master branch. Make the user do it if they really want it | |
if [ $LOCAL_BRANCH != 'master' ]; then | |
echo `date +%r` "Pushing local to origin/$LOCAL_BRANCH" | |
git push -f | |
else | |
echo `date +%r` "!! Skipped pushing to origin/$LOCAL_BRANCH !!" | |
fi | |
echo `date +%r` "Updating $SSH_HOST:$DEST_DIR to origin/$LOCAL_BRANCH" | |
ssh $SSH_HOST "(cd $DEST_DIR; git fetch origin -p; git checkout -f $LOCAL_BRANCH; git reset --hard origin/$LOCAL_BRANCH; git clean -df)" | |
# Checkout changes from another branch if defined | |
if [ $BRANCH_2 ]; then | |
BRANCH_2_FILES=`git diff --name-only origin/master...origin/$BRANCH_2 | tr '\n' ' '` | |
echo `date +%r` "checkout origin/$BRANCH_2 -- $BRANCH_2_FILES" | |
ssh $SSH_HOST "(cd $DEST_DIR; git checkout origin/$BRANCH_2 -- $BRANCH_2_FILES)" | |
fi | |
echo "" | |
echo `date +%r` "Syncing files in git status" | |
git status -s -u | awk '{print $2}' | sync_files | |
echo "" | |
echo `date +%r` "Watching for new changes" | |
fswatch -m fsevents_monitor -Ee '\.git|node_modules' . | sync_files |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment