Skip to content

Instantly share code, notes, and snippets.

@jwliechty
Last active August 29, 2015 14:27
Show Gist options
  • Save jwliechty/90af0c974ba53d9eed53 to your computer and use it in GitHub Desktop.
Save jwliechty/90af0c974ba53d9eed53 to your computer and use it in GitHub Desktop.
Iterates over the branches of a repository, executing a command (or custom script) on each checked out branch.
#!/bin/bash -e
REPO_PATH=/home/jwliechty/dev/release/ascent-assays
COMMAND="$1"
ARG_COUNT="$#"
usage(){
cat <<-END
Usage: $(basename $0) COMMAND
where COMMAND will be the command executed with the branch name passed in
as an argument. The command will be executed in the repository directory
with the branch checked out. To pause on each branch, read from standard
input within your custom script command.
Examples:
$(basename $0) echo
$(basename $0) my_custom_script.sh
END
die
}
ensureCommandProvided(){
[ -z "${command}" ] || usage
[ "${ARG_COUNT}" = "1" ] || usage
}
goToRepo(){
cd "${REPO_PATH}"
isGitRepo || die "Not a git repository: ${REPO_PATH}"
}
updateRepo(){
echo "Updating repository"
git fetch origin
git remote prune origin
}
runOnEachBranch(){
echo -e "Iterating over branches...\n"
for refname in $(git for-each-ref --format='%(refname:short)' refs/remotes/origin); do
local branch="${refname#origin/}"
[ "${branch}" != "HEAD" ] && executeOnBranch "${branch}"
done
}
executeOnBranch(){
local branch="$1"
git checkout "${branch}" > /dev/null 2>&1 || die "Unable to checkout branch '${branch}'"
git pull origin "${branch}" > /dev/null 2>&1 || die "Error while pulling branch '${branch}'"
(
${COMMAND} "${branch}"
) || die "Command failed on branch '${branch}'"
}
isGitRepo(){
git rev-parse 2> /dev/null
return $?
}
die(){
local msg="$1"
echo "${msg}" >&2
exit 1
}
ensureCommandProvided
goToRepo
updateRepo
runOnEachBranch
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment