Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically get a diff between two versions of a file in TFS

Tags:

c#

tfs

tfs-sdk

I'm trying to write a code which, given a path to an item in the TFS repository and two revisions, would compute a difference between the contents file had at these two moments. For now the code might look like this:

using (var projectCollection = new TfsTeamProjectCollection(new Uri(repositoryUrl)))
{
    projectCollection.EnsureAuthenticated();
    var versionControlServer = (VersionControlServer)projectCollection.GetService(typeof(VersionControlServer));

    string path = "$/MyProject/path/to/file.xml"

    var before = new DiffItemVersionedFile(versionControlServer, path, VersionSpec.ParseSingleSpec(minRevision.ToString(), null));
    var after = new DiffItemVersionedFile(versionControlServer, path, VersionSpec.ParseSingleSpec(maxRevision.ToString(), null));

    using (var stream = new MemoryStream())
    using (var writer = new StreamWriter(stream))
    {
        var options = new DiffOptions();
        options.Flags = DiffOptionFlags.EnablePreambleHandling;
        options.OutputType = DiffOutputType.Unified;
        options.TargetEncoding = Encoding.UTF8;
        options.SourceEncoding = Encoding.UTF8;
        options.StreamWriter = writer;
        Difference.DiffFiles(versionControlServer, before, after, options, path, true);
        writer.Flush();

        var reader = new StreamReader(stream);
        var diff = reader.ReadToEnd();
    }
}

But once this code is executed, the variable diff is an empty string even though I know for sure the file has been modified between minRevision and maxRevision.

This code will also throw an exception if the file didn't exist at minRevision or was deleted in maxRevision, but this seems to be a problem to solve later, once I get this thing working with files which were only edited.

EDIT

Having checked temp files, I'm sure both versions of the file are downloaded correctly. Something is wrong with the computation of the diff or with writing the diff to a stream or with copying the diff to a string.

like image 611
kamilk Avatar asked Jun 29 '12 14:06

kamilk


2 Answers

Solved. The problem was the reader. After I changed the last two lines to

var diff = Encoding.UTF8.GetString(stream.ToArray());

I got some diff at last.

like image 114
kamilk Avatar answered Sep 28 '22 16:09

kamilk


I know you accepted your answer, and this was asked in 2012, but I recently had to do the same thing, but much prefer using a StreamReader vs .ToArray()

The answer is that you have to reset the MemoryStream before you start reading from it.

add this

stream.Position = 0;

right after you flush the writer

like image 30
karoberts Avatar answered Sep 28 '22 15:09

karoberts