Description
Hi, I am looking for a way to get the latest commit that affected a particular file / directory. It is something similar to the following git command
git log -1 FILE_NAME
I have tried my own way by iterating through all the commits in the repo and comparing it with its immediate ancestor to find the files that were modified in a commit. The sample code is as follows,
head, _ := r.Head()
commit, _ := r.LookupCommit(head.Target())
for commit != nil {
numParents := commit.ParentCount()
if numParents > 0 {
parentCommit := commit.Parent(0)
parentTree, _ := parentCommit.Tree()
commitTree, _ := commit.Tree()
if parentTree != nil && commitTree != nil {
diff, _ := r.DiffTreeToTree(parentTree, commitTree, nil)
if diff != nil {
numDeltas, _ := diff.NumDeltas()
if numDeltas > 0 {
entry := commitEntry{
commitMessage: commit.Message(),
}
for d := 0; d < numDeltas; d++ {
delta, _ := diff.Delta(d)
fileEntry := fileDiffStruct{diffPath: delta.NewFile.Path}
entry.fileEntries = append(entry.fileEntries, fileEntry)
}
commitEntries = append(commitEntries, entry)
}
}
}
}
commit = commit.Parent(0)
}
I have a function which compares the target file name with the entries stored in the commitEntries
and this logic works as expected for me. The issue arises when the repo size is large.
I tested it with my own repo with around 360 commits and 1100 files, and I get the result in matter of milliseconds. When I tested the same with a larger repo with 20,000 commits and over 5000 objects in the tree, the function takes 3 minutes to return the results.
Is there a built-in API to achieve the expected result or is there any way to optimize my logic to get the expected results faster even for large repos ? Any feedback would be appreciated.