How to retrieve the history of a file?

后端 未结 3 784
不知归路
不知归路 2021-01-01 14:04

I got another libgit2 issue and will be very grateful for your help.

I\'m trying to retrieve file history, i.e. list of commits where this file was changed. And it s

3条回答
  •  情深已故
    2021-01-01 14:15

    If using C#, this functionality has been added to the LibGit2Sharp 0.22.0 NuGet Package (Pull Request 963). You can do the following:

    var fileHistory = repository.Commits.QueryBy(filePathRelativeToRepository);
    foreach (var version in fileHistory)
    {
        // Get further details by inspecting version.Commit
    }
    

    In my Diff All Files VS Extension (which is open source so you can view the code), I needed to get a file's previous commit so I can see what changes were made to a file in a given commit. This is how I retrieved the file's previous commit:

    /// 
    /// Gets the previous commit of the file.
    /// 
    /// The repository.
    /// The file path relative to repository.
    /// The commit sha to start the search for the previous version from. If null, the latest commit of the file will be returned.
    /// 
    private static Commit GetPreviousCommitOfFile(Repository repository, string filePathRelativeToRepository, string commitSha = null)
    {
        bool versionMatchesGivenVersion = false;
        var fileHistory = repository.Commits.QueryBy(filePathRelativeToRepository);
        foreach (var version in fileHistory)
        {
            // If they want the latest commit or we have found the "previous" commit that they were after, return it.
            if (string.IsNullOrWhiteSpace(commitSha) || versionMatchesGivenVersion)
                return version.Commit;
    
            // If this commit version matches the version specified, we want to return the next commit in the list, as it will be the previous commit.
            if (version.Commit.Sha.Equals(commitSha))
                versionMatchesGivenVersion = true;
        }
    
        return null;
    }
    

提交回复
热议问题