pseudosudo
pseudosudo

Reputation: 6590

List files in order of last modification date

My repo is overdue for a cleanup. I thought a good starting point would be to list all files in order of last time they were touched and start with the oldest. Is there a way to achieve this?

Upvotes: 8

Views: 3411

Answers (3)

user3426575
user3426575

Reputation: 1773

There is no way (of which I'm aware) to do this using the standard git commands. What you need is some sort of git blame for the whole repository, identifying the last commit in the history which changed each file. Of course, you could use the standard git blame, parse the porcelain output to identify the timestamp of the latest commit which added content to the file, and sort the files according to that timestamp:

#!/bin/bash

function last-modified()
{
    git blame -p "$1" | awk '
        BEGIN {
            print 0;
        }
        $1 == "author-time" {
            print $2;
        }' | sort -n | tail -n 1
}

function list-files()
{
    for file in $(git ls-files); do
        echo "$(last-modified $file) $file"
    done
}

list-files | sort -n

This approach is only able to register content being added to a file, though, not content being removed from the file. Also, it will break when there are lines in your repository starting with author-time.

Upvotes: 5

CodeMonkey
CodeMonkey

Reputation: 4738

4b825dc642cb6eb9a060e54bf8d69288fbee4904 is the empty-tree commit in git.

Using --name-only you can get the file names, by pretty printing nothing, you get empty lines for the commit info. By piping into awk NF you filter the empty lines. By piping into tac the order is reversed.

git log --pretty="format:" --name-only 4b825dc642cb6eb9a060e54bf8d69288fbee4904..HEAD | awk NF | tac

Upvotes: 0

Stéphane Gourichon
Stéphane Gourichon

Reputation: 6981

Commit-level information should be enough to answer the OP question, no need for the sort of details that git-blame fetches.

This approach lists all files known to git with the date of the last commit that affects the file, sorted by that date:

while read FILE
do git log --pretty="%ad $FILE" --date=iso8601-strict -1 -- "$FILE"
done < <( git ls-files ) | sort

One might want to restrict to files currently checked out in their current directory:

while read FILE
do git log --pretty="%ad $FILE" --date=iso8601-strict -1 -- "$FILE"
done < <( find . -type f ) | sort

One might want to list only files, not showing dates:

while read FILE
do git log --pretty="%ad $FILE" --date=iso8601-strict -1 -- "$FILE"
done < <( git ls-files ) | sort | cut -f 2 -d " "

Other combinations are possible.

All those should work in case of files with spaces and other characters.

Upvotes: 5

Related Questions