Skip to content

Instantly share code, notes, and snippets.

@rlyon
Created January 25, 2014 08:20
Show Gist options
  • Save rlyon/8613404 to your computer and use it in GitHub Desktop.
Save rlyon/8613404 to your computer and use it in GitHub Desktop.
Fetch and merge all repositories in a folder.
#!/bin/bash
function header() {
printf "\e[0;36m$1\e[0m\n"
}
function error() {
printf " \e[1;31m!!! $1\e[0m\n"
}
function warning() {
printf " \e[1;33m* $1\e[0m\n"
}
function colorize_yellow() {
printf "\e[1;33m"
}
function colorize_reset() {
printf "\e[0m\n"
}
function notice() {
printf " \e[1;32m* $1\e[0m\n"
}
function is_git_repository() {
return $([ -d .git ])
}
function local_ref() {
echo $(git show-ref | grep refs/heads/master | cut -f1 -d' ')
}
function remote_ref() {
echo $(git ls-remote 2>/dev/null | grep refs/heads/master | cut -f1)
}
function has_untracked_files() {
git status -uall | grep "Untracked files" 2>&1>/dev/null
return $?
}
function has_uncommitted_files() {
git status -uall | grep "Changes to be committed" 2>&1>/dev/null
return $?
}
function has_unstaged_files() {
git status -uall | grep "Changes not staged for commit" 2>&1>/dev/null
return $?
}
function needs_push() {
git log origin/master..master | grep "commit" 2>&1>/dev/null
return $?
}
function can_fetch() {
local retval=0
is_git_repository
if [ $? -eq 1 ] ; then error "Is not a git repository" ; return 2 ; fi
#echo -n " * Checking to see if it is ahead of the remote... "
needs_push
if [ $? -eq 0 ] ; then error "Is ahead of remote" ; retval=1 ; fi
#echo -n " * Checking to see if it has uncommitted files... "
has_uncommitted_files
if [ $? -eq 0 ] ; then error "Has uncommitted files" ; retval=1 ; fi
#echo -n " * Checking to see if it has untracked files... "
has_untracked_files
if [ $? -eq 0 ] ; then error "Has untracked files" ; retval=1 ; fi
has_unstaged_files
if [ $? -eq 0 ] ; then error "Has unstaged files" ; retval=1 ; fi
return $retval
}
cd $HOME/git
for finddir in $(find . -type d -maxdepth 1 -mindepth 1) ; do
dir=$(basename $finddir)
pushd $dir > /dev/null
# "$(local_ref)" == "$(remote_ref)"
header "Checking the $dir directory"
can_fetch
retval=$?
if [[ $retval == 1 ]] ; then
error "Found local changes... Please stash/commit/push."
elif [[ $retval == 2 ]] ; then
error "Please run 'git init' to initialize the repository."
else
if [ "$(local_ref)" != "$(remote_ref)" ] ; then
warning "The $dir directory does not match the remote..."
warning "Trying to fetch and merge."
colorize_yellow
git fetch origin
git merge origin/master
colorize_reset
else
notice "OK"
fi
fi
popd > /dev/null
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment