This repository has been archived by the owner on May 15, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 502
/
Copy pathbuild.cake
378 lines (307 loc) · 13.7 KB
/
build.cake
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
#addin nuget:?package=Cake.AppleSimulator&version=0.2.0
#addin nuget:?package=Cake.Android.Adb&version=3.2.0
#addin nuget:?package=Cake.Android.AvdManager&version=2.2.0
#addin nuget:?package=Cake.Android.SdkManager&version=3.0.2
#addin nuget:?package=Cake.FileHelpers&version=3.3.0
#addin nuget:?package=Cake.Boots&version=1.1.0.712-preview2
var TARGET = Argument("target", "Default");
var IOS_SIM_NAME = Argument("ios-device", EnvironmentVariable("IOS_SIM_NAME") ?? "iPhone 14");
var IOS_SIM_RUNTIME = Argument("ios-runtime", EnvironmentVariable("IOS_SIM_RUNTIME") ?? "ios-simulator-64");
var IOS_PROJ = "./DeviceTests.iOS/DeviceTests.iOS.csproj";
var IOS_BUNDLE_ID = "com.xamarin.essentials.devicetests";
var IOS_IPA_PATH = "./DeviceTests.iOS/bin/iPhoneSimulator/Release/XamarinEssentialsDeviceTestsiOS.app";
var IOS_TEST_RESULTS_PATH = MakeAbsolute((FilePath)"../output/test-results/ios");
var ANDROID_PROJ = "./DeviceTests.Android/DeviceTests.Android.csproj";
var ANDROID_APK_PATH = MakeAbsolute((FilePath)"./DeviceTests.Android/bin/Debug/com.xamarin.essentials.devicetests-Signed.apk");
var ANDROID_INSTRUMENTATION_NAME = "com.xamarin.essentials.devicetests.TestInstrumentation";
var ANDROID_TEST_RESULTS_PATH = MakeAbsolute((FilePath)"../output/test-results/android");
var ANDROID_AVD = EnvironmentVariable("ANDROID_AVD") ?? "CABOODLE";
var ANDROID_PKG_NAME = "com.xamarin.essentials.devicetests";
var ANDROID_EMU_TARGET = Argument("avd-target", EnvironmentVariable("ANDROID_EMU_TARGET") ?? "system-images;android-30;google_apis_playstore;x86");
var ANDROID_EMU_DEVICE = Argument("avd-device", EnvironmentVariable("ANDROID_EMU_DEVICE") ?? "Nexus 5X");
var UWP_PROJ = "./DeviceTests.UWP/DeviceTests.UWP.csproj";
var UWP_TEST_RESULTS_PATH = MakeAbsolute((FilePath)"../output/test-results/uwp/TestResults.xml");
var UWP_PACKAGE_ID = "ec0cc741-fd3e-485c-81be-68815c480690";
var TCP_LISTEN_TIMEOUT = 240;
var TCP_LISTEN_PORT = 63559;
var TCP_LISTEN_HOST = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName())
.AddressList.First(f => f.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
.ToString();
var OUTPUT_PATH = MakeAbsolute((DirectoryPath)"../output/");
// set up env
var ANDROID_SDK_ROOT = GetAndroidSDKPath();
var ANDROID_HOME = ANDROID_SDK_ROOT;
SetEnvironmentVariable("PATH", $"{ANDROID_SDK_ROOT}/tools/bin", prepend: true);
SetEnvironmentVariable("PATH", $"{ANDROID_SDK_ROOT}/cmdline-tools/5.0/bin", prepend: true);
SetEnvironmentVariable("PATH", $"{ANDROID_SDK_ROOT}/cmdline-tools/7.0/bin", prepend: true);
SetEnvironmentVariable("PATH", $"{ANDROID_SDK_ROOT}/cmdline-tools/latest/bin", prepend: true);
SetEnvironmentVariable("PATH", $"{ANDROID_SDK_ROOT}/platform-tools", prepend: true);
SetEnvironmentVariable("PATH", $"{ANDROID_SDK_ROOT}/emulator", prepend: true);
Information("Android SDK Root: {0}", ANDROID_SDK_ROOT);
string androidSdks = EnvironmentVariable("ANDROID_API_SDKS", "platform-tools,platforms;android-26,platforms;android-27,platforms;android-28,platforms;android-29,build-tools;29.0.3,platforms;android-30,build-tools;30.0.2,platforms;android-32,build-tools;32.0.0,platforms;android-33,build-tools;33.0.2");
Information("ANDROID_API_SDKS: {0}", androidSdks);
string[] androidSdkManagerInstalls = androidSdks.Split(',');
// utils
Task DownloadTcpTextAsync(int port, FilePath filename, Action waitAction = null)
{
filename = MakeAbsolute(filename);
EnsureDirectoryExists(filename.GetDirectory());
return System.Threading.Tasks.Task.Run(() => {
var tcpListener = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Any, port);
tcpListener.Start();
var listening = true;
System.Threading.Tasks.Task.Run(() => {
// Sleep until timeout elapses or tcp listener stopped after a successful connection
var elapsed = 0;
while(elapsed <= TCP_LISTEN_TIMEOUT && listening) {
System.Threading.Thread.Sleep(1000);
elapsed++;
Information($"Still waiting for tests... {elapsed}/{TCP_LISTEN_TIMEOUT}");
waitAction?.Invoke();
}
// If still listening, timeout elapsed, stop the listener
if (listening) {
tcpListener.Stop();
listening = false;
}
});
try {
var tcpClient = tcpListener.AcceptTcpClient();
using (var file = System.IO.File.Open(filename.FullPath, System.IO.FileMode.Create))
using (var stream = tcpClient.GetStream())
stream.CopyTo(file);
tcpClient.Close();
tcpListener.Stop();
listening = false;
} catch {
throw new Exception("Test results listener failed or timed out.");
}
});
}
void SetEnvironmentVariable(string name, string value, bool prepend = false)
{
var target = EnvironmentVariableTarget.Process;
if (prepend)
value = value + System.IO.Path.PathSeparator + EnvironmentVariable(name);
Environment.SetEnvironmentVariable(name, value, target);
Information("Setting environment variable: {0} = '{1}'", name, value);
}
string GetAndroidSDKPath()
{
var ANDROID_SDK_ROOT = Argument("android", EnvironmentVariable("ANDROID_SDK_ROOT") ?? EnvironmentVariable("ANDROID_HOME"));
if (string.IsNullOrEmpty(ANDROID_SDK_ROOT)) {
throw new Exception("Environment variable 'ANDROID_SDK_ROOT' or 'ANDROID_HOME' must be set to the Android SDK root.");
}
return ANDROID_SDK_ROOT;
}
// iOS tasks
Task("build-ios")
.Does(() =>
{
MSBuild(IOS_PROJ, c => {
c.Configuration = "Release";
c.Restore = true;
c.Properties["Platform"] = new List<string> { "iPhoneSimulator" };
c.Properties["BuildIpa"] = new List<string> { "true" };
c.Properties["ContinuousIntegrationBuild"] = new List<string> { "false" };
c.Targets.Clear();
c.Targets.Add("Rebuild");
c.BinaryLogger = new MSBuildBinaryLogSettings {
Enabled = true,
FileName = OUTPUT_PATH.CombineWithFilePath("binlogs/device-tests-ios-build.binlog").FullPath,
};
});
});
Task("test-ios-emu")
.IsDependentOn("build-ios")
.Does(() =>
{
// Clean up after previous runs
CleanDirectories(IOS_TEST_RESULTS_PATH.FullPath);
// Run the tests
var resultCode = StartProcess("xharness", "apple test " +
$"--app=\"{IOS_IPA_PATH}\" " +
$"--targets=\"ios-simulator-64\" " +
$"--output-directory=\"{IOS_TEST_RESULTS_PATH}\" " +
$"--verbosity=\"Debug\" " +
$"--set-env=ci-run=true ");
// Rename test result files
var resultFiles = GetFiles($"{IOS_TEST_RESULTS_PATH}/*.xml");
foreach (var resultFile in resultFiles) {
MoveFile(resultFile, resultFile.ChangeExtension("TestResults.xml"));
}
if (resultCode != 0)
throw new Exception("xharness had an error.");
});
// Android tasks
Task("boots")
.Does(async () =>
{
await Boots (Product.XamarinAndroid, ReleaseChannel.Stable);
});
Task("provision-androidsdk")
.Description("Install Xamarin.Android SDK")
.Does(() =>
{
Information ("ANDROID_HOME: {0}", ANDROID_HOME);
if(androidSdkManagerInstalls.Length > 0)
{
Information("Updating Android SDKs");
var androidSdkSettings = new AndroidSdkManagerToolSettings {
SkipVersionCheck = true
};
if(!String.IsNullOrWhiteSpace(ANDROID_HOME))
androidSdkSettings.SdkRoot = ANDROID_HOME;
try{
AcceptLicenses (androidSdkSettings);
}
catch(Exception exc)
{
Information("AcceptLicenses: {0}", exc);
}
try{
AndroidSdkManagerUpdateAll (androidSdkSettings);
}
catch(Exception exc)
{
Information("AndroidSdkManagerUpdateAll: {0}", exc);
}
try{
AcceptLicenses (androidSdkSettings);
}
catch(Exception exc)
{
Information("AcceptLicenses: {0}", exc);
}
try{
AndroidSdkManagerInstall (androidSdkManagerInstalls, androidSdkSettings);
}
catch(Exception exc)
{
Information("AndroidSdkManagerInstall: {0}", exc);
}
}
});
Task("build-android")
.IsDependentOn("provision-androidsdk")
.IsDependentOn("boots")
.Does(() =>
{
MSBuild(ANDROID_PROJ, c => {
c.Configuration = "Debug"; // needs to be debug so unit tests get discovered
c.Restore = true;
c.Properties["ContinuousIntegrationBuild"] = new List<string> { "false" };
c.Targets.Clear();
c.Targets.Add("Rebuild");
c.Targets.Add("SignAndroidPackage");
c.BinaryLogger = new MSBuildBinaryLogSettings {
Enabled = true,
FileName = OUTPUT_PATH.CombineWithFilePath("binlogs/device-tests-android-build.binlog").FullPath,
};
});
});
Task("test-android-emu")
.IsDependentOn("build-android")
.Does(() =>
{
// Clean up after previous runs
CleanDirectories(ANDROID_TEST_RESULTS_PATH.FullPath);
var avdSettings = new AndroidAvdManagerToolSettings { SdkRoot = ANDROID_HOME };
var adbSettings = new AdbToolSettings { SdkRoot = ANDROID_HOME };
var emuSettings = new AndroidEmulatorToolSettings { SdkRoot = ANDROID_HOME, ArgumentCustomization = args => args.Append("-no-window") };
// Delete AVD first, if it exists
Information("Deleting AVD if exists: {0}...", ANDROID_AVD);
try { AndroidAvdDelete(ANDROID_AVD, avdSettings); }
catch { }
// Create the AVD
Information("Creating AVD: {0}...", ANDROID_AVD);
AndroidAvdCreate(ANDROID_AVD, ANDROID_EMU_TARGET, ANDROID_EMU_DEVICE, force: true, settings: avdSettings);
// Start the emulator
Information("Starting Emulator: {0}...", ANDROID_AVD);
var emulatorProcess = AndroidEmulatorStart(ANDROID_AVD, emuSettings);
var waited = 0;
while (AdbShell("getprop sys.boot_completed", adbSettings).FirstOrDefault() != "1") {
System.Threading.Thread.Sleep(1000);
if (waited++ > 60 * 10)
break;
}
Information("Waited {0} seconds for the emulator to boot up.", waited);
var targetArch = ANDROID_EMU_TARGET.Split(';').Last();
// Run the tests
var resultCode = StartProcess("xharness", "android test " +
$"--app=\"{ANDROID_APK_PATH}\" " +
$"--package-name=\"{ANDROID_PKG_NAME}\" " +
$"--instrumentation=\"{ANDROID_INSTRUMENTATION_NAME}\" " +
$"--device-arch=\"{targetArch}\" " +
$"--output-directory=\"{ANDROID_TEST_RESULTS_PATH}\" " +
$"--verbosity=\"Debug\" ");
// Stop / cleanup the emulator
AdbEmuKill(adbSettings);
System.Threading.Thread.Sleep(5000);
// Kill the process if it has not already exited
try { emulatorProcess.Kill(); }
catch { }
if (resultCode != 0)
throw new Exception("xharness had an error.");
Information("Done Tests");
});
// UWP tasks
Task("build-uwp")
.Does(() =>
{
MSBuild(UWP_PROJ, c => {
c.Configuration = "Debug";
c.Restore = true;
c.Properties["ContinuousIntegrationBuild"] = new List<string> { "false" };
c.Properties["AppxBundlePlatforms"] = new List<string> { "x86" };
c.Properties["AppxBundle"] = new List<string> { "Always" };
c.Properties["AppxPackageSigningEnabled"] = new List<string> { "true" };
c.Targets.Clear();
c.Targets.Add("Rebuild");
c.BinaryLogger = new MSBuildBinaryLogSettings {
Enabled = true,
FileName = OUTPUT_PATH.CombineWithFilePath("binlogs/device-tests-uwp-build.binlog").FullPath,
};
});
});
Task("test-uwp-emu")
.IsDependentOn("build-uwp")
.WithCriteria(IsRunningOnWindows())
.Does(() =>
{
var uninstallPS = new Action(() => {
try {
StartProcess("powershell",
"$app = Get-AppxPackage -Name " + UWP_PACKAGE_ID + "; if ($app) { Remove-AppxPackage -Package $app.PackageFullName }");
} catch { }
});
// Try to uninstall the app if it exists from before
uninstallPS();
var certPath = GetFiles("./**/DeviceTests.UWP_TemporaryKey.pfx").First();
Information("Installing certificate: {0}", certPath);
StartProcess("certutil", "-p Microsoft -importpfx \"" + MakeAbsolute(certPath).FullPath + "\"");
// Install the appx
var dependencies = GetFiles("./**/AppPackages/**/Dependencies/x86/*.appx");
foreach (var dep in dependencies) {
Information("Installing Dependency appx: {0}", dep);
StartProcess("powershell", "Add-AppxPackage -Path \"" + MakeAbsolute(dep).FullPath + "\"");
}
var appxBundlePath = GetFiles("./**/AppPackages/**/*.msixbundle").First();
Information("Installing appx: {0}", appxBundlePath);
StartProcess("powershell", "Add-AppxPackage -Path \"" + MakeAbsolute(appxBundlePath).FullPath + "\"");
// Start the TCP Test results listener
Information("Started TCP Test Results Listener on port: {0}:{1}", TCP_LISTEN_HOST, TCP_LISTEN_PORT);
var tcpListenerTask = DownloadTcpTextAsync(TCP_LISTEN_PORT, UWP_TEST_RESULTS_PATH);
// Launch the app
Information("Running appx: {0}", appxBundlePath);
var ip = TCP_LISTEN_HOST.Replace(".", "-");
var executeCommand = $"xamarin-essentials-device-tests://{ip}_{TCP_LISTEN_PORT}";
Information("Running appx: {0}", executeCommand);
StartProcess("explorer", executeCommand);
// Wait for the test results to come back
Information("Waiting for tests...");
tcpListenerTask.Wait();
// Uninstall the app(this will terminate it too)
uninstallPS();
});
RunTarget(TARGET);