Last active
August 4, 2021 13:08
-
-
Save apexskier/7211e17a902007cfca92dcf6ae291545 to your computer and use it in GitHub Desktop.
Update all git repos in a directory
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
#!/bin/bash | |
# Updates all git repositories in a directory, doing some housekeeping along the | |
# way | |
nocol="\033[m" | |
green="\033[0;32m" | |
yellow="\033[1;33m" | |
lightgrey="\033[0;37m" | |
darkgrey="\033[1;30m" | |
update() { | |
echo -ne $lightgrey | |
echo -n "$(git rev-parse --abbrev-ref HEAD)" | |
local tracking | |
tracking=$(git for-each-ref --format='%(upstream:short)' "$(git symbolic-ref -q HEAD)") | |
if [ -n "$tracking" ] | |
then | |
echo -n " ➡ $tracking" | |
fi | |
echo -ne $nocol | |
if git show-ref -q "$tracking" | |
then | |
local ahead_behind | |
ahead_behind=$(git rev-list --left-right --count "$tracking"...HEAD) | |
local behind | |
behind=$(echo "$ahead_behind" | cut -d$'\t' -f1) | |
local ahead | |
ahead=$(echo "$ahead_behind" | cut -d$'\t' -f2) | |
if [ "$behind" -ne "0" ] | |
then | |
echo -n ", $behind behind" | |
fi | |
if [ "$ahead" -ne "0" ] | |
then | |
echo -n ", $ahead ahead" | |
fi | |
if [ "$behind" -ne "0" ] | |
then | |
if git merge -q --ff-only 2> /dev/null | |
then | |
echo -ne ", ${green}updated${nocol}" | |
else | |
echo -ne ", ${yellow}no update${nocol}" | |
fi | |
fi | |
elif [ -n "$tracking" ] | |
then | |
echo -ne ", ${yellow}tracked ref missing${nocol}" | |
fi | |
echo | |
} | |
SOURCE_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) | |
for dir in "$SOURCE_DIR/"*/ | |
do | |
cd "$dir" || exit 1 | |
if test -d .git | |
then | |
current=$(git rev-parse --abbrev-ref HEAD) | |
echo -ne $darkgrey | |
basename "$PWD" | |
echo -ne $nocol | |
git fetch -pq | |
echo -n " " | |
update | |
main_branch=$(git symbolic-ref refs/remotes/origin/HEAD | cut -d'/' -f4-) | |
if ! git rev-parse --quiet --verify "$main_branch" > /dev/null | |
then | |
# update the default branch if it's changed | |
echo -n " " | |
git remote set-head origin --auto | |
new_main_branch=$(git symbolic-ref refs/remotes/origin/HEAD | cut -d'/' -f4-) | |
if [ "$current" == "$main_branch" ] | |
then | |
git checkout "$new_main_branch" | |
if git branch -d "$main_branch" | |
then | |
echo -e " ${yellow}couldn't delete old main branch: ${main_branch}${nocol}" | |
fi | |
fi | |
main_branch="$new_main_branch" | |
fi | |
if [ "$current" != "$main_branch" ] | |
then | |
if git checkout -q "$main_branch" | |
then | |
echo -n " " | |
update | |
git checkout -q - | |
else | |
echo -e " ${yellow}couldn't update ${main_branch}${nocol}" | |
fi | |
fi | |
fi | |
cd .. | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment