aboutsummaryrefslogtreecommitdiff
path: root/src/tools/Dtf/DDiff/TextFileDiffEngine.cs
blob: beb5ea84438262d7271135d504bcbc00b5aaec1d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// Copyright (c) .NET Foundation and contributors. All rights reserved. Licensed under the Microsoft Reciprocal License. See LICENSE.TXT file in the project root for full license information.

using System;
using System.IO;
using System.Diagnostics;

namespace WixToolset.Dtf.Tools.DDiff
{
	public class TextFileDiffEngine : IDiffEngine
	{
		public TextFileDiffEngine()
		{
		}

		private bool IsTextFile(string file)
		{
			// Guess whether this is a text file by reading the first few bytes and checking for non-ascii chars.

			bool isText = true;
			FileStream stream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read);
			byte[] buf = new byte[256];
			int count = stream.Read(buf, 0, buf.Length);
			for(int i = 0; i < count; i++)
			{
				if((buf[i] & 0x80) != 0)
				{
					isText = false;
					break;
				}
			}
			stream.Close();
			return isText;
		}

		public float GetDiffQuality(string diffInput1, string diffInput2, string[] options, IDiffEngineFactory diffFactory)
		{
			if(diffInput1 != null && File.Exists(diffInput1) &&
				diffInput2 != null && File.Exists(diffInput2) &&
				(IsTextFile(diffInput1) && IsTextFile(diffInput2)))
			{
				return .70f;
			}
			else
			{
				return 0;
			}
		}

		public bool GetDiff(string diffInput1, string diffInput2, string[] options, TextWriter diffOutput, string linePrefix, IDiffEngineFactory diffFactory)
		{
			try
			{
				bool difference = false;
				ProcessStartInfo psi = new ProcessStartInfo("diff.exe");
				psi.Arguments = String.Format("\"{0}\" \"{1}\"", diffInput1, diffInput2);
				psi.WorkingDirectory = null;
				psi.UseShellExecute = false;
				psi.WindowStyle = ProcessWindowStyle.Hidden;
				psi.RedirectStandardOutput = true;
				Process proc = Process.Start(psi);

				string line;
				while((line = proc.StandardOutput.ReadLine()) != null)
				{
					diffOutput.WriteLine("{0}{1}", linePrefix, line);
					difference = true;
				}

				proc.WaitForExit();
				return difference;
			}
			catch(System.ComponentModel.Win32Exception)  // If diff.exe is not found, just compare the bytes
			{
				return new FileDiffEngine().GetDiff(diffInput1, diffInput2, options, diffOutput, linePrefix, diffFactory);
			}
		}

		public IDiffEngine Clone()
		{
			return new TextFileDiffEngine();
		}
	}
}