Everton Oliveira
Everton Oliveira

Reputation: 950

Git log - show the timestamp of the last change in a specific file

I would like to get the timestamp of the last modification in a specific file, I tried the following approaches:

git log -1 --format="%ai" -- "abc/abc/abc/test_1203.sql"

The result of the command above is empty.

I also tried to output all changes with their timestamp, but the command that I used breaks the line, and I'd like to have "file name" "timestamp"

git log --diff-filter=D --since="3 day ago" --name-only --pretty='format:%ai'

Any ideas on how to make it work?

Thanks

Upvotes: 0

Views: 495

Answers (1)

Everton Oliveira
Everton Oliveira

Reputation: 950

Edit - Answer 1

I am not sure why, but the Git command now runs as expected after rebooting the computer (I'm on Windows PC). The command below answers my question:

git log -1 --format="%ai" -- "abc/abc/abc/test_1203.sql"

Answer 2

I ended up doing a workaround to get the result that I wanted, basically it envolves a PowerShell script to parse the output returned from git. It's not pretty, I'm certain there is a better way of doing this, but it gets the job done.

  1. Get a list of deleted files since 7 days ago with timestamp included
    # get all deleted changes
    $sqlDiffList= Git log --diff-filter=D --since="7 day ago" --name-only --pretty=format:%ai
  1. Create two objects with matching Ids, one for the timestamp and the other for the filename.
#Helper
$timestamp =@()
$name =@()
$i = 0

# Loop through array and create two objects with matching IDs
foreach ($sqlDiff in $sqlDiffList) {

    # New lines are determined by an empty string returned in the array, so we attribute a new ID for it.
    if ($sqlDiff -eq '') {
        $i += 1;
    }
    # Populate object with datetime values
    if(($sqlDiff) -match "\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}")
    {
        $timestamp += New-Object -TypeName psobject -Property @{ 
            id          = $i;`
            lastUpdate  = $sqlDiff;`
            filter      = 'X'   
        }  
    # Populate object with file name
    } else {
        $name += New-Object -TypeName psobject -Property @{ 
            id         = $i;`
            name       = $sqlDiff;`
            filter     = 'X'   
        }  
    }  
}
# Get rid of empty lines 
$name = $name | Where-Object {$_.name -ne ''}
  1. Join objects on matching Ids
# Join the objects created above with the latest modification 
foreach ($n in $name)
{
    foreach ($t in $timestamp)
    {
        # decide whether to join
        if ($n.id -eq ($t.id | Measure-Object -Maximum).Maximum)
        {
            # output a new object with the join result
            New-Object PSObject -Property @{
                name = $n.name;
                lastUpdate = $t.lastUpdate;
                filter = $t.filter;
            };
        }
    }
}
  1. Output

enter image description here

Upvotes: 1

Related Questions