forked from unoplatform/uno
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
389 lines (326 loc) · 15.5 KB
/
Copy pathProgram.cs
File metadata and controls
389 lines (326 loc) · 15.5 KB
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media.Imaging;
using Uno.UI.TestComparer;
namespace Umbrella.UI.TestComparer
{
class Program
{
static void Main(string[] args)
{
if (args[0] == "appcenter")
{
if (args.Length != 4)
{
Console.WriteLine("tc [base path] [run limit] [api key]");
return;
}
var basePath = args[1];
var runLimit = int.Parse(args[2]);
var apiKey = args[3];
new AppCenterTestsDownloader(apiKey).Download(apiKey, basePath, runLimit).Wait();
ProcessFiles(args, basePath, "ios");
ProcessFiles(args, basePath, "Android");
}
else if (args[0] == "azdo")
{
var pat = args[1];
var basePath = args[2];
var targetBranch = !string.IsNullOrEmpty(args[3]) ? args[3] : "refs/heads/master"; // System.PullRequest.TargetBranch
var artifactName = args[4];
var definitionName = args[5]; // Build.DefinitionName
var projectName = args[6]; // System.TeamProject
var serverUri = args[7]; // System.TeamFoundationCollectionUri
var currentBuild = int.Parse(args[8]); // Build.BuildId
var runLimit = int.Parse(args[9]);
var downloader = new AzureDevopsDownloader(pat, serverUri);
downloader.DownloadArtifacts(Path.Combine(basePath, "wasm"), projectName, definitionName, artifactName, targetBranch, currentBuild, runLimit).Wait();
ProcessFiles(args, basePath, "wasm");
}
else if (args[0] == "compare")
{
var leftPath = args[0];
var rightPath = args[1];
var outputPath = args[2];
var q = from leftFilePath in Directory.EnumerateFiles(leftPath, "*.png")
let leftFileName = Path.GetFileName(leftFilePath)
join rightFilePath in Directory.EnumerateFiles(rightPath, "*.png") on leftFileName equals Path.GetFileName(rightFilePath) into gj
from pair in gj.DefaultIfEmpty()
select new
{
LeftPath = leftFilePath,
RightPath = pair
};
using (var file = new StreamWriter(outputPath))
{
file.Write("<html><body>");
file.Write("<table>");
foreach (var pair in q)
{
var areValidFiles = pair.LeftPath != null && pair.RightPath != null;
var areEqual = areValidFiles ?
File.ReadAllBytes(pair.LeftPath).SequenceEqual(File.ReadAllBytes(pair.RightPath))
: false;
if (!areEqual)
{
file.Write("<tr>");
file.Write("<td>");
file.Write($"<img src=\"file:///{pair.LeftPath}\" width=400 height=400 />");
file.Write("</td>");
file.Write("<td>");
file.Write($"<img src=\"file:///{pair.RightPath}\" width=400 height=400 />");
file.Write("</td>");
file.Write("</tr>");
}
}
file.Write("</table>");
file.Write("</body></html>");
}
}
}
private static void ProcessFiles(string[] args, string basePath, string platform)
{
string path = Path.Combine(basePath, platform);
var resultsId = $"{DateTime.Now:yyyyMMdd-hhmmss}";
string diffPath = Path.Combine(basePath, $"Results-{platform}-{resultsId}");
string resultsFilePath = Path.Combine(basePath, $"Results-{platform}-{resultsId}.html");
Directory.CreateDirectory(path);
Directory.CreateDirectory(diffPath);
var q1 = from directory in Directory.EnumerateDirectories(path)
let info = new DirectoryInfo(directory)
orderby info.CreationTime descending
select directory;
q1 = q1.ToArray();
var orderedDirectories = from directory in q1
orderby directory
select directory;
var q = from directory in orderedDirectories.Select((v, i) => new { Index = i, Path = v })
let files = from sample in EnumerateFiles(Path.Combine(directory.Path, ""), "*.png").AsParallel()
select new { File = sample, Id = BuildSha1(sample) }
select new
{
Path = directory.Path,
Index = directory.Index,
Files = files.ToArray(),
};
var allFolders = LogForeach(q, i => Console.WriteLine($"Processed {i.Path}")).ToArray();
var allFiles = allFolders
.SelectMany(folder => folder
.Files.Select(file => Path.GetFileName(file.File))
)
.Distinct()
.ToArray();
var sb = new StringBuilder();
sb.AppendLine("<html><body>");
sb.AppendLine("<p>How to read this table:</p>");
sb.AppendLine("<ul>");
sb.AppendLine("<li>This tool compares the binary content of successive runs screenshots of the same test output</li>");
sb.AppendLine("<li>Each line represents a test result screen shot.</li>");
sb.AppendLine("<li>Each cell number represent an unique image ID.</li>");
sb.AppendLine("<li>A red cell means the image has changed from the previous run (not that the results are incorrect).</li>");
sb.AppendLine("<li>Subtle changes can be visualized using a XOR filtering between images</li>");
sb.AppendLine("</ul>");
sb.AppendLine("<ul>");
foreach (var folder in allFolders)
{
sb.AppendLine($"<li>{folder.Index}: {folder.Path}</li>");
}
sb.AppendLine("</ul>");
sb.AppendLine("<table>");
sb.AppendLine("<tr><td/>");
foreach (var folder in allFolders)
{
sb.AppendLine($"<td>{folder.Index}</td>");
}
sb.AppendLine("</tr>");
int unchanged = 0;
foreach (var testFile in allFiles)
{
var testFileIncrements = from folder in allFolders
orderby folder.Index ascending
select new
{
Folder = folder.Path,
FolderIndex = folder.Index,
Files = new[] {
new { FileInfo = folder.Files.FirstOrDefault(f => Path.GetFileName(f.File) == testFile) }
}
};
var increments =
(
from platformIndex in Enumerable.Range(0, 1)
select testFileIncrements
.Aggregate(
new[] { new { FolderIndex = -1, Path = "", IdSha = "", Id = -1, CompareeId = -1 } },
(a, f) =>
{
var platformFiles = f.Files[platformIndex];
if (platformFiles?.FileInfo == null)
{
return a;
}
var otherMatch = a.Reverse().Where(i => i.IdSha != null).FirstOrDefault();
if (platformFiles.FileInfo?.Id.sha != otherMatch?.IdSha)
{
return a
.Concat(new[] { new { FolderIndex = f.FolderIndex, Path = platformFiles.FileInfo.File, IdSha = platformFiles.FileInfo?.Id.sha, Id = platformFiles.FileInfo?.Id.index ?? -1, CompareeId = otherMatch.Id } })
.ToArray();
}
else
{
return a
.Concat(new[] { new { FolderIndex = f.FolderIndex, Path = platformFiles.FileInfo.File, IdSha = (string)null, Id = platformFiles.FileInfo.Id.index, CompareeId = -1 } })
.ToArray();
}
}
)
).ToArray();
var hasChanges = increments.Any(i => i.Where(v => v.IdSha != null).Count() - 1 > 1);
if (hasChanges)
{
sb.AppendLine($"<tr rowspan=\"3\"><td>{testFile}</td></tr>");
for (int platformIndex = 0; platformIndex < 1; platformIndex++)
{
sb.AppendLine("<tr>");
sb.AppendLine($"<td></td>");
if (increments[platformIndex].Count() > 1)
{
var firstFolder = increments[platformIndex].Where(i => i.FolderIndex != -1).Min(i => i.FolderIndex);
for (int folderIndex = 0; folderIndex < allFolders.Length; folderIndex++)
{
var folderInfo = increments[platformIndex].FirstOrDefault(inc => inc.FolderIndex == folderIndex);
var hasChanged = folderIndex != firstFolder && folderInfo?.IdSha != null;
var color = folderInfo == null ? "#555" : hasChanged ? "#f00" : "#0f0";
sb.AppendLine($"<td bgcolor=\"{color}\" width=20 height=20>");
if (folderInfo != null)
{
var relativePath = folderInfo.Path.Replace(basePath, "").Replace("\\", "/").TrimStart('/');
sb.AppendLine($"<a href=\"{relativePath}\">{folderInfo.Id}</a><!--{folderInfo.IdSha}-->");
var previousFolderInfo = increments[platformIndex].FirstOrDefault(inc => inc.FolderIndex == folderIndex - 1);
if (hasChanged && previousFolderInfo != null)
{
var currentImage = DecodeImage(folderInfo.Path);
var previousImage = DecodeImage(previousFolderInfo.Path);
var diff = DiffImages(currentImage.pixels, previousImage.pixels);
var diffFilePath = Path.Combine(diffPath, $"{folderInfo.Id}-{folderInfo.CompareeId}.png");
WriteImage(diffFilePath, diff, currentImage.frame);
var diffRelativePath = diffFilePath.Replace(basePath, "").Replace("\\", "/").TrimStart('/');
sb.AppendLine($"<a href=\"{diffRelativePath}\">D</a>");
}
else
{
sb.AppendLine($"D");
}
}
sb.AppendLine("</td>");
}
}
sb.AppendLine("</tr>");
}
}
else
{
unchanged++;
}
}
sb.AppendLine("</table>");
sb.AppendLine($"{unchanged} samples unchanged, {allFiles.Length} files total.");
sb.AppendLine("</body></html>");
File.WriteAllText(resultsFilePath, sb.ToString());
Console.WriteLine($"{platform}: {unchanged} samples unchanged, {allFiles.Length} files total.");
}
private static void WriteImage(string diffPath, byte[] diff, BitmapFrame frameInfo)
{
using (var stream = new FileStream(diffPath, FileMode.Create))
{
var encoder = new PngBitmapEncoder();
encoder.Interlace = PngInterlaceOption.On;
var frame = BitmapSource.Create(
pixelWidth: (int)frameInfo.Width,
pixelHeight: (int)frameInfo.Height,
dpiX: frameInfo.DpiX,
dpiY: frameInfo.DpiY,
pixelFormat: frameInfo.Format,
palette: frameInfo.Palette,
pixels: diff,
stride: (int)(frameInfo.Width * 4)
);
encoder.Frames.Add(BitmapFrame.Create(frame));
encoder.Save(stream);
}
}
private static byte[] DiffImages(byte[] currentImage, byte[] previousImage)
{
var result = new byte[currentImage.Length];
for (int i = 0; i < result.Length; i++)
{
result[i] = (byte)(currentImage[i] ^ previousImage[i]);
}
return result;
}
private static (BitmapFrame frame, byte[] pixels) DecodeImage(string path1)
{
Stream imageStreamSource = new FileStream(path1, FileMode.Open, FileAccess.Read, FileShare.Read);
var decoder = new PngBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
byte[] image = new byte[(int)(decoder.Frames[0].Width * decoder.Frames[0].Height * 4)];
decoder.Frames[0].CopyPixels(image, (int)(decoder.Frames[0].Width * 4), 0);
return (decoder.Frames[0], image);
}
private static IEnumerable<string> EnumerateFiles(string path, string pattern)
{
if (Directory.Exists(path))
{
return Directory.EnumerateFiles(path, pattern, SearchOption.AllDirectories);
}
else
{
return new string[0];
}
}
private static IEnumerable<T> LogForeach<T>(IEnumerable<T> q, Action<T> action)
{
foreach (var item in q)
{
action(item);
yield return item;
}
}
static Dictionary<string, int> _fileHashesTable = new Dictionary<string, int>();
private static (string sha, int index) BuildSha1(string sample)
{
// return "000";
using (var sha1 = SHA1.Create())
{
using (var file = File.OpenRead(sample))
{
var data = sha1.ComputeHash(file);
// Create a new Stringbuilder to collect the bytes
// and create a string.
var sBuilder = new StringBuilder();
// Loop through each byte of the hashed data
// and format each one as a hexadecimal string.
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data[i].ToString("x2", CultureInfo.InvariantCulture));
}
var sha = sBuilder.ToString();
lock (_fileHashesTable)
{
if (!_fileHashesTable.TryGetValue(sha, out var index))
{
index = _fileHashesTable.Count;
_fileHashesTable[sha] = index;
}
return (sha, index);
}
}
}
}
}
}