Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding files older than certain dates in Git repository

Tags:

git

I am trying to find files older than certain dates in the past, for example, cpp source files that have not been modified for 2 months in the Git repo.

If I use the Linux find shell command I won't be able to find it, because the files in my workspace are marked by the date when it was "git sync"-ed.

How can I do this?

like image 809
electro Avatar asked Mar 10 '23 23:03

electro


1 Answers

First we need to find the files currently in the repo. That's easy:

git ls-files

For each of those files, we want to see if it has been modified after a given date. git log will work here:

git log --since "<some date>" -- somefile.cpp

(This will give no output if the file hasn't been modified since the given date.)

Putting it all together with another git log command for user-friendly output, here's a bash script that should do the job:

#!/bin/bash

date=$1
git ls-files | while read path
do
  if [ "$(git log --since \"$date\" -- $path)" == "" ]
  then
    echo "$path $(git log -1 --pretty='%h %ad' -- $path)"
  fi
done

Usage:

/path/to/myscript.sh "2017-01-01 12:00"

This will show you only files that have not been modified since before noon on January 1st, 2017.

It's Bash, so of course you could condense this down to one line:

git ls-files | while read path; do if [ "$(git log --since \"$1\" -- $path)" == "" ]; then echo "$path $(git log -1 --pretty='%h %ad' -- $path)"; fi done

To limit the results to certain kinds of files, add a grep command in the middle, like so:

git ls-files | grep -e ".cpp$" -e ".h$" -e ".c$" | while read path; ...

Here's a version of the above script that lets you pass those file types as arguments:

#!/bin/bash

date=$1
grepargs=""
shift
while [ $? -eq 0 ]
do
  grepargs="$grepargs -e \"$1\""
  shift
done
git ls-files | grep $grepargs | while read path
do
  if [ "$(git log --since \"$date\" -- $path)" == "" ]
  then
    echo "$path $(git log -1 --pretty='%h %ad' -- $path)"
  fi
done

Usage:

/path/to/myscript.sh "2017-01-01 12:00" ".cpp$" ".h$" ".c$"
like image 169
Scott Weldon Avatar answered Mar 14 '23 05:03

Scott Weldon