Repository navigation
Expand file tree
/
Copy pathMSBuildTargetsTests.cs
More file actions
756 lines (663 loc) · 33.1 KB
/
Copy pathMSBuildTargetsTests.cs
File metadata and controls
756 lines (663 loc) · 33.1 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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------------------------------------------*/
using System.Collections.Concurrent;
using System.Diagnostics;
using System.IO.Compression;
using System.Net;
using System.Net.Sockets;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
using System.Text;
using Xunit;
namespace GitHub.Copilot.Test.Unit;
/// <summary>
/// Integration tests for the MSBuild targets shipped in
/// <c>dotnet/src/build/GitHub.Copilot.SDK.targets</c>. Each test creates a throwaway
/// project that imports the targets file directly and invokes <c>dotnet build</c> in
/// a subprocess so we exercise real MSBuild evaluation.
/// </summary>
/// <remarks>
/// Download tests use a loopback release server; they never access the default GitHub URL.
/// </remarks>
public class MSBuildTargetsTests
{
private static readonly string TargetsFilePath = FindTargetsFile();
private static readonly string BinaryName = OperatingSystem.IsWindows() ? "copilot.exe" : "copilot";
private static readonly string RuntimeWrapperName =
OperatingSystem.IsWindows() ? "copilot-runtime.exe" : "copilot-runtime";
private static readonly string RuntimeLibraryName =
OperatingSystem.IsWindows() ? "copilot_runtime.dll"
: OperatingSystem.IsMacOS() ? "libcopilot_runtime.dylib"
: "libcopilot_runtime.so";
[Fact]
public async Task PreinstalledCliBinaryPath_IsHonored_DownloadSkipped_AndCopiedToOutput()
{
using var sandbox = MSBuildSandbox.Create();
var preinstalled = sandbox.WritePreinstalledBinary("fake-cli-contents");
var result = await sandbox.BuildAsync(new Dictionary<string, string>
{
["CopilotCliBinaryPath"] = preinstalled,
});
Assert.True(result.Succeeded, result.FailureMessage());
// Download message must be absent because the download target was skipped.
Assert.DoesNotContain("Downloading Copilot CLI", result.StandardOutput, StringComparison.Ordinal);
// Binary must be placed at the canonical runtimes path so Client.cs can locate it.
var outputPath = sandbox.ExpectedOutputBinary();
Assert.True(File.Exists(outputPath), $"Expected CLI to be copied to '{outputPath}'.\n{result.FailureMessage()}");
Assert.Equal(File.ReadAllText(preinstalled), File.ReadAllText(outputPath));
Assert.True(File.Exists(Path.Combine(Path.GetDirectoryName(outputPath)!, ".copilot-explicit-cli")));
}
[Fact]
public async Task PreinstalledCliBinaryPath_NormalizesNonStandardFileNameToCanonical()
{
using var sandbox = MSBuildSandbox.Create();
// Use an off-spec source filename to confirm the copy task renames it to copilot[.exe].
var preinstalled = sandbox.WritePreinstalledBinary("custom-named", fileName: "my-copilot-binary-v1.bin");
var result = await sandbox.BuildAsync(new Dictionary<string, string>
{
["CopilotCliBinaryPath"] = preinstalled,
});
Assert.True(result.Succeeded, result.FailureMessage());
var outputPath = sandbox.ExpectedOutputBinary();
Assert.True(File.Exists(outputPath), $"Expected canonical binary at '{outputPath}'.\n{result.FailureMessage()}");
}
[Fact]
public async Task SkipCliDownload_WithoutBinaryPath_ProducesNoBinaryAndSucceeds()
{
using var sandbox = MSBuildSandbox.Create();
var result = await sandbox.BuildAsync(new Dictionary<string, string>
{
["CopilotSkipCliDownload"] = "true",
});
Assert.True(result.Succeeded, result.FailureMessage());
// The runtimes folder may or may not be created by something else, but the binary
// itself must not exist.
Assert.False(File.Exists(sandbox.ExpectedOutputBinary()),
$"Expected no CLI binary in output when CopilotSkipCliDownload=true and no path supplied.\n{result.FailureMessage()}");
// Download must also have been skipped.
Assert.DoesNotContain("Downloading Copilot CLI", result.StandardOutput, StringComparison.Ordinal);
}
[Fact]
public async Task PreinstalledCliBinaryPath_WithSkipCliDownload_StillCopiesToOutput()
{
using var sandbox = MSBuildSandbox.Create();
var preinstalled = sandbox.WritePreinstalledBinary("fake-cli-contents");
var result = await sandbox.BuildAsync(new Dictionary<string, string>
{
["CopilotCliBinaryPath"] = preinstalled,
["CopilotSkipCliDownload"] = "true",
});
Assert.True(result.Succeeded, result.FailureMessage());
Assert.True(File.Exists(sandbox.ExpectedOutputBinary()), result.FailureMessage());
}
[Fact]
public async Task ReleaseAsset_IsDownloadedVerifiedExtractedAndCached()
{
using var sandbox = MSBuildSandbox.Create();
var archive = sandbox.CreateReleaseArchive("release-runtime-wrapper");
var assetName = $"github-copilot-0.0.0-test-{GetReleasePlatform()}.tgz";
var assetPath = $"/v0.0.0-test/{assetName}";
var checksumsPath = "/v0.0.0-test/SHA256SUMS.txt";
var checksum = ComputeSha256(archive);
using var server = new ReleaseServer(new Dictionary<string, byte[]>
{
[checksumsPath] = Encoding.UTF8.GetBytes($"{checksum} {assetName}\n"),
[assetPath] = archive,
});
var properties = new Dictionary<string, string>
{
["CopilotCliReleaseBaseUrl"] = server.BaseUrl,
};
var firstBuild = await sandbox.BuildAsync(properties);
Assert.True(firstBuild.Succeeded, firstBuild.FailureMessage());
Assert.Equal("release-runtime-wrapper", File.ReadAllText(sandbox.ExpectedOutputBinary()));
Assert.Equal("release-runtime-wrapper", File.ReadAllText(sandbox.ExpectedRuntimeAsset(RuntimeWrapperName)));
Assert.Equal("runtime", File.ReadAllText(sandbox.ExpectedRuntimeAsset("runtime.node")));
Assert.True(File.Exists(sandbox.ExpectedCacheAsset(".copilot-runtime-complete")));
Assert.False(File.Exists(sandbox.ExpectedRuntimeAsset(".copilot-runtime-complete")));
Assert.Equal(1, server.RequestPaths.Count(path => path == checksumsPath));
Assert.Equal(1, server.RequestPaths.Count(path => path == assetPath));
Assert.False(File.Exists(sandbox.ExpectedRuntimeAsset("SHA256SUMS.txt")));
var secondBuild = await sandbox.BuildAsync(properties);
Assert.True(secondBuild.Succeeded, secondBuild.FailureMessage());
Assert.Equal(2, server.RequestPaths.Count);
}
[Fact]
public async Task IncompleteCache_WithRuntimePairButNoMarker_IsReacquired()
{
using var sandbox = MSBuildSandbox.Create();
sandbox.WriteRuntimeCacheAsset("prebuilds", GetReleasePlatform(), RuntimeWrapperName, "partial-wrapper");
sandbox.WriteRuntimeCacheAsset("prebuilds", GetReleasePlatform(), "runtime.node", "partial-runtime");
sandbox.WriteRuntimeCacheAsset("definitions", "stale.json", "stale");
var archive = sandbox.CreateReleaseArchive("complete-wrapper");
var assetName = $"github-copilot-0.0.0-test-{GetReleasePlatform()}.tgz";
var assetPath = $"/v0.0.0-test/{assetName}";
var checksumsPath = "/v0.0.0-test/SHA256SUMS.txt";
using var server = new ReleaseServer(new Dictionary<string, byte[]>
{
[checksumsPath] = Encoding.UTF8.GetBytes($"{ComputeSha256(archive)} {assetName}\n"),
[assetPath] = archive,
});
var result = await sandbox.BuildAsync(new Dictionary<string, string>
{
["CopilotCliReleaseBaseUrl"] = server.BaseUrl,
});
Assert.True(result.Succeeded, result.FailureMessage());
Assert.Equal(1, server.RequestPaths.Count(path => path == checksumsPath));
Assert.Equal(1, server.RequestPaths.Count(path => path == assetPath));
Assert.Equal("complete-wrapper", File.ReadAllText(sandbox.ExpectedRuntimeAsset(RuntimeWrapperName)));
Assert.Equal("runtime", File.ReadAllText(sandbox.ExpectedRuntimeAsset("runtime.node")));
Assert.True(File.Exists(sandbox.ExpectedCacheAsset(".copilot-runtime-complete")));
Assert.False(File.Exists(sandbox.ExpectedCacheAsset("definitions", "stale.json")));
Assert.False(File.Exists(sandbox.ExpectedRuntimeAsset("definitions", "stale.json")));
}
[Fact]
public async Task ReleaseAsset_WithChecksumMismatch_FailsBeforeExtraction()
{
using var sandbox = MSBuildSandbox.Create();
var archive = Encoding.UTF8.GetBytes("not the expected archive");
var assetName = $"github-copilot-0.0.0-test-{GetReleasePlatform()}.tgz";
using var server = new ReleaseServer(new Dictionary<string, byte[]>
{
["/v0.0.0-test/SHA256SUMS.txt"] =
Encoding.UTF8.GetBytes($"{new string('0', 64)} *{assetName}\n"),
[$"/v0.0.0-test/{assetName}"] = archive,
});
var result = await sandbox.BuildAsync(new Dictionary<string, string>
{
["CopilotCliReleaseBaseUrl"] = server.BaseUrl,
});
Assert.False(result.Succeeded, "Build should fail when the release checksum does not match.");
Assert.Contains($"Checksum mismatch for {assetName}", result.StandardOutput, StringComparison.Ordinal);
Assert.False(File.Exists(sandbox.ExpectedOutputBinary()));
}
[Fact]
public async Task RuntimePackageAssets_AreFilteredAndCopiedToOutput()
{
using var sandbox = MSBuildSandbox.Create();
var preinstalled = sandbox.WritePreinstalledBinary("fake-cli-contents");
sandbox.WriteRuntimeCacheAsset("prebuilds", GetReleasePlatform(), "runtime.node", "runtime");
sandbox.WriteRuntimeCacheAsset("prebuilds", GetReleasePlatform(),
RuntimeWrapperName, "wrapper");
sandbox.WriteRuntimeCacheAsset("ripgrep", "bin", GetReleasePlatform(), "rg", "ripgrep");
sandbox.WriteRuntimeCacheAsset("definitions", "future.json", "{}");
sandbox.WriteRuntimeCacheAsset("copilot-sdk", "extension.js", "extension");
sandbox.WriteRuntimeCacheAsset("preloads", "extension_bootstrap.mjs", "preload");
sandbox.WriteRuntimeCacheAsset("sdk", "factory.js", "factory");
sandbox.WriteRuntimeCacheAsset("app.js", "excluded");
sandbox.WriteRuntimeCacheAsset("LICENSE.md", "excluded");
sandbox.WriteRuntimeCacheAsset("README.md", "excluded");
sandbox.WriteStaleOutputRuntimeAsset("obsolete", "tool", "stale");
var result = await sandbox.BuildAsync(new Dictionary<string, string>
{
["CopilotCliBinaryPath"] = preinstalled,
});
Assert.True(result.Succeeded, result.FailureMessage());
Assert.Equal("ripgrep", File.ReadAllText(sandbox.ExpectedRuntimeAsset("ripgrep", "bin", GetReleasePlatform(), "rg")));
Assert.Equal("{}", File.ReadAllText(sandbox.ExpectedRuntimeAsset("definitions", "future.json")));
Assert.Equal("extension", File.ReadAllText(sandbox.ExpectedRuntimeAsset("copilot-sdk", "extension.js")));
Assert.Equal("preload", File.ReadAllText(sandbox.ExpectedRuntimeAsset("preloads", "extension_bootstrap.mjs")));
Assert.Equal("factory", File.ReadAllText(sandbox.ExpectedRuntimeAsset("sdk", "factory.js")));
Assert.False(File.Exists(sandbox.ExpectedRuntimeAsset("app.js")));
Assert.False(File.Exists(sandbox.ExpectedRuntimeAsset("LICENSE.md")));
Assert.False(File.Exists(sandbox.ExpectedRuntimeAsset("README.md")));
Assert.False(File.Exists(sandbox.ExpectedRuntimeAsset("obsolete", "tool")));
}
[Fact]
public async Task PackAsTool_NoBuild_IncludesRuntimeAssetsInToolPackage()
{
using var sandbox = MSBuildSandbox.Create(packAsTool: true);
var preinstalled = sandbox.WritePreinstalledBinary("fake-cli-contents");
sandbox.WriteRuntimeCacheAsset("prebuilds", GetReleasePlatform(), "runtime.node", "runtime");
sandbox.WriteRuntimeCacheAsset("prebuilds", GetReleasePlatform(), RuntimeWrapperName, "wrapper");
sandbox.WriteRuntimeCacheAsset("ripgrep", "bin", GetReleasePlatform(), "rg", "ripgrep");
var result = await sandbox.PackNoBuildAsync(new Dictionary<string, string>
{
["CopilotCliBinaryPath"] = preinstalled,
});
Assert.True(result.Succeeded, result.FailureMessage());
var rid = MSBuildSandbox.GetPortableRid();
var entries = sandbox.GetPackageEntries();
var nativePath = $"tools/net8.0/{rid}/runtimes/{rid}/native";
Assert.Contains($"{nativePath}/{BinaryName}", entries);
Assert.Contains($"{nativePath}/{RuntimeWrapperName}", entries);
Assert.Contains($"{nativePath}/runtime.node", entries);
Assert.Contains($"{nativePath}/{RuntimeLibraryName}", entries);
Assert.Contains($"{nativePath}/ripgrep/bin/{GetReleasePlatform()}/rg", entries);
}
[Fact]
public async Task PackAsTool_NoBuild_PublishesExplicitCliMarker()
{
using var sandbox = MSBuildSandbox.Create(packAsTool: true);
var preinstalled = sandbox.WritePreinstalledBinary("fake-cli-contents");
var result = await sandbox.PackNoBuildAsync(new Dictionary<string, string>
{
["CopilotCliBinaryPath"] = preinstalled,
});
Assert.True(result.Succeeded, result.FailureMessage());
// The marker is what CopilotClient uses to launch an explicit CLI without
// requiring the runtime pair, so it has to survive into the publish layout
// the tool package is built from. NuGet's default dot-file exclusion keeps
// it out of the .nupkg itself, which is a separate pre-existing limitation.
Assert.True(File.Exists(sandbox.PublishedRuntimeAsset(".copilot-explicit-cli")),
"The explicit-CLI marker must reach the publish layout.");
Assert.True(File.Exists(sandbox.PublishedRuntimeAsset(BinaryName)));
}
[Fact]
public async Task PreinstalledCliBinaryPath_NonExistentFile_FailsWithActionableError()
{
using var sandbox = MSBuildSandbox.Create();
var nonexistent = Path.Combine(sandbox.ProjectDir, "does-not-exist", BinaryName);
var result = await sandbox.BuildAsync(new Dictionary<string, string>
{
["CopilotCliBinaryPath"] = nonexistent,
});
Assert.False(result.Succeeded, "Build should have failed when CopilotCliBinaryPath points at a missing file.");
Assert.Contains("Copilot CLI binary not found", result.StandardOutput, StringComparison.Ordinal);
Assert.Contains(nonexistent, result.StandardOutput, StringComparison.Ordinal);
}
private static string FindTargetsFile([CallerFilePath] string? thisFile = null)
{
// thisFile == <repo>/dotnet/test/Unit/MSBuildTargetsTests.cs
if (thisFile is not null && File.Exists(thisFile))
{
var candidate = Path.GetFullPath(Path.Combine(
Path.GetDirectoryName(thisFile)!, "..", "..", "src", "build", "GitHub.Copilot.SDK.targets"));
if (File.Exists(candidate))
{
return candidate;
}
}
// Fall back to walking up from the test assembly location.
var dir = AppContext.BaseDirectory;
for (var i = 0; i < 8 && dir is not null; i++)
{
var candidate = Path.Combine(dir, "src", "build", "GitHub.Copilot.SDK.targets");
if (File.Exists(candidate))
{
return candidate;
}
dir = Path.GetDirectoryName(dir);
}
throw new InvalidOperationException(
"Could not locate GitHub.Copilot.SDK.targets relative to test assembly or source file.");
}
private static string GetReleasePlatform()
{
var arch = System.Runtime.InteropServices.RuntimeInformation.ProcessArchitecture
== System.Runtime.InteropServices.Architecture.Arm64
? "arm64"
: "x64";
if (OperatingSystem.IsWindows()) return $"win32-{arch}";
if (OperatingSystem.IsMacOS()) return $"darwin-{arch}";
var platform = IsMusl() ? "linuxmusl" : "linux";
return $"{platform}-{arch}";
}
private static bool IsMusl()
{
#if NETFRAMEWORK
return false;
#else
return System.Runtime.InteropServices.RuntimeInformation.RuntimeIdentifier.StartsWith(
"linux-musl-",
StringComparison.Ordinal);
#endif
}
private static string ComputeSha256(byte[] contents)
{
#if NETFRAMEWORK
using var sha256 = SHA256.Create();
return BitConverter.ToString(sha256.ComputeHash(contents)).Replace("-", "").ToLowerInvariant();
#else
return Convert.ToHexString(SHA256.HashData(contents)).ToLowerInvariant();
#endif
}
/// <summary>
/// A throwaway directory containing a minimal csproj that imports the SDK targets
/// file. Disposing removes the directory tree.
/// </summary>
private sealed class MSBuildSandbox : IDisposable
{
public string ProjectDir { get; }
private MSBuildSandbox(string projectDir)
{
ProjectDir = projectDir;
}
public static MSBuildSandbox Create(bool packAsTool = false)
{
var dir = Path.Combine(Path.GetTempPath(), "copilot-sdk-targets-test-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(dir);
// Tool packages are produced from the publish layout, so the tool variant
// exercises the packaging path reported in issue #2067.
var toolProperties = packAsTool
? $"""
<OutputType>Exe</OutputType>
<PackAsTool>true</PackAsTool>
<PackageId>CopilotSdkTargetsTest.Tool</PackageId>
<Version>1.0.0</Version>
<ToolCommandName>copilot-sdk-targets-test</ToolCommandName>
<RuntimeIdentifiers>{GetPortableRid()}</RuntimeIdentifiers>
<SelfContained>false</SelfContained>
<UseAppHost>false</UseAppHost>
"""
: string.Empty;
// Pin the RID for every sandbox build. Left unpinned, the targets fall
// back to the spawned SDK's own RID, which need not match the test
// process — so an emulated run would build for one architecture while
// GetReleasePlatform() seeded the cache for another.
var csproj = $"""
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<RuntimeIdentifier>{GetPortableRid()}</RuntimeIdentifier>
<AppendRuntimeIdentifierToOutputPath>false</AppendRuntimeIdentifierToOutputPath>
<CopilotCliVersion>0.0.0-test</CopilotCliVersion>
<EnableDefaultCompileItems>true</EnableDefaultCompileItems>{toolProperties}
</PropertyGroup>
<Import Project="{TargetsFilePath}" />
</Project>
""";
File.WriteAllText(Path.Combine(dir, "App.csproj"), csproj);
File.WriteAllText(
Path.Combine(dir, "Stub.cs"),
packAsTool
? "namespace CopilotSdkTargetsTest { internal static class Stub { private static void Main() { } } }\n"
: "namespace CopilotSdkTargetsTest { internal static class Stub { } }\n");
return new MSBuildSandbox(dir);
}
public string WritePreinstalledBinary(string contents, string? fileName = null)
{
var preinstallDir = Path.Combine(ProjectDir, "preinstall");
Directory.CreateDirectory(preinstallDir);
// Strip any path information from fileName so it cannot escape preinstallDir.
var safeFileName = string.IsNullOrEmpty(fileName) ? BinaryName : Path.GetFileName(fileName);
var path = Path.Combine(preinstallDir, safeFileName);
File.WriteAllText(path, contents);
return path;
}
public byte[] CreateReleaseArchive(string runtimeWrapperContents)
{
var sourceDir = Path.Combine(ProjectDir, "release-source");
var packageDir = Path.Combine(sourceDir, "package");
var prebuildDir = Path.Combine(packageDir, "prebuilds", GetReleasePlatform());
Directory.CreateDirectory(prebuildDir);
File.WriteAllText(Path.Combine(prebuildDir, "runtime.node"), "runtime");
File.WriteAllText(Path.Combine(prebuildDir, RuntimeWrapperName), runtimeWrapperContents);
var archivePath = Path.Combine(ProjectDir, "release-asset.tgz");
var tarPath = OperatingSystem.IsWindows()
? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "System32", "tar.exe")
: "tar";
var startInfo = new ProcessStartInfo(tarPath)
{
Arguments = $"-czf \"{archivePath}\" -C \"{sourceDir}\" package",
RedirectStandardError = true,
UseShellExecute = false,
};
using var process = Process.Start(startInfo) ??
throw new InvalidOperationException("Failed to start tar while creating a release test asset.");
var standardError = process.StandardError.ReadToEnd();
process.WaitForExit();
if (process.ExitCode != 0)
{
throw new InvalidOperationException($"tar failed while creating a release test asset: {standardError}");
}
return File.ReadAllBytes(archivePath);
}
public string ExpectedOutputBinary()
{
var rid = GetPortableRid();
return Path.Combine(ProjectDir, "bin", "Debug", "net8.0", "runtimes", rid, "native", BinaryName);
}
public void WriteRuntimeCacheAsset(params string[] pathAndContents)
{
var pathParts = pathAndContents.Take(pathAndContents.Length - 1).ToArray();
var path = ExpectedCacheAsset(pathParts);
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
File.WriteAllText(path, pathAndContents[^1]);
}
public string ExpectedCacheAsset(params string[] pathParts)
{
var path = Path.Combine(ProjectDir, "obj", "Debug", "net8.0", "copilot-cli", "0.0.0-test",
GetReleasePlatform());
foreach (var part in pathParts)
{
path = Path.Combine(path, part);
}
return path;
}
/// <summary>
/// A runtime asset in the publish layout, which is what tool packaging
/// consumes.
/// </summary>
public string PublishedRuntimeAsset(params string[] pathParts)
{
var rid = GetPortableRid();
var path = Path.Combine(ProjectDir, "bin", "Debug", "net8.0", rid, "publish", "runtimes", rid, "native");
foreach (var part in pathParts)
{
path = Path.Combine(path, part);
}
return path;
}
public string ExpectedRuntimeAsset(params string[] pathParts)
{
var path = Path.Combine(ProjectDir, "bin", "Debug", "net8.0", "runtimes", GetPortableRid(), "native");
foreach (var part in pathParts)
{
path = Path.Combine(path, part);
}
return path;
}
public void WriteStaleOutputRuntimeAsset(params string[] pathAndContents)
{
var relativeParts = pathAndContents.Take(pathAndContents.Length - 1).ToArray();
var path = ExpectedRuntimeAsset(relativeParts);
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
File.WriteAllText(path, pathAndContents[^1]);
var manifest = ExpectedRuntimeAsset(".copilot-runtime-assets");
Directory.CreateDirectory(Path.GetDirectoryName(manifest)!);
File.WriteAllText(
manifest,
string.Join(Path.DirectorySeparatorChar.ToString(), relativeParts) + Environment.NewLine);
}
public async Task<BuildResult> BuildAsync(IDictionary<string, string> properties) =>
await RunAsync("build --nologo -clp:NoSummary", properties);
/// <summary>
/// Builds, publishes, then packs without rebuilding — the tool packaging sequence
/// used by CI pipelines and reported in issue #2067.
/// </summary>
public async Task<BuildResult> PackNoBuildAsync(IDictionary<string, string> properties)
{
// Pin the configuration: build defaults to Debug while publish and pack default
// to Release, which would otherwise stage and read different output trees.
var rid = GetPortableRid();
var build = await RunAsync($"build --nologo -clp:NoSummary -c Debug -r {rid}", properties);
if (!build.Succeeded)
{
return build;
}
var publish = await RunAsync($"publish --nologo -clp:NoSummary -c Debug -r {rid}", properties);
if (!publish.Succeeded)
{
return publish;
}
return await RunAsync(
$"pack --nologo -clp:NoSummary -c Debug -r {rid} --no-build -o packages",
properties);
}
public List<string> GetPackageEntries()
{
var package = Directory.GetFiles(Path.Combine(ProjectDir, "packages"), "*.nupkg").Single();
using var stream = File.OpenRead(package);
using var archive = new ZipArchive(stream, ZipArchiveMode.Read);
return archive.Entries.Select(entry => entry.FullName).ToList();
}
private async Task<BuildResult> RunAsync(string command, IDictionary<string, string> properties)
{
var args = new StringBuilder(command);
foreach (var (key, value) in properties)
{
// Quote the value so paths with spaces are preserved.
args.Append(" /p:").Append(key).Append('=').Append('"').Append(value).Append('"');
}
var psi = new ProcessStartInfo("dotnet", args.ToString())
{
WorkingDirectory = ProjectDir,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true,
};
// Avoid inheriting the parent's MSBuildSDKsPath/RuntimeIdentifier from the
// running test host; the subprocess should resolve its own SDK and pick the
// RID that matches ExpectedOutputBinary().
psi.Environment.Remove("MSBuildSDKsPath");
psi.Environment.Remove("RuntimeIdentifier");
using var process = Process.Start(psi) ?? throw new InvalidOperationException("Failed to start dotnet build subprocess.");
// Drain both streams concurrently to avoid deadlocks on full pipe buffers.
var stdoutTask = process.StandardOutput.ReadToEndAsync();
var stderrTask = process.StandardError.ReadToEndAsync();
// Generous timeout: dotnet restore + build of an empty project on a slow CI
// worker can take ~60s the first time. We keep individual tests short by
// using minimal projects.
using var cts = new CancellationTokenSource(TimeSpan.FromMinutes(5));
try
{
await process.WaitForExitAsync(cts.Token);
}
catch (OperationCanceledException)
{
try { process.Kill(entireProcessTree: true); }
catch (InvalidOperationException) { /* process already exited */ }
catch (NotSupportedException) { /* not supported on this platform */ }
catch (System.ComponentModel.Win32Exception) { /* kill failed; best effort */ }
throw new TimeoutException($"dotnet did not complete within the timeout for args: {args}");
}
return new BuildResult(
ExitCode: process.ExitCode,
StandardOutput: await stdoutTask,
StandardError: await stderrTask,
CommandLine: $"dotnet {args}");
}
public void Dispose()
{
try { Directory.Delete(ProjectDir, recursive: true); }
catch (IOException) { /* cleanup is best effort */ }
catch (UnauthorizedAccessException) { /* cleanup is best effort */ }
}
public static string GetPortableRid()
{
// Must agree with GetReleasePlatform(), which names the seeded runtime cache:
// both describe the SDK actually running the build, so an emulated process
// (x64 on arm64) pins the RID it seeded assets for.
var arch = System.Runtime.InteropServices.RuntimeInformation.ProcessArchitecture;
if (OperatingSystem.IsWindows())
{
return arch switch
{
System.Runtime.InteropServices.Architecture.Arm64 => "win-arm64",
_ => "win-x64",
};
}
if (OperatingSystem.IsMacOS())
{
return arch switch
{
System.Runtime.InteropServices.Architecture.Arm64 => "osx-arm64",
_ => "osx-x64",
};
}
var os = IsMusl() ? "linux-musl" : "linux";
var architecture = arch switch
{
System.Runtime.InteropServices.Architecture.Arm64 => "arm64",
_ => "x64",
};
return $"{os}-{architecture}";
}
}
private sealed class ReleaseServer : IDisposable
{
private readonly IReadOnlyDictionary<string, byte[]> _responses;
private readonly TcpListener _listener = new(IPAddress.Loopback, 0);
private readonly CancellationTokenSource _cancellation = new();
private readonly Task _serverTask;
public ReleaseServer(IReadOnlyDictionary<string, byte[]> responses)
{
_responses = responses;
_listener.Start();
var endpoint = (IPEndPoint)_listener.LocalEndpoint;
BaseUrl = $"http://127.0.0.1:{endpoint.Port}";
_serverTask = ServeAsync();
}
public string BaseUrl { get; }
public ConcurrentQueue<string> RequestPaths { get; } = new();
public void Dispose()
{
_cancellation.Cancel();
_listener.Stop();
try { _serverTask.GetAwaiter().GetResult(); }
catch (OperationCanceledException) { }
_cancellation.Dispose();
}
private async Task ServeAsync()
{
while (!_cancellation.IsCancellationRequested)
{
TcpClient client;
try
{
client = await _listener.AcceptTcpClientAsync();
}
catch (ObjectDisposedException) when (_cancellation.IsCancellationRequested)
{
break;
}
catch (SocketException) when (_cancellation.IsCancellationRequested)
{
break;
}
await RespondAsync(client);
}
}
private async Task RespondAsync(TcpClient client)
{
using (client)
{
var stream = client.GetStream();
using var reader = new StreamReader(stream, Encoding.ASCII, false, 1024, leaveOpen: true);
var requestLine = await reader.ReadLineAsync();
string? header;
do
{
header = await reader.ReadLineAsync();
}
while (!string.IsNullOrEmpty(header));
var path = requestLine?.Split(' ', StringSplitOptions.RemoveEmptyEntries).ElementAtOrDefault(1) ?? "";
RequestPaths.Enqueue(path);
var found = _responses.TryGetValue(path, out var body);
body ??= Encoding.UTF8.GetBytes("Not found");
var status = found ? "200 OK" : "404 Not Found";
var responseHeaders = Encoding.ASCII.GetBytes(
$"HTTP/1.1 {status}\r\nContent-Length: {body.Length}\r\nConnection: close\r\n\r\n");
await WriteBytesAsync(stream, responseHeaders);
await WriteBytesAsync(stream, body);
}
}
private static Task WriteBytesAsync(Stream stream, byte[] contents)
{
#if NETFRAMEWORK
return stream.WriteAsync(contents, 0, contents.Length);
#else
return stream.WriteAsync(contents).AsTask();
#endif
}
}
private sealed record BuildResult(int ExitCode, string StandardOutput, string StandardError, string CommandLine)
{
public bool Succeeded => ExitCode == 0;
public string FailureMessage() =>
$"{CommandLine}\nExitCode: {ExitCode}\n--- STDOUT ---\n{StandardOutput}\n--- STDERR ---\n{StandardError}";
}
}