-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathbuild.cake
More file actions
861 lines (771 loc) · 30.7 KB
/
Copy pathbuild.cake
File metadata and controls
861 lines (771 loc) · 30.7 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
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
#addin nuget:?package=Cake.FileHelpers&version=2.0.0
#addin nuget:?package=Cake.AzureStorage
#addin nuget:?package=Cake.Xcode
#addin nuget:?package=Cake.Json&version=3.0.1
#addin nuget:?package=Cake.Http&version=1.3.0
#load "utility.cake"
#load "nuget-tools.cake"
using Path = System.IO.Path;
using System;
using System.Net;
using System.Threading;
// Native SDK versions
const string AndroidSdkVersion = "4.4.2";
const string IosSdkVersion = "4.4.1";
const string UwpSdkVersion = "4.5.0";
// URLs for downloading binaries.
/*
* Read this: http://www.mono-project.com/docs/faq/security/.
* On Windows,
* you have to do additional steps for SSL connection to download files.
* http://stackoverflow.com/questions/4926676/mono-webrequest-fails-with-https
* By running mozroots and install part of Mozilla's root certificates can make it work.
*/
const string SdkStorageUrl = "https://mobilecentersdkdev.blob.core.windows.net/sdk/";
const string AndroidUrl = SdkStorageUrl + "AppCenter-SDK-Android-" + AndroidSdkVersion + ".zip";
const string IosUrl = SdkStorageUrl + "AppCenter-SDK-Apple-" + IosSdkVersion + ".zip";
const string UwpUrl = SdkStorageUrl + "AppCenter-SDK-Unity-UWP-" + UwpSdkVersion + ".zip";
const string AndroidRepoUrl = "https://github.com/microsoft/appcenter-sdk-android.git";
const string AppleRepoUrl = "https://github.com/microsoft/appcenter-sdk-apple.git";
const string DotNetRepoUrl = "https://github.com/microsoft/appcenter-sdk-dotnet.git";
var ReposToUpdate = new List<string>()
{
AndroidRepoUrl,
AppleRepoUrl,
DotNetRepoUrl
};
var AppCenterModules = new []
{
new AppCenterModule("appcenter-release.aar", "AppCenter.framework", "Microsoft.AppCenter", "Core"),
new AppCenterModule("appcenter-analytics-release.aar", "AppCenterAnalytics.framework", "Microsoft.AppCenter.Analytics", "Analytics"),
new AppCenterModule("appcenter-distribute-release.aar", new[] { "AppCenterDistribute.framework", "AppCenterDistributeResources.bundle" }, "Microsoft.AppCenter.Distribute", "Distribute"),
new AppCenterModule("appcenter-crashes-release.aar", "AppCenterCrashes.framework", "Microsoft.AppCenter.Crashes", "Crashes")
};
var ExternalUnityPackages = new []
{
// From https://github.com/googlesamples/unity-jar-resolver#getting-started
// Import the play-services-resolver-*.unitypackage into your plugin project <...> ensuring that you add the -gvh_disable option.
// You must specify the -gvh_disable option in order for the Version Handler to work correctly!
new ExternalUnityPackage($"play-services-resolver-{ExternalUnityPackage.VersionPlaceholder}.0.unitypackage",
"1.2.135",
$"https://github.com/googlesamples/unity-jar-resolver/raw/v{ExternalUnityPackage.VersionPlaceholder}/{ExternalUnityPackage.NamePlaceholder}",
"-gvh_disable")
};
// Unity requires a specific NDK version for building Android with IL2CPP.
// Download from a link here: https://developer.android.com/ndk/downloads/older_releases.html
// Unity 2018.4.18 requires NDK r16b.
// The destination for the NDK download.
const string NdkFolder = "android_ndk";
// Task TARGET for build
var Target = Argument("target", Argument("t", "Default"));
// App Center module class definition.
class AppCenterModule
{
public string AndroidModule { get; private set; }
public string[] IosModules { get; private set; }
public string DotNetModule { get; private set; }
public string Moniker { get; private set; }
public bool UWPHasNativeCode { get; private set; }
public string[] NativeArchitectures { get; private set; }
public AppCenterModule(string android, string ios, string dotnet, string moniker, bool hasNative = false) :
this(android, new[] { ios }, dotnet, moniker, hasNative)
{
}
public AppCenterModule(string android, string[] ios, string dotnet, string moniker, bool hasNative = false)
{
AndroidModule = android;
IosModules = ios;
DotNetModule = dotnet;
Moniker = moniker;
UWPHasNativeCode = hasNative;
if (hasNative)
{
NativeArchitectures = new string[] {"x86", "x64", "arm", "arm64"};
}
}
}
class ExternalUnityPackage
{
public static string NamePlaceholder = "<name>";
public static string VersionPlaceholder = "<version>";
public string Name { get; private set; }
public string Version { get; private set; }
public string Url { get; private set; }
public string AdditionalImportArgs { get; private set; }
public ExternalUnityPackage(string name, string version, string url, string additionalImportArgs = "")
{
AdditionalImportArgs = additionalImportArgs;
Version = version;
Name = name.Replace(VersionPlaceholder, Version);
Url = url.Replace(NamePlaceholder, Name).Replace(VersionPlaceholder, Version);
}
}
// Spec files can have up to one dependency.
class UnityPackage
{
private string _packageName;
private string _packageVersion;
private List<string> _includePaths = new List<string>();
public UnityPackage(string specFilePath)
{
var result = AddFilesFromSpec(specFilePath);
if (!result)
{
throw new Exception("Failed to form unity package.");
}
}
private bool AddFilesFromSpec(string specFilePath)
{
var needsCore = Statics.Context.XmlPeek(specFilePath, "package/@needsCore") == "true";
if (needsCore)
{
var specFileDirectory = Path.GetDirectoryName(specFilePath);
if (!AddFilesFromSpec(specFileDirectory + "/AppCenter.unitypackagespec"))
{
return false;
}
}
_packageName = Statics.Context.XmlPeek(specFilePath, "package/@name");
_packageVersion = Statics.Context.XmlPeek(specFilePath, "package/@version");
if (_packageName == null || _packageVersion == null)
{
Statics.Context.Error("Invalid format for UnityPackageSpec file '" + specFilePath + "': missing package name or version");
return false;
}
var xpathPrefix = "/package/include/file[";
var xpathSuffix= "]/@path";
var lastPath = Statics.Context.XmlPeek(specFilePath, xpathPrefix + "last()" + xpathSuffix);
var currentIdx = 1;
var currentPath = Statics.Context.XmlPeek(specFilePath, xpathPrefix + currentIdx++ + xpathSuffix);
if (currentPath != null)
{
_includePaths.Add(currentPath);
}
while (currentPath != lastPath)
{
currentPath = Statics.Context.XmlPeek(specFilePath, xpathPrefix + currentIdx++ + xpathSuffix);
_includePaths.Add(currentPath);
}
return true;
}
public void CreatePackage(string targetDirectory)
{
// From https://github.com/googlesamples/unity-jar-resolver#getting-started
// Export your plugin <...> ensuring that you <...> Add the -gvh_disable option.
// You must specify the -gvh_disable option in order for the Version Handler to work correctly!
var args = "-gvh_disable -exportPackage ";
foreach (var path in _includePaths)
{
args += " " + path;
}
var fullPackageName = _packageName + "-v" + _packageVersion + ".unitypackage";
args += " " + targetDirectory + "/" + fullPackageName;
var result = ExecuteUnityCommand(args);
if (result != 0)
{
Statics.Context.Error("Something went wrong while creating Unity package '" + fullPackageName + "'");
}
}
public void CopyFiles(DirectoryPath targetDirectory)
{
foreach (var path in _includePaths)
{
if (Statics.Context.DirectoryExists(path))
{
Statics.Context.CopyDirectory(path, targetDirectory.Combine(path));
}
else
{
Statics.Context.CopyFile(path, targetDirectory.CombineWithFilePath(path));
}
}
}
}
// Downloading Android binaries.
Task("Externals-Android").Does(() =>
{
var externalsDirectory = "externals/android/";
var outputDirectory = "Assets/AppCenter/Plugins/Android/";
var zipFilePath = externalsDirectory + "android.zip";
CleanDirectory(externalsDirectory);
EnsureDirectoryExists(outputDirectory);
// Download zip file.
var authParams = Argument("StorageAuthParams", EnvironmentVariable("STORAGE_AUTH_PARAMS"));
var artifactUrl = $"{AndroidUrl}{authParams}";
Information($"Downloading Android libraries from {artifactUrl}...");
DownloadFile(artifactUrl, zipFilePath);
Information($"Unzipping Android libraries from \"{zipFilePath}\" to \"{externalsDirectory}\".");
Unzip(zipFilePath, externalsDirectory);
// Copy files.
foreach (var module in AppCenterModules)
{
Information($"Copying module \"{module.Moniker}\"...");
var files = GetFiles($"{externalsDirectory}*/{module.AndroidModule}");
CopyFiles(files, outputDirectory);
}
}).OnError(HandleError);
// Downloading iOS binaries.
Task("Externals-Ios")
.Does(() =>
{
var externalsDirectory = "externals/ios/";
var outputDirectory = "Assets/AppCenter/Plugins/iOS/";
var zipFilePath = externalsDirectory + "ios.zip";
CleanDirectory(externalsDirectory);
EnsureDirectoryExists(outputDirectory);
// Download zip file containing AppCenter frameworks.
var authParams = Argument("StorageAuthParams", EnvironmentVariable("STORAGE_AUTH_PARAMS"));
var artifactUrl = $"{IosUrl}{authParams}";
Information($"Downloading iOS frameworks from {artifactUrl}...");
DownloadFile(artifactUrl, zipFilePath);
Information($"Unzipping iOS frameworks from \"{zipFilePath}\" to \"{externalsDirectory}\".");
Unzip(zipFilePath, externalsDirectory);
// Copy files.
foreach (var module in AppCenterModules)
{
Information($"Copying module \"{module.Moniker}\"...");
foreach (var iosModule in module.IosModules)
{
var destinationDirectory = $"{outputDirectory}{module.Moniker}/{iosModule}";
DeleteDirectoryIfExists(destinationDirectory);
MoveDirectory(externalsDirectory + "AppCenter-SDK-Apple/iOS/" + iosModule, destinationDirectory);
}
}
}).OnError(HandleError);
// Downloading UWP binaries.
Task("Externals-Uwp")
.WithCriteria(IsRunningOnWindows)
.Does(() =>
{
var externalsDirectory = "externals/uwp/";
var outputDirectory = "Assets/AppCenter/Plugins/WSA/";
var zipFilePath = externalsDirectory + "uwp.zip";
CleanDirectory(externalsDirectory);
EnsureDirectoryExists(outputDirectory);
// Downloading files.
var authParams = Argument("StorageAuthParams", EnvironmentVariable("STORAGE_AUTH_PARAMS"));
var artifactUrl = $"{UwpUrl}{authParams}";
Information($"Downloading UWP packages from {artifactUrl}...");
DownloadFile(artifactUrl, zipFilePath);
// Unzipping files.
Information($"Unzipping UWP packages from \"{zipFilePath}\" to \"{externalsDirectory}\".");
Unzip(zipFilePath, externalsDirectory);
foreach (var module in AppCenterModules)
{
if (module.Moniker == "Distribute")
{
Warning("Skipping 'Distribute' for UWP.");
continue;
}
if (module.Moniker == "Crashes")
{
Warning("Skipping 'Crashes' for UWP.");
continue;
}
Information($"Copying module \"{module.Moniker}\"...");
// Prepare folders.
var destination = $"{outputDirectory}{module.Moniker}/";
EnsureDirectoryExists(destination);
DeleteFiles(destination + "*.dll");
DeleteFiles(destination + "*.winmd");
// Copy files.
var files = GetFiles($"{externalsDirectory}{module.DotNetModule}.dll");
CopyFiles(files, destination);
}
}).OnError(HandleError);
// Builds the ContentProvider for the Android package and puts it in the
// proper folder.
Task("BuildAndroidContentProvider").Does(() =>
{
// Folder and script locations
var appName = "AppCenterLoaderApp";
var libraryName = "appcenter-loader";
BuildAndroidLibrary(appName, libraryName);
// This is a workaround for NDK build making an error where it claims
// it can't find the built .so library (which is built successfully).
// This error is breaking the CI build on Windows. If you are seeing this,
// most likely we haven't found a fix and this is an NDK bug.
if (!IsRunningOnWindows())
{
appName = "BreakpadSupport";
BuildAndroidLibrary(appName, "", false);
if (GetFiles("Assets/Plugins/Android/*/libPuppetBreakpad.so").Count() == 0)
{
throw new Exception("Building breakpad library failed.");
}
}
}).OnError(HandleError);
void BuildAndroidLibrary(string appName, string libraryName, bool copyBinary = true)
{
var libraryFolder = Path.Combine(appName, libraryName);
var gradleScript = Path.Combine(libraryFolder, "build.gradle");
// Compile the library
var gradleWrapper = Path.Combine(appName, "gradlew");
if (IsRunningOnWindows())
{
gradleWrapper += ".bat";
}
var fullArgs = "-b " + gradleScript + " assembleRelease";
var result = StartProcess(gradleWrapper, fullArgs);
if (copyBinary)
{
// We check the result of the build only here because we need to check build
// result only in case we build native binary.
// In another case, when we build breakpad, we don't check it
// Due to the known issue that breakpad build always reports false failure.
if (result != 0)
{
throw new Exception("Failed to build android native library. Gradle result code: " + result);
}
// Source and destination of generated aar
var aarName = libraryName + "-release.aar";
var aarSource = Path.Combine(libraryFolder, "build/outputs/aar/" + aarName);
var aarDestination = "Assets/AppCenter/Plugins/Android";
// Move the .aar to destination folder.
DeleteFileIfExists(Path.Combine(aarDestination, aarName));
MoveFileToDirectory(aarSource, aarDestination);
}
}
// Install Unity Editor for Windows
Task("Install-Unity-Windows")
.WithCriteria(IsRunningOnWindows)
.Does(() =>
{
string unityDownloadUrl = EnvironmentVariable("EDITOR_URL_WIN");
string il2cppSupportDownloadUrl = EnvironmentVariable("IL2CPP_SUPPORT_URL");
var URLs = new []
{
unityDownloadUrl,
il2cppSupportDownloadUrl
};
foreach (var url in URLs)
{
var fileName = Path.GetFileName(url);
Information($"Downloading component {fileName} ...");
DownloadFile(url, $"./{fileName}");
Information($"Installing {fileName} ...");
var result = StartProcess($"./{fileName}", "/S");
if (result != 0)
{
throw new Exception($"Failed to install {fileName}");
}
}
}).OnError(HandleError);
// Downloading UWP IL2CPP dependencies.
Task("Externals-Uwp-IL2CPP-Dependencies")
.WithCriteria(IsRunningOnWindows)
.IsDependentOn("BuildNewtonsoftJson")
.Does (async () =>
{
var targetPath = "Assets/AppCenter/Plugins/WSA/IL2CPP";
EnsureDirectoryExists(targetPath);
EnsureDirectoryExists(targetPath + "/ARM");
EnsureDirectoryExists(targetPath + "/ARM64");
EnsureDirectoryExists(targetPath + "/X86");
EnsureDirectoryExists(targetPath + "/X64");
foreach (var dependency in UwpIL2CPPDependencies)
{
await ProcessDependency(dependency, targetPath);
}
// Process UWP IL2CPP dependencies.
Information("Processing UWP IL2CPP dependencies. This could take a minute.");
var result = ExecuteUnityCommand("-executeMethod AppCenterPostBuild.ProcessUwpIl2CppDependencies");
if (result != 0)
{
throw new Exception("Something went wrong while executing post build script. Unity result code: " + result);
}
}).OnError(HandleError);
Task("RestorePackagesForNewtonsoftJson")
.Does(() =>
{
NuGetRestore("./Modules/Newtonsoft.Json-for-Unity/Src/Newtonsoft.Json/Newtonsoft.Json.csproj");
});
Task("BuildNewtonsoftJson")
.IsDependentOn("RestorePackagesForNewtonsoftJson")
.WithCriteria(IsRunningOnWindows)
.Does(() =>
{
var outputDirectory = "Assets/AppCenter/Plugins/WSA/IL2CPP";
var projectPath = "Modules/Newtonsoft.Json-for-Unity/Src/Newtonsoft.Json";
var assemblyName = "Newtonsoft.Json.dll";
var assemblyPath = $"{projectPath}/bin/Release/unity-aot/{assemblyName}";
Information("Building Newtonsoft.Json project...");
MSBuild(Path.Combine(projectPath, "Newtonsoft.Json.csproj"), c => c
.WithProperty("UnityBuild", "AOT")
.SetConfiguration("Release"));
Information($"Moving Newtonsoft.Json to {outputDirectory}...");
DeleteFileIfExists(Path.Combine(outputDirectory, assemblyName));
MoveFileToDirectory(assemblyPath, outputDirectory);
}).OnError(HandleError);
// Download and install all external Unity packages required.
Task("Externals-Unity-Packages").Does(() =>
{
var directoryPath = new DirectoryPath("externals/unity-packages");
CleanDirectory(directoryPath);
foreach (var package in ExternalUnityPackages)
{
var destination = directoryPath.CombineWithFilePath(package.Name);
DownloadFile(package.Url, destination);
Information("Importing package " + package.Name + ". This could take a minute.");
var command = package.AdditionalImportArgs + " -importPackage " + destination.FullPath;
var result = ExecuteUnityCommand(command);
if (result != 0)
{
throw new Exception("Something went wrong while importing packages. Unity result code: " + result);
}
}
}).OnError(HandleError);
// Add App Center packages to demo app.
Task("AddPackagesToDemoApp")
.IsDependentOn("CreatePackages")
.Does(()=>
{
var specFiles = GetFiles("UnityPackageSpecs/*.unitypackagespec");
foreach (var spec in specFiles)
{
Information("Add files from " + spec);
var package = new UnityPackage(spec.FullPath);
package.CopyFiles("AppCenterDemoApp");
}
}).OnError(HandleError);
// Remove package files from demo app.
Task("RemovePackagesFromDemoApp").Does(() =>
{
DeleteDirectoryIfExists("AppCenterDemoApp/Assets/AppCenter");
DeleteDirectoryIfExists("AppCenterDemoApp/Assets/Plugins");
}).OnError(HandleError);
// Create a common externals task depending on platform specific ones
// NOTE: It is important to execute Externals-Uwp-IL2CPP-Dependencies *last*
// or steps that run Unity commands might cause the *.meta files to be deleted!
// (Unity deletes meta data files when it is opened if the corresponding files are not on disk.)
Task("Externals")
.IsDependentOn("Externals-Uwp")
.IsDependentOn("Externals-Ios")
.IsDependentOn("Externals-Android")
.IsDependentOn("BuildAndroidContentProvider")
.IsDependentOn("Externals-Uwp-IL2CPP-Dependencies")
.IsDependentOn("Externals-Unity-Packages")
.Does(() =>
{
DeleteDirectoryIfExists("externals");
});
// Creates Unity packages corresponding to all ".unitypackagespec" files
// in "UnityPackageSpecs" folder.
Task("Package").Does(() =>
{
// Remove AndroidManifest.xml
var path = "Assets/Plugins/Android/appcenter/AndroidManifest.xml";
DeleteFileIfExists(path);
// Store packages in a clean folder.
const string outputDirectory = "output";
CleanDirectory(outputDirectory);
var specFiles = GetFiles("UnityPackageSpecs/*.unitypackagespec");
foreach (var spec in specFiles)
{
var package = new UnityPackage(spec.FullPath);
package.CreatePackage(outputDirectory);
}
});
Task("PrepareAssets").IsDependentOn("Externals");
// Creates Unity packages corresponding to all ".unitypackagespec" files
// in "UnityPackageSpecs" folder (and downloads binaries)
Task("CreatePackages").IsDependentOn("PrepareAssets").IsDependentOn("Package");
// Builds the puppet applications and throws an exception on failure.
Task("BuildPuppetApps")
.IsDependentOn("PrepareAssets")
.Does(() =>
{
BuildApps("Puppet");
}).OnError(HandleError);
// Builds the demo applications and throws an exception on failure.
Task("BuildDemoApps")
.IsDependentOn("AddPackagesToDemoApp")
.Does(() =>
{
BuildApps("Demo", "AppCenterDemoApp");
}).OnError(HandleError);
// Downloads the NDK from the specified location.
Task("DownloadNdk").Does(() =>
{
var ndkUrl = EnvironmentVariable("ANDROID_NDK_URL");
if (string.IsNullOrEmpty(ndkUrl))
{
throw new Exception("Ndk Url is empty string or null");
}
var zipDestination = Statics.TemporaryPrefix + "ndk.zip";
// Download required NDK
DownloadFile(ndkUrl, zipDestination);
// Something is buggy about the way Cake unzips, so use shell on mac
if (IsRunningOnUnix())
{
CleanDirectory(NdkFolder);
var result = StartProcess("unzip", new ProcessSettings{ Arguments = $"{zipDestination} -d {NdkFolder}"});
if (result != 0)
{
throw new Exception("Failed to unzip ndk.");
}
}
else
{
Unzip(zipDestination, NdkFolder);
}
}).OnError(HandleError);
void BuildApps(string type, string projectPath = ".")
{
if (Statics.Context.IsRunningOnUnix())
{
VerifyIosAppsBuild(type, projectPath);
VerifyAndroidAppsBuild(type, projectPath);
}
else
{
VerifyWindowsAppsBuild(type, projectPath);
}
}
void VerifyIosAppsBuild(string type, string projectPath)
{
VerifyAppsBuild(type, "ios", projectPath,
// From Unity 2018.3 changelog: "iOS: Marked Mono scripting backend as deprecated."
new string[] { "IosIl2CPP" },
outputDirectory =>
{
var directories = GetDirectories(outputDirectory + "/*/*.xcodeproj");
if (directories.Count == 0)
{
throw new Exception("No ios projects found in directory '" + outputDirectory + "'");
}
var xcodeProjectPath = directories.Single();
Statics.Context.Information("Attempting to build '" + xcodeProjectPath.FullPath + "'...");
BuildXcodeProject(xcodeProjectPath.FullPath);
Statics.Context.Information("Successfully built '" + xcodeProjectPath.FullPath + "'");
});
}
void VerifyAndroidAppsBuild(string type, string projectPath)
{
var extraArgs = "";
if (DirectoryExists(NdkFolder))
{
var absoluteNdkFolder = Statics.Context.MakeAbsolute(Statics.Context.Directory(NdkFolder));
extraArgs += "-NdkLocation \"" + absoluteNdkFolder + "\"";
}
VerifyAppsBuild(type, "android", projectPath,
new string[] { "AndroidIl2CPP" },
outputDirectory =>
{
// Verify that an APK was generated.
if (Statics.Context.GetFiles(outputDirectory + "/*.apk").Count == 0)
{
throw new Exception("No apk found in directory '" + outputDirectory + "'");
}
Statics.Context.Information("Found apk.");
}, extraArgs);
}
void VerifyWindowsAppsBuild(string type, string projectPath)
{
VerifyAppsBuild(type, "wsaplayer", projectPath,
new string[] { "WsaIl2CPPD3D" },
outputDirectory =>
{
Statics.Context.Information("Verifying app build in directory: " + outputDirectory);
var slnFiles = GetFiles(outputDirectory + "/*/*.sln");
if (slnFiles.Count() == 0)
{
throw new Exception("No .sln files found in the following directory and all it's subdirectories: " + outputDirectory);
}
if (slnFiles.Count() > 1)
{
throw new Exception(string.Format("Multiple .sln files found in directory {0}: {1}", outputDirectory, string.Join(", ", slnFiles)));
}
var solutionFilePath = slnFiles.Single();
Statics.Context.Information("Attempting to build '" + solutionFilePath.ToString() + "'...");
Statics.Context.MSBuild(solutionFilePath.ToString(), c => c
.SetConfiguration("Master")
.WithProperty("Platform", "x86")
.SetVerbosity(Verbosity.Minimal)
.SetMSBuildPlatform(MSBuildPlatform.x86));
Statics.Context.Information("Successfully built '" + solutionFilePath.ToString() + "'");
});
}
void VerifyAppsBuild(string type, string platformIdentifier, string projectPath, string[] buildTypes, Action<string> verificatonMethod, string extraArgs = "")
{
var outputDirectory = GetBuildFolder(type, projectPath);
var methodPrefix = "Build" + type + ".Build" + type + "Scene";
foreach (var buildType in buildTypes)
{
// Remove all existing builds and create new build.
Statics.Context.CleanDirectory(outputDirectory);
ExecuteUnityMethod(methodPrefix + buildType + " " + extraArgs, platformIdentifier);
verificatonMethod(outputDirectory);
// Remove all remaining builds.
Statics.Context.CleanDirectory(outputDirectory);
}
// Remove all remaining builds.
Statics.Context.CleanDirectory(outputDirectory);
}
Task("PublishPackagesToStorage").Does(() =>
{
// The environment variables below must be set for this task to succeed
var apiKey = Argument("AzureStorageAccessKey", EnvironmentVariable("AZURE_STORAGE_ACCESS_KEY"));
var accountName = EnvironmentVariable("AZURE_STORAGE_ACCOUNT");
var corePackageVersion = XmlPeek(File("UnityPackageSpecs/AppCenter.unitypackagespec"), "package/@version");
var zippedPackages = "AppCenter-SDK-Unity-" + corePackageVersion + ".zip";
var files = GetFiles("output/*.unitypackage");
Zip("./", zippedPackages, files);
Information("Publishing packages to blob storage: " + zippedPackages);
AzureStorage.UploadFileToBlob(new AzureStorageSettings
{
AccountName = accountName,
ContainerName = "sdk",
BlobName = zippedPackages,
Key = apiKey,
UseHttps = true
}, zippedPackages);
DeleteFiles(zippedPackages);
foreach (var package in GetBuiltPackages())
{
Information("Publishing packages to blob storage: " + package);
var fileName = Path.GetFileNameWithoutExtension(package); // AppCenterAnalytics-v1.0.0
var index = fileName.IndexOf('-'); // 18
var fileNameLatest = fileName.Substring(0, index) + "Latest.unitypackage"; // AppCenterAnalyticsLatest.unitypackage
AzureStorage.UploadFileToBlob(new AzureStorageSettings
{
AccountName = accountName,
ContainerName = "sdk",
BlobName = fileNameLatest,
Key = apiKey,
UseHttps = true
}, package);
}
}).OnError(HandleError);
Task("RegisterUnity").Does(() =>
{
var serialNumber = Argument<string>("UnitySerialNumber");
var username = Argument<string>("UnityUsername");
var password = Argument<string>("UnityPassword");
// This will produce an error, but that's okay because the project "noproject" is used so that the
// root isn't opened by unity, which could potentially remove important .meta files.
ExecuteUnityCommand($"-serial {serialNumber} -username {username} -password {password}", "noproject");
var found = false;
if (Statics.Context.IsRunningOnUnix())
{
found = GetFiles("/Library/Application Support/Unity/*.ulf").Count > 0;
}
else
{
var localAppDataUnityPath = Path.Combine(EnvironmentVariable("LOCALAPPDATA"), @"VirtualStore\ProgramData\Unity\*.ulf");
found = GetFiles(localAppDataUnityPath).Count + GetFiles(Path.Combine(EnvironmentVariable("PROGRAMDATA"), @"Unity\*.ulf")).Count > 0;
}
if (!found)
{
throw new Exception("Failed to activate license.");
}
}).OnError(HandleError);
Task("UnregisterUnity").Does(() =>
{
var username = Argument<string>("UnityUsername");
var password = Argument<string>("UnityPassword");
var result = ExecuteUnityCommand($"-returnLicense -username {username} -password {password}", null);
if (result != 0)
{
throw new Exception("Something went wrong while returning Unity license.");
}
}).OnError(HandleError);
// Default Task.
Task("Default").IsDependentOn("PrepareAssets");
// Clean up files/directories.
Task("clean")
.IsDependentOn("RemoveTemporaries")
.Does(() =>
{
DeleteDirectoryIfExists("externals");
DeleteDirectoryIfExists("output");
CleanDirectories("./**/bin");
CleanDirectories("./**/obj");
});
void BuildXcodeProject(string projectPath)
{
var projectFolder = Path.GetDirectoryName(projectPath);
var buildOutputFolder = Path.Combine(projectFolder, "build");
XCodeBuild(new XCodeBuildSettings {
Project = projectPath,
Scheme = "Unity-iPhone",
Configuration = "Release",
DerivedDataPath = buildOutputFolder
});
}
Task("UpdateCgManifest").Does(()=>
{
try
{
var manifestFilePath = "cgmanifest.json";
var content = ParseJsonFromFile(manifestFilePath);
var registrations = (JArray)content["Registrations"];
foreach (var registration in registrations.Children())
{
HanldeRegistration(registration);
}
SerializeJsonToPrettyFile(manifestFilePath, content);
}
catch (Exception e)
{
Warning($"Can't update 'cgmanifest.json'. Error message: {e.Message}");
}
});
void HanldeRegistration(JToken registration)
{
var component = registration["component"];
if (component == null)
{
Warning("Current registration has no 'component' property.");
return;
}
var typeObject = component["type"];
if (typeObject == null || typeObject.Value<string>() != "git")
{
Warning("Current component has no field 'type' or 'type' is not 'git'.");
return;
}
UpdateCommitHash(component);
}
void UpdateCommitHash(JToken component)
{
var gitData = component["git"];
var repoUrl = gitData["repositoryUrl"].Value<string>();
if (ReposToUpdate.IndexOf(repoUrl) < 0)
{
Warning($"Repository url: {repoUrl}. Current component should not be updated.");
return;
}
var releaseTag = GetReleaseTag(repoUrl);
if (string.IsNullOrEmpty(releaseTag))
{
Warning($"Repository url: {repoUrl}. Release tag '{releaseTag}' was not found.");
return;
}
var tagsUrl = repoUrl.Replace(".git", "/tags").Replace("https://github.com", "https://api.github.com/repos");
var tagsListJson = HttpGet(tagsUrl);
var tag = JArray.Parse(tagsListJson).Children().FirstOrDefault(t => t["name"].Value<string>() == releaseTag);
if (tag == null)
{
Warning($"Repository url: {repoUrl}. Tag '{tag}' was not found.");
return;
}
gitData["commitHash"] = tag["commit"]["sha"].Value<string>();
}
string GetReleaseTag(string repoUrl)
{
switch (repoUrl)
{
case AndroidRepoUrl:
return AndroidSdkVersion;
case AppleRepoUrl:
return IosSdkVersion;
case DotNetRepoUrl:
return UwpSdkVersion;
default:
return null;
}
}
RunTarget(Target);