Skip to content

Instantly share code, notes, and snippets.

@gerasiov gerasiov/git-sync
Created Apr 25, 2018

Embed
What would you like to do?
#!/bin/sh
set -e
#set -x
USB="$PWD"
WORK=$HOME/work
SYNC_TS=.git/sync.timestamp
[ -f .components ] && COMPONENTS="$(cat .components)"
if [ ! -z "$@" ];then
COMPONENTS="$@"
fi
if [ -z "$COMPONENTS" ];then
echo "No components specified."
echo "List them in .components file or command line."
exit 1
fi
checklocal(){
local COMP=$1
(
test -d "$COMP" || return 0
cd "$COMP"
git diff --quiet || { echo 1; return 1; }
git diff --quiet --cached || { echo 2; return 1; }
)
}
compare(){
local COMP=$1
local MODIFIED=0
test -d "$COMP" -o -f "$USB/$COMP.tar" || { echo 5; return 5; }
test -d "$COMP" || { echo 1; return 1; }
test -f "$USB/$COMP.tar" || { echo 2; return 2; }
test -f "$COMP/$SYNC_TS"|| { echo 4; return 4; }
local WORK_TS=$(find $COMP/.git/refs $COMP/.git/HEAD $COMP/.git/logs/refs/ -type f -printf '%T@ %p\n' | sort -rn | awk '{print $2;exit}')
if [ "$USB/$COMP.tar" -nt "$COMP/$SYNC_TS" ]; then
MODIFIED=$((MODIFIED + 1))
fi
if [ "$WORK_TS" -nt "$COMP/$SYNC_TS" ];then
MODIFIED=$((MODIFIED + 2))
fi
echo $MODIFIED
return $MODIFIED
}
towork(){
local COMP=$1
test -f "$USB/$COMP.tar" || { echo "Fatal: $COMP not found on USB."; return 1; }
rm -rf "$COMP/.git"
tar xpf "$USB/$COMP.tar"
{
cd $COMP
git reset --hard
cd ..
}
touch -r "$USB/$COMP.tar" "$COMP/$SYNC_TS"
return 0
}
tousb(){
local COMP=$1
rm -f "$USB/$COMP.tar" "$USB/$COMP.tar.tmp"
tar cp "$COMP/.git" -f "$USB/$COMP.tar.tmp"
touch -r "$USB/$COMP.tar.tmp" "$COMP/$SYNC_TS"
mv "$USB/$COMP.tar.tmp" "$USB/$COMP.tar"
return 0
}
process(){
local COMP=$1
local CHANGED=$(checklocal $COMP)
case $CHANGED in
1) { echo "$COMP: unstaged changes found, skipping."; return 1; }
;;
2) { echo "$COMP: uncommited changes found, skipping."; return 1; }
;;
esac
local COMPARE=$(compare $COMP)
case $COMPARE in
0) echo "$COMP is equal, skipping."
;;
1) echo "$COMP is newer on USB, processing..."
towork $COMP
;;
2) echo "$COMP is newer in working dir, processing..."
tousb $COMP
;;
3) echo "$COMP was modified in both location, skipping."
;;
4) echo "$COMP exists, but sync status is unknown, skipping."
;;
5) echo "$COMP not exists in working dir nor on USB, skipping."
;;
*) echo "unexpected"
;;
esac
}
cd "$WORK"
for COMP in $COMPONENTS;do
COMP=${COMP%.tar}
process $COMP||true
done
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.