so I have this snippet that I want to use to filter out branches that doesn't have a certain prefix and that hasn't received any commits in over 3 months so that I can remove them from our remote later on.
for k in $(git branch -r | awk -Forigin !'/\/Prefix1\/|\/prefix2\//'); do
if [ "$(git log -1 --before="3 month" $k)" ]; then
echo "$(git log -1 --pretty=format:"%ci, %cr, " $k) $k";
fi;
done
The problem is currently that when I run this I see branches that have received commits 3 weeks ago, 5 months ago, 2 months ago, 1 month ago etc etc and I can't figure out why.
But if I only run: git log --before="4 month" --pretty=format:"%ci, %cr, " It works as intended.
Can anyone give me any guidance?
The -1
in git log -1 [filters] $k
will :
git log [filters] $k
So if a branch has a 3 month old commit in its history (I would guess : any of your branches does), git log -1 --before="3 month" $k
will always show 1 line -- the first commit in its history that is more than 3 month old.
Your leading if [ ... ]
condition will always be true.
To fix that, you can limit the range of commits to select only the leading commit of each branch :
git log --before="3month" $k^..$k
[edit]
Another option (as suggested by user phd in a comment to this question) is to list each branch together with the date of its topmost commit, and keep only lines where the date fall below 4 months ago:
# in this example I use 'committerdate', you may also use 'authordate' if
# you think it is a better fit for your needs
git branch -r --format="%(committerdate:format:%F) %(refname:short)" \
--sort=-committerdate | <... process the list ...>
note the --format
option for git branch
is documented in git help for-each-ref
(here: --format flag and here: FIELD NAMES section),
if you scroll at the bottom of the FIELD NAMES section, you will find a mention of how to format date fields:
As a special case for the date-type fields, you may specify a format for the date by adding
:
followed by date format name (see the values the--date
option togit-rev-list[1]
takes).