diff --git a/src/common/gitservice/blame.go b/src/common/gitservice/blame.go index c6147de8..6a39a714 100644 --- a/src/common/gitservice/blame.go +++ b/src/common/gitservice/blame.go @@ -2,6 +2,7 @@ package gitservice import ( "fmt" + "github.com/go-git/go-git/v5/plumbing/object" "strings" "time" @@ -19,29 +20,45 @@ type GitBlame struct { GitUserEmail string } -func NewGitBlame(RelFilePath string, filePath string, lines structure.Lines, blameResult *git.BlameResult, g *GitService) *GitBlame { - gitBlame := GitBlame{GitOrg: g.organization, GitRepository: g.repoName, BlamesByLine: map[int]*git.Line{}, FilePath: filePath, GitUserEmail: g.currentUserEmail} - startLine := lines.Start - 1 // the lines in blameResult.Lines start from zero while the lines range start from 1 - endLine := lines.End - 1 - - ref, _ := g.repository.Head() - commit, _ := g.repository.CommitObject(ref.Hash()) +func GetPreviousBlameResult(g *GitService, filePath string) (*git.BlameResult, *object.Commit) { + if g.repository == nil { + return nil, nil + } + ref, err := g.repository.Head() + if err != nil { + return nil, nil + } + commit, err := g.repository.CommitObject(ref.Hash()) + if err != nil { + return nil, nil + } parentIter := commit.Parents() - previousCommit, _ := parentIter.Next() + previousCommit, err := parentIter.Next() + if err != nil { + return nil, nil + } var previousBlameResult *git.BlameResult result, _ := g.PreviousBlameByFile.Load(filePath) previousBlameResult = result.(*git.BlameResult) + return previousBlameResult, previousCommit +} + +func NewGitBlame(realFilePath string, filePath string, lines structure.Lines, blameResult *git.BlameResult, g *GitService) *GitBlame { + gitBlame := GitBlame{GitOrg: g.organization, GitRepository: g.repoName, BlamesByLine: map[int]*git.Line{}, FilePath: realFilePath, GitUserEmail: g.currentUserEmail} + startLine := lines.Start - 1 // the lines in blameResult.Lines start from zero while the lines range start from 1 + endLine := lines.End - 1 + previousBlameResult, previousCommit := GetPreviousBlameResult(g, filePath) for line := startLine; line <= endLine; line++ { if line >= len(blameResult.Lines) { - logger.Warning(fmt.Sprintf("Index out of bound on parsed file %s", RelFilePath)) + logger.Warning(fmt.Sprintf("Index out of bound on parsed file %s", realFilePath)) return &gitBlame } gitBlame.BlamesByLine[line+1] = blameResult.Lines[line] // Check if the line has been removed in the current state of the file - if len(previousBlameResult.Lines) > len(blameResult.Lines) { + if previousBlameResult != nil && len(previousBlameResult.Lines) > len(blameResult.Lines) { if previousBlameResult.Lines[line].Text != blameResult.Lines[line].Text { // The line has been removed, so update the git commit id gitBlame.BlamesByLine[line+1].Hash = previousCommit.Hash