Skip to content

Instantly share code, notes, and snippets.

@battlesnake
Last active January 26, 2022 12:34
Show Gist options
  • Save battlesnake/59eab6c00429f1ba279056bb8a42c46c to your computer and use it in GitHub Desktop.
Save battlesnake/59eab6c00429f1ba279056bb8a42c46c to your computer and use it in GitHub Desktop.
Archive Git branches in remote that have not received a commit for x days/weeks/months/years
#!/usr/bin/env bash
set -euo pipefail
declare -a branches=()
# Update our view of the remote
git fetch --all
# Read in names of branches in remote (<remote-name>/<branch-name>), excluding already-archived branches
# Also filter by whether the branch received any commits during a recent time-interval
while read -r branch; do
if [ -z "$(git log -1 --since='6 months ago' -s "${branch}")" ]; then
branches+=( "$branch" )
fi
done < <(git branch -r | grep -vF HEAD | grep -vF -- '->' | grep -vF '/archive/' | sed -e 's/^\s\+\|\s\+$//g')
# List branches and last commit relative-time
echo ""
echo "Branches:"
for branch in "${branches[@]}"; do
printf -- " * %s \x1b[35m(%s ago)\x1b[0m\n" "${branch}" "$(git log -1 --format="%cr" "$branch")"
done
echo ""
# Ask for confirmation
if ! read -r -n 1 -p 'Archive these branches? ' yn || ! [[ $yn == [Yy] ]]; then
echo "Cancelled"
exit 1
fi
# Iterate over branches and prefix their names with "archive/"
function do_archiving {
local remote_name
local local_name
local archive_name
local worktree
worktree="$(mktemp -u)"
for branch in "${branches[@]}"; do
remote_name="$(printf -- "%s\n" "$branch" | cut -d/ -f1)"
local_name="$(printf -- "%s\n" "$branch" | cut -d/ -f2-)"
archive_name="archive/${local_name}"
git worktree add -b "${archive_name}" "$worktree" "${branch}"
pushd "$worktree"
git push "${remote_name}" ":${local_name}" "${archive_name}:${archive_name}"
popd
git worktree remove -f "$worktree"
rm -rf "$worktree"
git branch -D "${archive_name}"
done | tee .archive-old-branches.log
}
do_archiving
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment