Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 11 additions & 53 deletions src/Nerdbank.GitVersioning.Tasks/CompareFiles.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.MemoryMappedFiles;
using System.Linq;
using System.Text;
using Microsoft.Build.Framework;
Expand Down Expand Up @@ -64,66 +65,23 @@ private bool IsContentOfFilesTheSame(string file1, string file2)
if (File.Exists(file1) ^ File.Exists(file2)) return false;
// If both are missing, that's the same.
if (!File.Exists(file1)) return true;
// If both are present, we need to do a content comparison.
using (FileStream fileStream1 = File.OpenRead(file1))
{
using (FileStream fileStream2 = File.OpenRead(file2))
{
if (fileStream1.Length != fileStream2.Length) return false;
byte[] buffer1 = new byte[4096];
byte[] buffer2 = new byte[buffer1.Length];
int bytesRead;
do
{
bytesRead = fileStream1.Read(buffer1, 0, buffer1.Length);
if (fileStream2.Read(buffer2, 0, buffer2.Length) != bytesRead)
{
// We should never get here since we compared file lengths, but
// this is a sanity check.
return false;
}
for (int i = 0; i < bytesRead; i++)
{
if (buffer1[i] != buffer2[i])
{
return false;
}
}
} while (bytesRead == buffer1.Length);
}
}

return true;
}
if (new FileInfo(file1).Length != new FileInfo(file2).Length) return false;

/// <summary>
/// Tests whether a file is up to date with respect to another,
/// based on existence, last write time and file size.
/// </summary>
/// <param name="sourcePath">The source path.</param>
/// <param name="destPath">The dest path.</param>
/// <returns><c>true</c> if the files are the same; <c>false</c> if the files are different</returns>
internal static bool FastFileEqualityCheck(string sourcePath, string destPath)
{
FileInfo sourceInfo = new FileInfo(sourcePath);
FileInfo destInfo = new FileInfo(destPath);
// If both are present, we need to do a content comparison.
// Keep our comparison simple by loading both in memory.
byte[] file1Content = File.ReadAllBytes(file1);
byte[] file2Content = File.ReadAllBytes(file2);

if (sourceInfo.Exists ^ destInfo.Exists)
{
// Either the source file or the destination file is missing.
return false;
}
// One more sanity check.
if (file1Content.Length != file2Content.Length) return false;

if (!sourceInfo.Exists)
for (int i = 0; i < file1Content.Length; i++)
{
// Neither file exists.
return true;
if (file1Content[i] != file2Content[i]) return false;
}

// We'll say the files are the same if their modification date and length are the same.
return
sourceInfo.LastWriteTimeUtc == destInfo.LastWriteTimeUtc &&
sourceInfo.Length == destInfo.Length;
return true;
}
}
}