-
Notifications
You must be signed in to change notification settings - Fork 1
/
build.cake
2154 lines (1803 loc) · 75.6 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
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
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env cake
// Required namespaces
using System;
using System.ComponentModel;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Web;
using System.Resources.NetStandard;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Linq;
using Cake.Common.Xml;
using Cake.Common.Tools.XUnit;
using Cake.Git.Clog;
using GoogleApi;
using GoogleApi.Entities.Translate.Common.Enums.Extensions;
using GoogleApi.Entities.Translate.Translate.Response;
using LibGit2Sharp;
// Tools and addins
#addin nuget:?package=Cake.Android.Adb&version=3.2.0
#addin nuget:?package=Cake.Android.AvdManager&version=2.2.0
#addin nuget:?package=Cake.AppCenter&version=2.0.1
#addin nuget:?package=Cake.AppleSimulator&version=0.2.0
#addin nuget:?package=Cake.AWS.S3&version=1.0.0&loaddependencies=true
#addin nuget:?package=Cake.Badge&version=1.0.0.2
#addin nuget:?package=Cake.Coverlet&version=2.5.4
#addin nuget:?package=Cake.DotNetTool.Module&version=1.1.0
#addin nuget:?package=Cake.FileHelpers&version=4.0.1
#addin nuget:?package=Cake.Git.Clog&version=1.0.0.2
#addin nuget:?package=Cake.Json&version=6.0.1
#addin nuget:?package=Cake.Plist&version=0.7.0
#addin nuget:?package=GoogleApi&version=3.10.9
#tool nuget:?package=LibGit2Sharp.NativeBinaries&version=2.0.315-alpha.0.9
#addin nuget:?package=LibGit2Sharp&version=0.27.0-preview-0175
#addin nuget:?package=Newtonsoft.Json&version=12.0.2
#addin nuget:?package=Portable.BouncyCastle&version=1.8.1.3
#addin nuget:?package=ResXResourceReader.NetStandard&version=1.0.1
#tool nuget:?package=GitVersion.CommandLine&version=5.0.1
#tool nuget:?package=NUnit.ConsoleRunner&version=3.11.1
#tool nuget:?package=xunit.runner.console&version=2.4.1
// Enum options
enum Configuration
{
Debug,
Release,
}
enum Flavor
{
Dev,
CI,
Canary,
Release,
}
enum Platform
{
Android,
iPhone,
iPhoneSimulator,
}
public class BuildFlagsConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return sourceType == typeof(string);
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
if (!(value is string stringValue))
{
throw new Exception($"Unsupported source value '{value}' for build flag");
}
var parsed = stringValue.Split("|");
var allBuildFlags = Enum.GetValues(typeof(BuildFlags)).Cast<BuildFlags>();
var providedBuildFlags = parsed.Select(flag => Enum.Parse<BuildFlags>(flag));
var parsedBuildFlags = (parsed.Contains("All") ? allBuildFlags : providedBuildFlags).Aggregate(BuildFlags.None, (a, b) => a |= b);
return parsedBuildFlags;
}
}
[Flags]
[TypeConverter(typeof(BuildFlagsConverter))]
enum BuildFlags
{
// No flags.
None = 0,
// Whether or not to show the set server screen.
TeamEntry = 1 << 0,
// Whether or not to enable offline cached providers.
OfflineAccess = 1 << 1,
// Whether or not to enable the media tab.
Podcasts = 1 << 2,
// Whether or not to show the terms of use page.
TermsOfUse = 1 << 3,
// Whether or not to enable the feedback screen.
FeedbackAccess = 1 << 4,
// Whether or not to enable the stats subtab.
StatsAccess = 1 << 5,
// Whether or not to enable the interests subtab.
InterestsAccess = 1 << 6,
// Whether or not to enable the support setting.
SupportSetting = 1 << 7,
// Whether to prefer accessing the app with a local account.
PrefersLocalAuthentication = 1 << 8,
// Whether or not to enable the notes subtab.
NotesAccess = 1 << 9,
// Whether or not to enable the groups setting.
GroupsSetting = 1 << 10,
// Whether or not to enable the account option in settings.
AccountSetting = 1 << 11,
// Whether or not to have tag following.
TagFollowing = 1 << 12,
// Whether or not to have the privacy policy.
PrivacyPolicySetting = 1 << 13,
// Downloads, enables, and compiles against the UnityFramework file.
EnableUnityFramework = 1 << 14,
}
enum APSEnvironment
{
Development,
Production,
}
enum AndroidPackageFormat
{
Apk,
Aab,
}
enum AndroidLinkTool
{
None,
Proguard,
R8,
}
// Constants
var defaultGuid = new Guid().ToString();
const string GitHashKey = "GIT_HASH";
const string VersionKey = "VERSION";
const string BundleHashKey = "BUNDLE_HASH";
const string BundleSizeKey = "BUNDLE_SIZE";
const string readableReaderLine = "<value>System.Resources.NetStandard.ResXResourceReader, System.Resources.NetStandard, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null</value>";
const string appReadyReaderLine = "<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>";
const string readableWriterLine = "<value>System.Resources.NetStandard.ResXResourceWriter, System.Resources.NetStandard, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null</value>";
const string appReadyWriterLine = "<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>";
// Handles an argument provided to the script as an argument (e.g. `./build.sh --example=flag`) OR as a YAML property
// If the `yamlFile` parameter is null or whitespace, will default to only return a script argument
// If a path to a YAML file is provided, this will look for a key with a matching name and then attempt
// to return the value associated with that key using a type converter to match the desired type.
T ArgumentOrYaml<T>(string name, T defaultValue, string yamlFile = null)
{
if (string.IsNullOrWhiteSpace(yamlFile))
{
return Argument(name, defaultValue);
}
if (!FileExists(yamlFile))
{
throw new Exception($"Unable to locate YAML file {yamlFile}");
}
var lines = FileReadLines(yamlFile);
foreach (var line in lines)
{
// ignore comments
if (line.StartsWith('#'))
{
continue;
}
var split = line.Split(':', 2);
if (split.Count() != 2)
{
Warning($"Ignoring line {line}");
continue;
}
var key = split[0].Trim();
var val = split[1].Trim();
// handle environment variables defined in YAML
if (val.StartsWith("${") && val.EndsWith("}"))
{
var envName = val.TrimStart(new [] { '$', '{' }).TrimEnd('}');
val = Environment.GetEnvironmentVariable(envName);
if (string.IsNullOrWhiteSpace(val))
{
throw new Exception($"Failed to read environment variable {envName}");
}
}
if (key == name)
{
try
{
return (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFromInvariantString(val);
}
catch
{
throw new Exception($"Failed to convert \"{val}\" with key \"{key}\"");
}
}
}
Debug($"Unable to find property {name} in {yamlFile}");
return Argument(name, defaultValue);
}
// Parameters and arguments
// A path to a YAML file containing arguments to parse.
readonly string yaml = Argument(nameof(yaml), string.Empty);
// The task to perform; see the <code>Task()</code> top-level invocations below to see what the options are.
readonly string task = ArgumentOrYaml(nameof(task), "Build", yaml);
// Whether to build in Debug or Release. This is generally passed on to MSBuild or dotnet.
readonly Configuration configuration = ArgumentOrYaml(nameof(configuration), Configuration.Debug, yaml);
// The build flavor, which is injected into the app Constants file and is used for the App Center URL slug.
readonly Flavor flavor = ArgumentOrYaml(nameof(flavor), Flavor.Dev, yaml);
// Determines the build platform, see options in the <code>Platform</code> enum above.
readonly Platform platform = ArgumentOrYaml(nameof(platform), Platform.iPhone, yaml);
/// Determines the marketing to apply; this will copy the contents of the Assets folder onto the repo.
/// When marketing is set to <code>Marketing.None</code>, the marketing task is effectively skipped, and no copying is performed.
readonly string marketing = ArgumentOrYaml(nameof(marketing), string.Empty, yaml);
// Specifies features that should be enabled in the built application.
readonly BuildFlags buildFlags = ArgumentOrYaml(nameof(buildFlags), BuildFlags.None, yaml);
/// The display name of the application.
readonly string appName = ArgumentOrYaml(nameof(appName), "App", yaml);
// The name of the project. Used for App Center download link environment variables and as part of the App Center project name.
readonly string projectName = ArgumentOrYaml(nameof(projectName), string.Empty, yaml);
// Release notes to upload to AppCenter.
// CI builds will prefix this with the git branch for pruning purposes. See the DeployCleanup task.
readonly string releaseNotes = ArgumentOrYaml(nameof(releaseNotes), string.Empty, yaml);
// The default server with which the app should communicate.
readonly string defaultServer = ArgumentOrYaml(nameof(defaultServer), "https://example.com/", yaml);
// The OAuth client ID for the server.
readonly string clientId = ArgumentOrYaml(nameof(clientId), string.Empty, yaml);
// The OAuth client secret for the server.
readonly string clientSecret = ArgumentOrYaml(nameof(clientSecret), string.Empty, yaml);
// The package ID to set in the plist or manifest for the app bundle.
readonly string packageIdentifier = ArgumentOrYaml(nameof(packageIdentifier), "com.example.app", yaml);
// Used just for the Android version code.
readonly int buildNumber = ArgumentOrYaml(nameof(buildNumber), 1, yaml);
// The name of the App Center URL slug to which to upload. If left empty, this script assumes that the slug is in project-flavor-platform format.
string appCenterApp = ArgumentOrYaml(nameof(appCenterApp), string.Empty, yaml);
// The App Center team prefix (part of the app URL). Unlikely to change.
readonly string appCenterPrefix = ArgumentOrYaml(nameof(appCenterPrefix), string.Empty, yaml);
// The group name to which to share this release in App Center.
// For store releases, this should be set to the store group, e.g. "App Store Connect Users"
readonly string appCenterGroupName = ArgumentOrYaml(nameof(appCenterGroupName), string.Empty, yaml);
// Path to a file to which post-build environment variables should be written.
readonly string envInjectFile = ArgumentOrYaml(nameof(envInjectFile), "build/app.properties", yaml);
// Whether or not to ignore some errors in the build process. Mostly for debugging.
readonly bool force = ArgumentOrYaml(nameof(force), false, yaml);
// Whether or not to upload to an app store during the deploy task.
readonly bool uploadToStore = ArgumentOrYaml(nameof(uploadToStore), false, yaml);
// The name of the codesign key to use when building for iOS.
readonly string codesignKey = ArgumentOrYaml(nameof(codesignKey), string.Empty, yaml);
// The name of the codesign provision to use when building for iOS.
readonly string codesignProvision = ArgumentOrYaml(nameof(codesignProvision), string.Empty, yaml);
// The folder to which bundles should be built, relative to the root directory.
readonly string buildFolder = ArgumentOrYaml(nameof(buildFolder), "build", yaml);
// Whether or not to use the shared runtime. Should be true for debug builds, false for release.
readonly bool androidUseSharedRuntime = ArgumentOrYaml(nameof(androidUseSharedRuntime), true, yaml);
// Whether or not to embed assemblies into the APK. This will almost always be true.
readonly bool embedAssembliesIntoApk = ArgumentOrYaml(nameof(embedAssembliesIntoApk), true, yaml);
// Whether or not to skip determining the App Center ID, even when not set.
readonly bool skipAppCenterId = ArgumentOrYaml(nameof(skipAppCenterId), false, yaml);
// Whether or not to completely restore git state after execution completes. Moderately dangerous!
readonly bool gitReset = ArgumentOrYaml(nameof(gitReset), false, yaml);
// Whether or not to badge app icons. Probably enabled for CI/Canary, and disabled for production.
readonly bool badgeIcons = ArgumentOrYaml(nameof(badgeIcons), false, yaml);
// Whether or not to badge in-app graphics (icon_no_shadow*). Requires 'badgeIcons' to be enabled also.
readonly bool inAppBadges = ArgumentOrYaml(nameof(inAppBadges), false, yaml);
// Enable to read the changelog start from an existing environment injection file.
readonly bool startChangelogFromEnvInject = ArgumentOrYaml(nameof(startChangelogFromEnvInject), false, yaml);
// Enable to skip configuring Firebase files for this build.
readonly bool skipFirebase = ArgumentOrYaml(nameof(skipFirebase), false, yaml);
// Enable to skip running tests on build.
readonly bool skipTests = ArgumentOrYaml(nameof(skipTests), false, yaml);
// Enable writing the git hash to the environment injection file.
// Disabled in build configurations that require a previous hash for the changelog and don't want to overwrite it.
readonly bool writeGitHash = ArgumentOrYaml(nameof(writeGitHash), true, yaml);
// Set to skip the clean step.
readonly bool noClean = ArgumentOrYaml(nameof(noClean), false, yaml);
// Set to skip the restore step.
readonly bool noRestore = ArgumentOrYaml(nameof(noRestore), false, yaml);
// The ref from which to start the changelog.
string changelogStart = ArgumentOrYaml(nameof(changelogStart), string.Empty, yaml);
// The ref to which to end the changelog.
string changelogEnd = ArgumentOrYaml(nameof(changelogEnd), string.Empty, yaml);
// The location of the changelog file to write.
readonly string changelogFile = ArgumentOrYaml(nameof(changelogFile), string.Empty, yaml);
// Specifies the filename of the keystore file. If this is specified, it's assumed you'll provide the other signing properties.
readonly string androidSigningKeyStore = ArgumentOrYaml(nameof(androidSigningKeyStore), string.Empty, yaml);
// Specifies the alias for the key in the keystore.
readonly string androidSigningKeyAlias = ArgumentOrYaml(nameof(androidSigningKeyAlias), string.Empty, yaml);
// Specifies the password to the Android keystore.
readonly string androidSigningStorePass = ArgumentOrYaml(nameof(androidSigningStorePass), string.Empty, yaml);
// Specifies the password of the key within the keystore file.
readonly string androidSigningKeyPass = ArgumentOrYaml(nameof(androidSigningKeyPass), string.Empty, yaml);
// Specifies the APS environment to include in entitlements.
readonly APSEnvironment apsEnvironment = ArgumentOrYaml(nameof(apsEnvironment), APSEnvironment.Development, yaml);
// The valid localizations for this build.
readonly string[] localizations = ArgumentOrYaml(nameof(localizations), string.Empty, yaml).Split(",");
// The Google API Key, used for translations.
readonly string googleAPIKey = ArgumentOrYaml(nameof(googleAPIKey), string.Empty, yaml);
// The App Center token for uploading events, crashes, and so on. Injected into the application at build time.
// If this value is left as `defaultGuid`, it will be determined during the AppCenterId task.
string appCenterId = ArgumentOrYaml(nameof(appCenterId), defaultGuid, yaml);
// The token to use when uploading apps to App Center.
readonly string appCenterToken = ArgumentOrYaml(nameof(appCenterToken), string.Empty, yaml);
// The root Android SDK folder. Sometimes Cake can't find it on build servers.
readonly string androidSdkRoot = ArgumentOrYaml(nameof(androidSdkRoot), string.Empty, yaml);
// The Android package format. APK is still most common, but AAB bundles can be used on Google Play.
readonly AndroidPackageFormat androidPackageFormat = ArgumentOrYaml(nameof(androidPackageFormat), AndroidPackageFormat.Apk, yaml);
// The Android link tool. R8 is newer & better, but Proguard is safer. If none, no DEX linking is performed.
readonly AndroidLinkTool androidLinkTool = ArgumentOrYaml(nameof(androidLinkTool), AndroidLinkTool.None, yaml);
// The name of the company to include in assemblies.
readonly string companyName = ArgumentOrYaml(nameof(companyName), string.Empty, yaml);
// The copyright to include in assemblies.
readonly string copyright = ArgumentOrYaml(nameof(copyright), string.Empty, yaml);
// The path that is opened when the user taps on the Support option in settings.
readonly string supportPath = ArgumentOrYaml(nameof(supportPath), "https://example.com/", yaml);
// The path to a legal info page.
readonly string legalInfoPath = ArgumentOrYaml(nameof(legalInfoPath), string.Empty, yaml);
// This value will be included in the user agent string for web requests.
readonly string userAgent = ArgumentOrYaml(nameof(userAgent), string.Empty, yaml);
// The server to be pre-filled on debug builds.
readonly string debugDefaultServer = ArgumentOrYaml(nameof(debugDefaultServer), string.Empty, yaml);
// The redirect URI for OAuth.
readonly string oauthRedirectUri = ArgumentOrYaml(nameof(oauthRedirectUri), "https://example.com/", yaml);
// The allowed host name for URI team names.
readonly string allowedHost = ArgumentOrYaml(nameof(allowedHost), "https://example.com", yaml);
// The default reachability URI.
readonly string defaultReachabilityUri = ArgumentOrYaml(nameof(defaultReachabilityUri), "https://example.com", yaml);
// The expected Unity message.
readonly string unityMessageLabel = ArgumentOrYaml(nameof(unityMessageLabel), "ExampleUnityMessage", yaml);
// The access key for downloading remote files from AWS S3.
readonly string awsAccessKey = ArgumentOrYaml(nameof(awsAccessKey), string.Empty, yaml);
// The secret key for downloading remote files from AWS S3.
readonly string awsSecretKey = ArgumentOrYaml(nameof(awsSecretKey), string.Empty, yaml);
// The bucket in AWS S3 from which to download remote files.
readonly string awsBucketName = ArgumentOrYaml(nameof(awsBucketName), string.Empty, yaml);
// The files in AWS S3 that should be downloaded to the native references folder.
readonly string[] awsFrameworkFilenames = FilterNullOrWhiteSpace(ArgumentOrYaml(nameof(awsFrameworkFilenames), string.Empty, yaml).Split(",")).ToArray();
// The files in AWS S3 that should be downloaded to the assets folder.
readonly string[] awsAssetFilenames = FilterNullOrWhiteSpace(ArgumentOrYaml(nameof(awsAssetFilenames), string.Empty, yaml).Split(",")).ToArray();
// A flag for testing that ensures the constants file will be unchanged.
readonly bool changeNoConstants = ArgumentOrYaml(nameof(changeNoConstants), false, yaml);
// Derived global parameters
var root = MakeAbsolute(new DirectoryPath("./"));
var isReleaseBuild = configuration == Configuration.Release;
var isApplePlatform = platform == Platform.iPhone || platform == Platform.iPhoneSimulator;
var solution = GetFiles($"./*.sln").First();
var folder = new {
Apple = "PERLS.iOS",
Android = "PERLS.Android",
Assets = "Assets",
Core = "PERLS",
Data = "PERLS.Data",
Impl = "PERLS.DataImplementation",
Test = $"PERLS.Tests",
Temp = $"tmp",
Unity = "UnityLibrary.iOS"
};
var project = new {
Apple = $"./{folder.Apple}/PERLS.iOS.csproj",
Android = $"./{folder.Android}/PERLS.Android.csproj",
Core = $"./{folder.Core}/PERLS.csproj",
Data = $"./{folder.Data}/PERLS.Data.csproj",
Impl = $"./{folder.Impl}/PERLS.DataImplementation.csproj",
Test = $"./{folder.Test}/PERLS.Tests.csproj",
Unity = $"./{folder.Unity}/UnityLibrary.iOS.csproj"
};
var extension = isApplePlatform
? "ipa"
: $"{androidPackageFormat}".ToLower();
var buildPath = root.Combine(new DirectoryPath(buildFolder));
var netAssemblyInfoLocation = File($"./{(isApplePlatform ? folder.Apple : folder.Android)}/Properties/AssemblyInfo.cs");
var appCenterNewline = "\r\n\r\n"; // I'm not sure why, but CRLF x2 is required (specifically for install.appcenter.ms)
var assemblyName = ParseProject(isApplePlatform ? project.Apple : project.Android).AssemblyName;
// Parameters to be defined later
var appVersion = "0.0.0";
var assemblyVersion = "0.0.0.0";
var packageVersion = "0.0.0.0-feat";
var fullSemVersion = "0.0.0-feat.1+1";
var infoVersion = "0.0.0-feat.1+1.Sha";
var branchName = string.Empty;
var changelog = string.Empty;
var gitSha = string.Empty;
var injectedEnvironmentVariables = new Dictionary<string, string>();
FilePath symbolsArchivePath = null;
FilePath bundlePath = null;
// Global methods
string EscapeNewLines(string str) => str.Replace("\n", "\\n");
string UnescapeNewLines(string str) => str.Replace("\\n", "\n");
IEnumerable<KeyValuePair<string, string>> ParseEnvInject(string filename)
{
var readLines = FileReadLines(filename);
var result = new Dictionary<string, string>();
string previousKey = null;
foreach (var line in readLines)
{
var split = line.Split("=");
if (split.Count() != 2)
{
if (string.IsNullOrWhiteSpace(previousKey))
{
Warning($"Unexpected format for line: {line}");
}
else
{
result[previousKey] = $"{result[previousKey]}\n{UnescapeNewLines(line)}";
}
continue;
}
previousKey = split[0];
result[split[0]] = UnescapeNewLines(split[1]);
}
return result;
}
IEnumerable<StatusEntry> RepoFileStatuses(string folder)
{
var repo = new Repository($"{root}");
foreach (var item in repo.RetrieveStatus())
{
yield return item;
}
}
// The next two methods are useful for getting the Resx files to be able to be read by the ResxResourceReader nuget.
// If these are not used, there will be build errors.
string PrepareResxStringForTranslation(string resx)
{
var readResx = resx.Replace(appReadyReaderLine, readableReaderLine);
return readResx.Replace(appReadyWriterLine, readableWriterLine);
}
string PrepareResxStringForApp(string resx)
{
var readResx = resx.Replace(readableReaderLine, appReadyReaderLine);
return readResx.Replace(readableWriterLine, appReadyWriterLine);
}
IEnumerable<Translation> TranslateSingleBlock(IEnumerable<string> toTranslate, string targetLanguage, bool useNeuralMachineTranslation)
{
if (toTranslate.Count() > 128)
{
throw new Exception("Limit each translation block to 128 strings or less.");
}
var request = new GoogleApi.Entities.Translate.Translate.Request.TranslateRequest
{
Target = targetLanguage.FromCode(),
Qs = toTranslate,
Source = GoogleApi.Entities.Translate.Common.Enums.Language.English,
Key = googleAPIKey,
Model = useNeuralMachineTranslation
? GoogleApi.Entities.Translate.Common.Enums.Model.Nmt
: GoogleApi.Entities.Translate.Common.Enums.Model.Base,
};
var response = GoogleTranslate.Translate.Query(request);
if (response.Data.Translations is not ICollection<Translation> translationsList)
{
throw new Exception("Unexpected API response");
}
if (translationsList.Count() != toTranslate.Count())
{
throw new Exception($"The number of returned translations {translationsList.Count()} does not equal the number of requested translations {toTranslate.Count()}. This is likely due to a duplicate string for two separate keys.");
}
return translationsList;
}
IEnumerable<Translation> TranslateMultipleBlocks(IEnumerable<string> text, string targetLanguage)
{
var currentTranslations = new List<Translation>();
var toTranslate = text;
while (toTranslate.Count() > 0)
{
var thisBlock = toTranslate.Take(128);
toTranslate = toTranslate.Skip(128);
try
{
var result1 = TranslateSingleBlock(thisBlock, targetLanguage, true);
currentTranslations.AddRange(result1);
}
catch
{
var result2 = TranslateSingleBlock(thisBlock, targetLanguage, false);
currentTranslations.AddRange(result2);
}
}
return currentTranslations;
}
string TrimStart(string str, string toTrim)
{
var output = str;
while (output.StartsWith(toTrim))
{
output = output.Substring(toTrim.Length);
}
return output;
}
string MakeRelative(string path)
{
return TrimStart(path, $"{root}");
}
bool DirectoriesExist(IEnumerable<string> directories)
{
foreach (var dir in directories)
{
if (!DirectoryExists(dir))
{
return false;
}
}
return true;
}
bool FilesExist(IEnumerable<string> files)
{
foreach (var file in files)
{
if (!FileExists(file))
{
return false;
}
}
return true;
}
IEnumerable<string> FilterNullOrWhiteSpace(IEnumerable<string> source)
{
foreach (var el in source)
{
if (!string.IsNullOrWhiteSpace(el))
{
yield return el;
}
}
}
// a replacement for an identical function in Cake.Git (not ARM supported)
bool GitHasUncommitedChanges(DirectoryPath path)
{
return new Repository($"{path}")
.RetrieveStatus()
.IsDirty;
}
// a replacement for a comparable class in Cake.Git (not ARM supported)
class GitCommit
{
public GitCommit(Commit commit)
{
Sha = commit.Sha;
}
public string Sha { get; }
}
// a replacement for an identical function in Cake.Git (not ARM supported)
ICollection<GitCommit> GitLog(string path, int count)
{
return new Repository($"{path}")
.Commits
.Take(count)
.Select(commit => new GitCommit(commit))
.ToList();
}
// Tasks
// Cleans folders containing cached data.
Task("Clean")
.Does(() =>
{
if (noClean)
{
Warning("Skipping clean step.");
return;
}
CleanDirectories(GetDirectories("./.vs"));
CleanDirectories(GetDirectories("./**/obj"));
CleanDirectories(GetDirectories("./**/bin"));
});
// Restores NuGet packages.
Task("RestorePackages")
.Does(() =>
{
if (noRestore)
{
Warning("Skipping restore step.");
return;
}
NuGetRestore(solution);
});
// Copies resources from a folder within the Assets folder to rebrand the application.
Task("Marketing")
.Does(() =>
{
if (string.IsNullOrWhiteSpace(marketing))
{
Information("Marketing disabled. Skipping.");
return;
}
if (GitHasUncommitedChanges(root) && !force)
{
if (flavor == Flavor.CI)
{
Warning("Ignoring uncommitted changes for CI build.");
}
else
{
Information("Locally modified files:");
foreach (var item in RepoFileStatuses($"{root}"))
{
if (item.State != FileStatus.Ignored)
{
Information($" {item.FilePath}: {item.State}");
}
}
throw new Exception("Marketing targets can only be changed on a clean git repo.");
}
}
// allow fully-qualified paths
var sourcePath = marketing.Contains("Assets")
? new DirectoryPath(marketing)
: new DirectoryPath($"./Assets/{marketing}");
if (!DirectoryExists(sourcePath))
{
throw new Exception($"Unable to find source path \"{sourcePath}\"");
}
CopyDirectory(sourcePath, root);
Information($"Applied marketing {marketing} from {sourcePath} to {root}");
foreach (var item in RepoFileStatuses($"{root}"))
{
if (item.State == FileStatus.NewInWorkdir
&& !item.FilePath.StartsWith(folder.Assets)
&& !item.FilePath.EndsWith(".resx"))
{
throw new Exception($"Unexpected new file in work dir after applying marketing: {item.FilePath}");
}
}
});
// Runs machine translation of the strings files for the desired localizations
Task("MachineTranslation")
.IsDependentOn("RestorePackages")
.Does(() =>
{
// Make sure we are requesting localizations
if (!localizations.Any() || (localizations.Count() == 1 && string.IsNullOrWhiteSpace(localizations[0])))
{
// If there are no localizations we want to default to our English-only version.
Information("Localization disabled. Skipping.");
return;
}
// Load in the proper strings files
// For now we'll translate any Strings.resx or StringsSpecific.resx.
var stringsFiles = System.IO.Directory.GetFiles(folder.Data, "Strings.resx");
var stringsSpecificFiles = System.IO.Directory.GetFiles(folder.Data, "StringsSpecific.resx");
var resxFiles = stringsFiles.Concat(stringsSpecificFiles);
Information($"Found {resxFiles.Count()} Strings files");
var allFiles = new Dictionary<string, List<DictionaryEntry>>();
foreach (var eachFile in resxFiles)
{
Information($"Reading {eachFile}");
var entries = new List<DictionaryEntry>();
var path = $"./{eachFile}";
var resxText = System.IO.File.ReadAllText(path);
var readableText = PrepareResxStringForTranslation(resxText);
System.IO.File.WriteAllText(path, readableText);
using (var resxReader = new ResXResourceReader(path))
{
foreach (DictionaryEntry entry in resxReader)
{
entries.Add(entry);
}
}
allFiles.Add(eachFile, entries);
// After we've created it we need to re-prepare it for the app.
var readingText = System.IO.File.ReadAllText(path);
var appReadyText = PrepareResxStringForApp(readingText);
System.IO.File.WriteAllText(path, appReadyText);
}
// Loop through each language desired and get the translations
foreach (var eachLocalization in localizations)
{
var targetLanguage = (string)eachLocalization;
// Skip over english as that is the base language.
if (targetLanguage == "en")
{
continue;
}
// A quick fix to better support our nuget: https://github.com/vivet/GoogleApi/blob/0554046cbd6f4c9b0b6e72a6a41bf5dcd35aca18/GoogleApi/Entities/Common/Enums/Extensions/StringExtension.cs
if (eachLocalization == "es-MX")
{
targetLanguage = "es-419";
}
// Get the localization for this language
// Loop through each of the files.
foreach (var eachFile in allFiles)
{
// Create new set
var thisTranslationSet = new List<DictionaryEntry>();
var entries = eachFile.Value;
var allKeys = entries.Select(arg => (string)arg.Key);
var allStrings = entries.Select(arg => (string)arg.Value);
var translations = TranslateMultipleBlocks(allStrings, targetLanguage);
for (int i = 0; i < translations.Count(); i++)
{
thisTranslationSet.Add(new DictionaryEntry(allKeys.ElementAt(i), System.Net.WebUtility.HtmlDecode(translations.ElementAt(i).TranslatedText)));
}
// Save the file
var translatedFilePath = $"./{eachFile.Key.Replace(".resx", $".{eachLocalization}.resx")}";
using (var resxWriter = new ResXResourceWriter(translatedFilePath))
{
foreach (var entry in thisTranslationSet)
{
resxWriter.AddResource((string)entry.Key, (string)entry.Value);
}
resxWriter.Generate();
// After we've created it we need to re-prepare it for the app.
var readingText = System.IO.File.ReadAllText(translatedFilePath);
var appReadyText = PrepareResxStringForApp(readingText);
System.IO.File.WriteAllText(translatedFilePath, appReadyText);
}
}
}
Information("Machine translations complete.");
});
Task("Localization")
.Does(() =>
{
if (!localizations.Any() || (localizations.Count() == 1 && string.IsNullOrWhiteSpace(localizations[0])))
{
// If there are no localizations we want to default to our English-only version.
Information("Localization disabled. Skipping.");
return;
}
// Set the proper data in the plist
var info = File($"./{folder.Apple}/Info.plist");
dynamic infoData = DeserializePlist(info);
var languages = localizations;
infoData["CFBundleLocalizations"] = languages.Append("en").ToArray();
SerializePlist(info, infoData);
Information("Localizations complete.");
});
// Retrieves version information using GitVersion, and applies that information to the AssemblyInfo file, plists, and/or Android manifest.
Task("GitVersion")
.Does(() =>
{
GitVersion gitVersion;
try
{
gitVersion = GitVersion(new GitVersionSettings
{
NoFetch = true,
});
}
catch
{
Warning("Failed to assign GitVersion. Version data will not be included in assembly.");
return;
}
assemblyVersion = gitVersion.AssemblySemVer;
packageVersion = gitVersion.NuGetVersion;
appVersion = gitVersion.MajorMinorPatch;
fullSemVersion = gitVersion.FullSemVer;
infoVersion = gitVersion.InformationalVersion;
branchName = gitVersion.BranchName;
gitSha = gitVersion.Sha;
injectedEnvironmentVariables[VersionKey] = fullSemVersion;
Information($"AssemblySemVer: {assemblyVersion}");
Information($"NuGetVersion: {packageVersion}");
Information($"AppVersion: {appVersion}");
Information($"InformationalVersion: {infoVersion}");
Information($"FullSemVer: {fullSemVersion}");
Information($"Branch: {branchName}");
var visible = isReleaseBuild
? new string[] {}
: new [] { folder.Test };
CreateAssemblyInfo(netAssemblyInfoLocation, new AssemblyInfoSettings
{
Version = assemblyVersion,
FileVersion = gitVersion.AssemblySemFileVer,
InformationalVersion = gitVersion.InformationalVersion,
ComVisible = false,
InternalsVisibleTo = visible,
Company = companyName,
Configuration = $"{configuration}",
Title = assemblyName,
Product = assemblyName,
Copyright = copyright,
Description = projectName,
CustomAttributes = new []
{
new AssemblyInfoCustomAttribute
{
NameSpace = "System.Resources",
Name = "NeutralResourcesLanguage",
Value = "en",
},
},
});
});
Task("WriteManifestInfo")
.IsDependentOn("GitVersion")
.Does(() =>
{
if (isApplePlatform)
{
var info = File($"./{folder.Apple}/Info.plist");
dynamic infoData = DeserializePlist(info);
infoData["CFBundleShortVersionString"] = uploadToStore ? appVersion : fullSemVersion;
infoData["CFBundleVersion"] = $"{buildNumber}";
infoData["CFBundleIdentifier"] = packageIdentifier;
infoData["CFBundleName"] = appName;
infoData["CFBundleDisplayName"] = appName;
SerializePlist(info, infoData);
var entitled = File($"./{folder.Apple}/Entitlements.plist");
dynamic entitledData = DeserializePlist(entitled);
entitledData["keychain-access-groups"][0] = $"$(AppIdentifierPrefix){packageIdentifier}";
entitledData["aps-environment"] = $"{apsEnvironment}".ToLower();
SerializePlist(entitled, entitledData);
var settings = File($"./{folder.Apple}/Settings.bundle/Root.plist");
dynamic settingsData = DeserializePlist(settings);
dynamic prefData = settingsData["PreferenceSpecifiers"];
dynamic versionData = prefData[0];
versionData["DefaultValue"] = fullSemVersion;
dynamic buildData = prefData[1];
buildData["DefaultValue"] = $"{buildNumber}";
SerializePlist(settings, settingsData);
}
else
{
var manifest = File($"./{folder.Android}/Properties/AndroidManifest.xml");
var settings = new XmlPokeSettings
{