git for-each-ref - filter results by age

Viewed 914

I'm using the following command from here:

git for-each-ref --format='%(color:cyan)%(authordate:format:%m/%d/%Y %I:%M %p)    %(align:25,left)%(color:yellow)%(authorname)%(end) %(color:reset)%(refname:strip=3)' --sort=authordate refs/remotes

Is there a way to sort authordate by a specific date?

For example, only show results that are X days or months old, or perhaps after a given date? I was thinking about using grep but I was hoping there was an approach that actually parses the given date to do the calculations rather than just string matching.

I came up with the following using sed:

git for-each-ref --format='%(color:cyan)%(authordate:format:%Y-%m-%d %I:%M %p)    %(align:25,left)%(color:yellow)%(authorname)%(end) %(color:reset)%(refname:strip=3)' --sort=authordate refs/remotes | sed -n '/{start_year}-*/,/{end_year}-{end_month}-*/p'

but it would be much better to just give one specific date and get all results before or after said date.

EDIT: The method above using sed doesn't work if the given end date doesn't exist since sed is only a stream editor. For example, if the resulting sed string is '/2017-*/,/2018-10-*/p' but there are no entries matching 2018-10-* (no branches with commits in the month of October of 2018) then it will get all of the results from 2017 onward. That is, it isn't a true date range calculation; it's a simple string matching that stop when it finds the first entry matching the right side.

1 Answers

Neither the git-for-each-ref nor git-branch commands provide an option to filter by date.

However, it's pretty trivial to filter the output of either one with AWK, but first we need to use an ISO 8601 date format (yyyy-MM-dd) to make the comparison easy. Also, the colour won't survive the pass through AWK (well, I don't know how to make it do that), so we might as well lose it.

Here's how to do it with your format:

git for-each-ref \
    refs/remotes \
    --sort=authordate \
    --format='%(authordate:format:%Y-%m-%d %I:%M %p)  %(align:25,left)%(authorname)%(end) %(refname:strip=3)'  \
    | awk '{ if ($1 < "2021-11-23") print $0 }'

Alternatively, this command will just print the name of local branches whose latest commit date (different to author date) was before the date inside the AWK program:

git branch --sort=-committerdate --format='%(committerdate:short) %(refname:short)' \
    | awk '{ if ($1 < "2021-11-23") { print $2 } }'
Related