-
Notifications
You must be signed in to change notification settings - Fork 347
/
build.gradle
2449 lines (2294 loc) · 87.4 KB
/
build.gradle
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
/*
* Gradle file to build the Jar Resolver Unity plugin.
*/
buildscript {
repositories {
mavenCentral()
mavenLocal()
}
}
plugins {
id "com.jetbrains.python.envs" version "0.0.30"
}
/*
* Project level variables
*/
project.ext {
// Set of properties to cache in the project.properties file.
Properties cacheProperties = new Properties()
// Set of directories to *not* search under the Unity root directory when
// searching for components of Unity.
String unitySearchDirExcludesString = findProperty("UNITY_EXCLUDES")
String[] unitySearchDirExcludes =
unitySearchDirExcludesString ?
unitySearchDirExcludesString.tokenize(";") : []
// Save the current OS.
operatingSystem = OperatingSystem.getOperatingSystem()
// Default installation path for Unity based upon the host operating system.
List<String> defaultUnityPaths =
[(OperatingSystem.UNKNOWN): ["Unity"],
(OperatingSystem.MAC_OSX):
["/Applications/Unity/Unity.app/Contents/MacOS/Unity"] +
(new FileNameFinder()).getFileNames(
"/", "Applications/Unity/Hub/Editor/*/Unity.app/Contents/MacOS/Unity"),
(OperatingSystem.WINDOWS):
["\\Program Files\\Unity\\Editor\\Unity.exe"] +
(new FileNameFinder()).getFileNames(
"\\", "Program Files\\Unity\\Hub\\Editor\\*\\Editor\\Unity.exe"),
(OperatingSystem.LINUX): ["/opt/Unity/Editor/Unity"]][operatingSystem]
// Search for the Unity editor executable.
// The Unity editor is required to package the plug-in.
for (defaultUnityPath in defaultUnityPaths) {
unityExe = findFileProperty("UNITY_EXE", new File(defaultUnityPath), false)
if (unityExe != null && unityExe.exists()) break;
}
if (unityExe == null || !unityExe.exists()) {
unityExe = findFileInPath(unityExe.name)
}
if (unityExe == null) {
throw new StopActionException("Unity editor executable (UNITY_EXE) not " +
"found")
}
saveProperty("UNITY_EXE", unityExe, cacheProperties)
// Path fragment that is the parent of the unity executable install location.
// This is used to find the unity root directory from the editor executable.
String unityExeParentPath =
[(OperatingSystem.UNKNOWN): "Editor",
(OperatingSystem.MAC_OSX): "Unity.app/Contents/MacOS",
(OperatingSystem.WINDOWS): "Editor",
(OperatingSystem.LINUX): "Editor"][operatingSystem]
File unityRootDir = findFileProperty(
"UNITY_DIR", new File(unityExe.parentFile.absolutePath -
unityExeParentPath), true)
if (unityRootDir == null) {
throw new StopActionException("Unity root directory (UNITY_DIR) not found.")
}
saveProperty("UNITY_DIR", unityRootDir, cacheProperties)
FileTree unityRootDirTree = fileTree(dir: unityRootDir)
// Find unity engine dll under the root directory.
unityDllPath = getFileFromPropertyOrFileTree(
"UNITY_DLL_PATH", true, {
unityRootDirTree.matching {
include "**/Managed/UnityEngine.dll"
exclude unitySearchDirExcludes
}
})
if (unityDllPath == null) {
throw new StopActionException(
"UnityEngine.dll and UnityEditor.dll directory (UNITY_DLL_PATH) " +
"not found.")
}
saveProperty("UNITY_DLL_PATH", unityDllPath, cacheProperties)
// iOS runtime dll. This is with the playback engine, so the
// structure is different for MacOS and the others.
unityIosPath = getFileFromPropertyOrFileTree(
"UNITY_IOS_PLAYBACK_PATH", true, {
unityRootDirTree.matching {
include "**/PlaybackEngines/iOSSupport/UnityEditor.iOS.Extensions.dll",
"**/PlaybackEngines/iossupport/UnityEditor.iOS.Extensions.dll"
exclude unitySearchDirExcludes
}
})
if (unityIosPath == null) {
// iOS support is *required* to build the iOS resolver.
throw new StopActionException(
"UnityEditor.iOS.Extensions.dll directory (UNITY_IOS_PLAYBACK_PATH) " +
"not found.")
}
saveProperty("UNITY_IOS_PLAYBACK_PATH", unityIosPath, cacheProperties)
// Find xbuild to build the dlls.
xbuildExe = getFileFromPropertyOrFileTree(
"XBUILD_EXE", false, {
unityRootDirTree.matching {
include (operatingSystem == OperatingSystem.WINDOWS ?
"**/bin/xbuild.bat" : "**/xbuild")
exclude unitySearchDirExcludes
}
})
if (xbuildExe == null) {
throw new StopActionException("xbuild not found (XBUILD_EXE)")
}
saveProperty("XBUILD_EXE", xbuildExe, cacheProperties)
// Find mono to determine the distribution being used.
monoExe = getFileFromPropertyOrFileTree(
"MONO_EXE", false, {
unityRootDirTree.matching {
include (operatingSystem == OperatingSystem.WINDOWS ?
"**/bin/mono.bat" : "**/bin/mono")
exclude unitySearchDirExcludes
}
})
saveProperty("MONO_EXE", monoExe, cacheProperties)
// Get the mono distribution version.
def versionRegEx = /^.* version ([^ ]+) .*/
def stdout = new ByteArrayOutputStream()
exec {
commandLine monoExe, "-V"
ignoreExitValue true
standardOutput = stdout
}
def monoVersionList =
stdout.toString().replace("\r\n", "\n").tokenize("\n").findResults {
def versionMatch = it =~ versionRegEx
if (versionMatch.matches()) {
return versionMatch.group(1)
}
return null
}
if (!monoVersionList) {
throw new StopActionException(
sprintf("Unable to determine mono version from %s", monoExe))
}
monoVersion = monoVersionList[0]
// Mono 5.x and above generate .pdb files that are compatible with visual
// studio as opposed to the mono-specific .pdb files.
pdbSupported = monoVersion.tokenize(".")[0].toInteger() >= 5
if (pdbSupported) {
logger.warn(
sprintf("Mono %s detected which will generate .pdb files " +
"that are not compatible with older versions of Unity. " +
"This can be fixed by compiling with Unity 5.6.",
monoVersion))
}
// Get the directory that contains this script.
scriptDirectory = buildscript.sourceFile.getParentFile()
// It can take a while to search for build tools, so cache paths in the project
// properties.
File projectPropertiesFile = new File(scriptDirectory,"gradle.properties")
if (!projectPropertiesFile.exists()) {
logger.info(sprintf("Saving %s to %s",
cacheProperties.stringPropertyNames(),
projectPropertiesFile))
cacheProperties.store(projectPropertiesFile.newWriter(), null)
}
// UnityAssetUploader required environment variables.
unityUsername = findProperty("UNITY_USERNAME")
unityPassword = findProperty("UNITY_PASSWORD")
unityPackageId = findProperty("UNITY_PACKAGE_ID")
unityPackagePath = findFileProperty("UNITY_PACKAGE_PATH", null)
// Whether debug symbols should be included.
debugEnabled = true
// Whether interactive mode tests are enabled.
interactiveModeTestsEnabled =
findProperty("INTERACTIVE_MODE_TESTS_ENABLED", "1") == "1"
// Whether to continue to the next test if one fails.
continueOnFailForTestsEnabled =
findProperty("CONTINUE_ON_FAIL_FOR_TESTS_ENABLED", "1") == "1"
// List of test sessions
testSessions = []
// List of test types that should be included. Controlled by
// "INCLUDE_TEST_TYPES" property. Includes every tests if the property is
// empty.
// DO NOT USE THIS FOR FILTER, Use `actualIncludeTestTypes` instead.
includeTestTypesParam =
TestTypeEnum.toSet(
findProperty("INCLUDE_TEST_TYPES", "").split('\\s+|\\s*,\\s*').toList(),
true)
// List of test types that should be excluded. Controlled by
// "EXCLUDE_TEST_TYPES" property. Excludes none if the property is
// empty.
// DO NOT USE THIS FOR FILTER, Use `actualIncludeTestTypes` instead.
excludeTestTypesParam =
TestTypeEnum.toSet(
findProperty("EXCLUDE_TEST_TYPES", "").split('\\s+|\\s*,\\s*').toList(),
false)
// The actual list of test types to run.
actualIncludeTestTypes = includeTestTypesParam.clone()
actualIncludeTestTypes.removeAll(excludeTestTypesParam)
// List of test modules that should be included. Controlled by
// "INCLUDE_TEST_MODULES" property. Includes every tests if the property is
// empty.
// DO NOT USE THIS FOR FILTER, Use `actualIncludeTestModules` instead.
includeTestModulesParam =
TestModuleEnum.toSet(
findProperty("INCLUDE_TEST_MODULES", "").split('\\s+|\\s*,\\s*').toList(),
true)
// List of test modules that should be excluded. Controlled by
// "EXCLUDE_TEST_MODULES" property. Excludes none if the property is
// empty.
// DO NOT USE THIS FOR FILTER, Use `actualIncludeTestModules` instead.
excludeTestModulesParam =
TestModuleEnum.toSet(
findProperty("EXCLUDE_TEST_MODULES", "").split('\\s+|\\s*,\\s*').toList(),
false)
// The actual list of test module to run.
actualIncludeTestModules = includeTestModulesParam.clone()
actualIncludeTestModules.removeAll(excludeTestModulesParam)
// List of tests to exclude. Controlled by "EXCLUDE_TESTS" property. Excludes
// none if the property is empty.
excludeTestsParam =
new HashSet(findProperty("EXCLUDE_TESTS", "").toLowerCase().split('\\s+|\\s*,\\s*').toList())
// Directory for intermediate and final build outputs.
buildDir = new File(scriptDirectory, "build")
// Directory for external tools.
externalToolsDir = new File(scriptDirectory, "external_tools")
// Directory for testing.
testDir = new File(scriptDirectory, "test_output")
// Version of the plugin (update this with CHANGELOG.md on each release).
pluginVersion = "1.2.183"
// Directory that contains the template plugin.
// Files under this directory are copied into the staging area for the
// plugin.
pluginTemplateDir = new File(scriptDirectory, "plugin")
// Directory where the plugin is staged to be exported as a Unity package.
pluginStagingAreaDir = new File(buildDir, "staging")
// Directory where the build plugin is unpacked to.
pluginExplodedDir = new File(scriptDirectory, "exploded")
// Directory where the UPM package is unpacked to.
pluginUpmDir = new File(scriptDirectory, "upm")
// Base filename of the released plugin.
currentPluginBasename = "external-dependency-manager"
// Base UPM package name of the released plugin.
currentPluginUpmPackageName = "com.google.external-dependency-manager"
// Where the exported plugin file is built before it's copied to the release
// location.
pluginExportFile = new File(buildDir, currentPluginBasename + ".unitypackage")
// Where the exported UPM plugin file is built.
pluginUpmExportFile = new File(buildDir,
currentPluginUpmPackageName + "-" + pluginVersion + ".tgz")
// Directory within the plugin staging area that just contains the plugin.
pluginAssetsDir = new File("Assets", "ExternalDependencyManager")
// Directories within the staging area to export.
pluginExportDirs = [pluginAssetsDir, new File("Assets", "PlayServicesResolver")]
// Directory within the plugin directory that contains the managed DLLs.
pluginEditorDllDir = new File(pluginAssetsDir, "Editor")
// Directory which contains the solution for all C# projects with a project in
// each subdirectory.
pluginSourceDir = new File(scriptDirectory, "source")
// Solution which references all projects used by the plugin.
pluginSolutionFile = new File(pluginSourceDir, "ExternalDependencyManager.sln")
// Versioned release plugin file.
pluginReleaseFile = new File(scriptDirectory,
sprintf("%s-%s.unitypackage",
currentPluginBasename,
pluginVersion))
// Unversioned release plugin file.
pluginReleaseFileUnversioned = new File(scriptDirectory,
sprintf("%s-latest.unitypackage",
currentPluginBasename))
// Location of the Unity asset uploader application.
unityAssetUploaderDir = new File(pluginSourceDir, "UnityAssetUploader")
// Location of the export_unity_package application.
exportUnityPackageDir = new File(pluginSourceDir, "ExportUnityPackage")
// Location of the import_unity_package application.
importUnityPackageDir = new File(pluginSourceDir, "ImportUnityPackage")
// Common arguments used to execute Unity in batch mode.
unityBatchModeArguments = ["-batchmode", "-nographics"]
// Common arguments used to execute Unity in interactive mode.
unityInteractiveModeArguments = ["-gvh_noninteractive"]
// Extension for Unity asset metadata files.
unityMetadataExtension = ".meta"
// Extensions for debug files.
symbolDatabaseExtension = pdbSupported ? ".pdb" : ".dll.mdb"
// Changelog file.
changelog = new File(scriptDirectory, "CHANGELOG.md")
pythonBootstrapDir = new File(externalToolsDir, "python_bootstrap")
pythonBinDir = new File(new File(pythonBootstrapDir, "python"), "bin")
// Python binary after it has been bootstrapped.
pythonExe = new File(pythonBinDir, "python3")
// Pip binary after it has been bootstrapped.
pipExe = new File(pythonBinDir, "pip3")
// Python packages required by export_unity_package.py
exportUnityPackageRequirements = ["absl-py", "PyYAML", "packaging"]
// Python packages required by gen_guids.py
genGuidRequirements = ["absl-py"]
}
// Configure com.jetbrains.python.envs to bootstrap a Python install.
envs {
bootstrapDirectory = project.ext.pythonBootstrapDir
envsDirectory = new File(project.ext.buildDir, "python_envs")
python "python", "3.9.5"
}
/*
* Host operating system.
*/
public enum OperatingSystem {
UNKNOWN, MAC_OSX, WINDOWS, LINUX
/*
* Get the current operating system.
*
* @returns Current host operating system.
*/
public static OperatingSystem getOperatingSystem() {
String os_name = System.getProperty("os.name").toLowerCase()
if (os_name.contains("mac os x")) {
return OperatingSystem.MAC_OSX
} else if (os_name.contains("windows")) {
return OperatingSystem.WINDOWS
} else if (os_name.contains("linux")) {
return OperatingSystem.LINUX
}
return OperatingSystem.UNKNOWN
}
}
/*
* Test Types
*/
public enum TestTypeEnum {
INTEGRATION, // Unity Integration Tests using IntegrationTester framework.
NUNIT, // Tests using NUnit framework
PYTHON, // Tests implemented in Python
GRADLE // Tests implemented in Gradle scripts
// A complete set of all enums
private static HashSet<TestTypeEnum> completeSet;
/*
* Get a complete set of all enums
*
* @returns A complete set of all enums
*/
private static HashSet<TestTypeEnum> getCompleteSet() {
if (completeSet == null) {
completeSet = new HashSet<TestTypeEnum>()
for (TestTypeEnum type : TestTypeEnum.values()) {
completeSet.add(type);
}
}
return completeSet.clone()
}
/*
* Convert a list of strings to a set of enums
*
* @param values A list of case-insensitive strings to convert to enum.
* @param completeSetWhenEmpty Whether to return a complete set if the list
* is empty.
*
* @returns A set of enums
*/
public static HashSet<TestTypeEnum> toSet(
Collection<String> values, Boolean completeSetWhenEmpty) {
def result = new HashSet<TestTypeEnum>()
if ( values == null) {
return completeSetWhenEmpty ? getCompleteSet() : result;
}
for (String value : values) {
def trimmed = value.trim().toUpperCase()
if (!trimmed.isEmpty()) {
result.add(TestTypeEnum.valueOf(trimmed))
}
}
if (result.size() == 0) {
result = completeSetWhenEmpty ? getCompleteSet() : result;
}
return result
}
}
/*
* Test Modules
*/
public enum TestModuleEnum {
ANDROIDRESOLVER, // Tests for Android Resolver
VERSIONHANDLER, // Tests for Version Handler
IOSRESOLVER, // Tests for iOS Resolver
PACKAGEMANAGER, // Tests for Package Manager
CORE, // Tests for reusable C# libraries
TOOL // Tests for build/packaging/release tools
// A complete set of all enums
private static HashSet<TestModuleEnum> completeSet;
/*
* Get a complete set of all enums
*
* @returns A complete set of all enums
*/
private static HashSet<TestModuleEnum> getCompleteSet() {
if (completeSet == null) {
completeSet = new HashSet<TestModuleEnum>()
for (TestModuleEnum type : TestModuleEnum.values()) {
completeSet.add(type);
}
}
return completeSet.clone()
}
/*
* Convert a list of strings to a set of enums
*
* @param values A list of case-insensitive strings to convert to enum.
* @param completeSetWhenEmpty Whether to return a complete set if the list
* is empty.
*
* @returns A set of enums
*/
public static HashSet<TestModuleEnum> toSet(
Collection<String> values, Boolean completeSetWhenEmpty) {
def result = new HashSet<TestModuleEnum>()
if ( values == null) {
return completeSetWhenEmpty ? getCompleteSet() : result;
}
for (String value : values) {
def trimmed = value.trim().toUpperCase()
if (!trimmed.isEmpty()) {
result.add(TestModuleEnum.valueOf(trimmed))
}
}
if (result.size() == 0) {
result = completeSetWhenEmpty ? getCompleteSet() : result;
}
return result
}
}
/*
* Determine whether the test should be run given the filter parameters,
* the current test type and the current test module
*
* @param type Type of the test.
* @param module Module of the test.
*
* @returns True if the test should be run by the given the filters.
*/
boolean shouldTestRunWithFilters(TestTypeEnum type, TestModuleEnum module) {
project.ext.actualIncludeTestTypes.contains(type) &&
project.ext.actualIncludeTestModules.contains(module)
}
/*
* Set the test type and module to the given task.
*
* @param task The task to set the properties to.
* @param type Type of the test.
* @param module Module of the test.
*/
void setTestProperties(Task task, TestTypeEnum type, TestModuleEnum module) {
task.ext.testType = type
task.ext.testModule = module
}
/*
* Unit test for TestTypeEnum
*/
task(testTestTypeEnum) { task ->
setTestProperties(task, TestTypeEnum.GRADLE, TestModuleEnum.TOOL)
doFirst {
ReportTestStarted(task)
}
doLast {
def expectedTestTypeEnumCompleteSet =
new HashSet([
TestTypeEnum.INTEGRATION,
TestTypeEnum.NUNIT,
TestTypeEnum.PYTHON,
TestTypeEnum.GRADLE])
def expectedEmptySet = new HashSet()
def expectedPythonOnlySet = new HashSet([TestTypeEnum.PYTHON])
def expectedPythonAndIntegrationSet = new HashSet([
TestTypeEnum.PYTHON,
TestTypeEnum.INTEGRATION])
assert TestTypeEnum.getCompleteSet().equals(
expectedTestTypeEnumCompleteSet)
assert TestTypeEnum.toSet([], false).equals(
expectedEmptySet)
assert TestTypeEnum.toSet([], true).equals(
expectedTestTypeEnumCompleteSet)
assert TestTypeEnum.toSet(["python"], false).equals(
expectedPythonOnlySet)
assert TestTypeEnum.toSet(["python"], true).equals(
expectedPythonOnlySet)
assert TestTypeEnum.toSet(["PYTHON"], false).equals(
expectedPythonOnlySet)
assert TestTypeEnum.toSet(["PyThOn"], false).equals(
expectedPythonOnlySet)
assert TestTypeEnum.toSet(["Python", "Integration"], false).equals(
expectedPythonAndIntegrationSet)
assert TestTypeEnum.toSet(["Integration", "Python"], false).equals(
expectedPythonAndIntegrationSet)
assert TestTypeEnum.toSet(
["Integration", "Python", "Gradle", "NUnit"], false).equals(
expectedTestTypeEnumCompleteSet)
EvaluateTestResult(task)
}
}
/*
* Unit test for TestModuleEnum
*/
task(testTestModuleEnum) { task ->
setTestProperties(task, TestTypeEnum.GRADLE, TestModuleEnum.TOOL)
doFirst {
ReportTestStarted(task)
}
doLast {
def expectedTestModuleEnumCompleteSet =
new HashSet([
TestModuleEnum.ANDROIDRESOLVER,
TestModuleEnum.VERSIONHANDLER,
TestModuleEnum.IOSRESOLVER,
TestModuleEnum.PACKAGEMANAGER,
TestModuleEnum.CORE,
TestModuleEnum.TOOL])
def expectedEmptySet = new HashSet()
def expectedToolOnlySet = new HashSet([TestModuleEnum.TOOL])
def expectedToolAndAndroidResolverSet = new HashSet([
TestModuleEnum.TOOL,
TestModuleEnum.ANDROIDRESOLVER])
assert TestModuleEnum.getCompleteSet().equals(
expectedTestModuleEnumCompleteSet)
assert TestModuleEnum.toSet([], false).equals(
expectedEmptySet)
assert TestModuleEnum.toSet([], true).equals(
expectedTestModuleEnumCompleteSet)
assert TestModuleEnum.toSet(["tool"], false).equals(
expectedToolOnlySet)
assert TestModuleEnum.toSet(["tool"], true).equals(
expectedToolOnlySet)
assert TestModuleEnum.toSet(["TOOL"], false).equals(
expectedToolOnlySet)
assert TestModuleEnum.toSet(["TooL"], false).equals(
expectedToolOnlySet)
assert TestModuleEnum.toSet(["Tool", "AndroidResolver"], false).equals(
expectedToolAndAndroidResolverSet)
assert TestModuleEnum.toSet(["AndroidResolver", "Tool"], false).equals(
expectedToolAndAndroidResolverSet)
assert TestModuleEnum.toSet([
"AndroidResolver",
"VersionHandler",
"iOSResolver",
"PackageManager",
"Core",
"Tool"], false).equals(
expectedTestModuleEnumCompleteSet)
EvaluateTestResult(task)
}
}
/*
* Test session
*/
public class TestSession {
public String name;
public TestTypeEnum type;
public TestModuleEnum module;
public Boolean isPassed;
}
/*
* Search the path variable for an executable file.
*
* @param filename Name of the file to search for.
*
* @return If found, the File object that references the file, null otherwise.
*/
File findFileInPath(String filename) {
def stdout = new ByteArrayOutputStream()
exec {
executable OperatingSystem.getOperatingSystem() == OperatingSystem.WINDOWS ?
"where" : "which"
args filename
ignoreExitValue true
standardOutput = stdout
}
String resultString = stdout.toString()
return resultString.isEmpty() ? null : new File(resultString)
}
/*
* Get a property value by name searching project properties, system properties
* and environment variables.
*
* @param propertyName Name of the property to search for.
* @param defaultValue Value of the property if it's not found.
*
* @returns Property value as string if found and not empty, null otherwise.
*/
String findProperty(String propertyName, String defaultValue = null) {
Closure valueIsSet = {
valueString -> valueString != null && !valueString.isEmpty()
}
String value = null
for (def queryObject in [project, System]) {
if (queryObject.hasProperty(propertyName)) {
value = queryObject.getProperty(propertyName)
if (valueIsSet(value)) {
return value
}
}
}
value = System.getenv(propertyName)
return valueIsSet(value) ? value : defaultValue
}
/*
* Get a property value by name as a file, searching project properties,
* system properties and environment variables.
*
* @param propertyName Name of the property to search for.
* @param defaultValue Value of the property if it's not found.
* @param mustExist Whether the file must exist.
*
* @returns Property value as a File if found and exists (if mustExist is true),
* null otherwise.
*/
File findFileProperty(String propertyName, File defaultValue = null,
Boolean mustExist = false) {
String foundFilePath = findProperty(
propertyName, defaultValue != null ? defaultValue.absolutePath : null)
File foundFile = foundFilePath != null ? new File(foundFilePath) : null
return foundFile != null && (!mustExist || foundFile.exists()) ?
foundFile : null
}
/*
* Get a File from the specified property or the shortest path in the specified
* FileTree object.
*
* @param propertyName Property name to lookup prior to searching the tree
* for a matching file.
* @param useParentDirectory If set to true, this returns a File object pointing
* at the parent directory of the file that is found.
* @param fileTreeClosure Closure which returns a FileTree object to search.
*
* @return File if it's found and exists, null otherwise.
*/
File getFileFromPropertyOrFileTree(String propertyName,
Boolean useParentDirectory,
fileTreeClosure) {
File fileValue = findFileProperty(propertyName, null, true)
if (fileValue == null) {
// Search for the shortest path to the require file.
fileTreeClosure().files.each { currentFile ->
if (fileValue == null ||
fileValue.absolutePath.length() > currentFile.absolutePath.length()) {
fileValue = currentFile
}
}
if (useParentDirectory && fileValue != null) {
fileValue = fileValue.parentFile
}
}
return fileValue
}
/*
* Set a project property and log it.
*
* @param name Name of the property.
* @param value Value of the property.
* @param properties Map of properties to save to.
*/
void saveProperty(String name, value, Properties properties) {
if (value != null) properties.setProperty(name.toString(), value.toString())
logger.info(sprintf("%s: %s", name, value))
}
/*
* Removes the extension from a filename.
*
* @param fileObj File object to split into a basename and extension.
*
* @returns (basename, extension) tuple where basename is the filename without
* an extension and extension is the extension.
*/
List<String> splitFilenameExtension(File fileObj) {
String filename = fileObj.name
String trimmedFilename = filename
if (trimmedFilename.endsWith(project.ext.unityMetadataExtension)) {
trimmedFilename -= project.ext.unityMetadataExtension
}
if (trimmedFilename.endsWith(".dll.mdb")) {
trimmedFilename -= ".mdb"
}
int extensionIndex = trimmedFilename.lastIndexOf(".")
if (extensionIndex < 0) return [filename, ""]
String basename = filename.substring(0, extensionIndex)
String extension = filename.substring(extensionIndex)
return [basename, extension]
}
/*
* Construct the name of a versioned asset from the source filename and version
* string. If fullVersionPrefix is true, the encoded string takes the form
* ${filename}_version-${version}.${extension}
* if fullVersionPrefix is false, the string takes the form
* ${filename}_v${version}.${extension}
* where extension is derived from the specified filename.
*
* @param fileObj File to add version to.
* @param fullVersionPrefix if true uses the "_version-" otherwise uses "_v-".
* @param postfix Optional string to add before the extensioon.
* @param useVersionDir If true, place the file to be under a folder named after
* the version number, instead of changing the filename.
*
* @returns File which includes an encoded version.
*/
File versionedAssetFile(File fileObj, Boolean fullVersionPrefix,
String postfix, Boolean useVersionDir) {
String basename
String extension
(basename, extension) = splitFilenameExtension(fileObj)
// Encode the DLL version and target names into the DLL in the form...
// ${dllname}_version-${version}.dll
String targetName = basename
String version = project.ext.pluginVersion
File dllDir = fileObj.parent != null ? new File(fileObj.parent) :
new File()
if (!(version == null || version.isEmpty())) {
if (useVersionDir) {
dllDir = new File(dllDir, version)
} else {
targetName += (fullVersionPrefix ? "_version-" : "_v") + version
}
}
String filename = targetName + postfix + extension
return new File(dllDir, filename)
}
/*
* Remove the version component from a path. (Both its filename and its parent
* folder)
*
* @param fileObj File to remove version from.
*
* @returns File with removed version string.
*/
File unversionedAssetFile(File fileObj) {
// Remove the version postfix. Ex.
// "ExternalDependencyManager/Editor/Google.IOSResolver_v1.2.166.dll" ->
// "ExternalDependencyManager/Editor/Google.IOSResolver.dll"
String basename
String extension
(basename, extension) = splitFilenameExtension(fileObj)
def versionRegExFull = /^(.*)_(version-[^-]+)$/
def versionRegExShort = /^(.*)_(v[^v]+)$/
def versionMatch = basename =~ versionRegExShort
if (versionMatch.matches()) {
basename = versionMatch.group(1)
} else {
versionMatch = basename =~ versionRegExFull
if (versionMatch.matches()) {
basename = versionMatch.group(1)
}
}
String filename = basename + extension
// Remove the version folder as well. Ex.
// "ExternalDependencyManager/Editor/1.2.166/Google.IOSResolver.dll" ->
// "ExternalDependencyManager/Editor/Google.IOSResolver.dll"
def versionFolderRegEx = /^[0-9]+\.[0-9]+\.[0-9]+$/
File parent = fileObj.parent != null ? new File(fileObj.parent) : null
if (parent != null) {
String parentFolder = parent.name
def folderMatch = parentFolder =~ versionFolderRegEx
if (folderMatch.matches()) {
parent = parent.parent != null ? new File(parent.parent) : null
}
}
return parent != null ? new File(parent, filename) : new File(filename)
}
/*
* Copy a file.
*
* @param sourceFile File to copy.
* @param targetFile File to write to.
*
* @returns targetFile.
*/
File copyFile(File sourceFile, File targetFile) {
targetFile.parentFile.mkdirs()
logger.info(sprintf("Copy %s -> %s", sourceFile.path, targetFile.path))
targetFile.newOutputStream() << sourceFile.newInputStream()
return targetFile
}
/*
* Copy a list of files from one directory into another.
*
* @param taskName Name of the task.
* @param taskDescription Description of the task.
* @param filesToCopy List of files to copy with paths relative to the source
* directory.
* @param sourceDir Directory to copy files from.
* @param targetDir Directory to copy files into preserving the relative path of
* each file.
* @param dependsOn List of dependencies for the task.
* @param copyFileClosure Closure which takes (sourceFile, targetFile) to copy a
* file.
*
* @returns Task which copies the specified files. The ext.sourceTargetFileMap
* property of the task contains the mapping of source to target files to be
* copied by the task.
*/
Task createCopyFilesTask(String taskName, String taskDescription,
Iterable<File> filesToCopy, File sourceDir,
File targetDir, Iterable<Task> dependsOn,
Closure copyFileClosure) {
Map<File, File> sourceTargetFileMap = filesToCopy.collectEntries {
[(new File(sourceDir, it.path)), (new File(targetDir, it.path))]
}
if (!copyFileClosure) {
copyFileClosure = {
sourceFile, targetFile -> copyFile(sourceFile, targetFile)
}
}
Task copyTask = tasks.create(name: taskName,
description: taskDescription,
type: Task,
dependsOn: dependsOn).with {
inputs.files sourceTargetFileMap.keySet()
outputs.files sourceTargetFileMap.values()
doLast {
sourceTargetFileMap.each { sourceFile, targetFile ->
copyFileClosure(sourceFile, targetFile)
}
}
}
copyTask.ext.sourceTargetFileMap = sourceTargetFileMap
return copyTask
}
/*
* Copy a file, injecting release information if it's a Unity asset metadata
* file.
*
* @param sourceFile File to copy from.
* @param targetFile File to copy to.
*
* @return targetFile.
*/
File copyAssetMetadataFile(File sourceFile, File targetFile) {
if (!sourceFile.name.endsWith(project.ext.unityMetadataExtension)) {
return copyFile(sourceFile, targetFile)
}
String[] lines = sourceFile.text.tokenize("\n")
// Parse the existing version from the asset metadata.
def folderAssetRegEx = /^folderAsset:\s+yes\s*$/
def versionRegEx = /^(-\s+gvh_version-)([a-zA-Z0-9.]+)\s*$/
def exportPathRegEx = /^(-\s+gvhp_exportpath-)(.*)$/
Boolean isFolder = false
String currentVersion = ""
lines.each { String line ->
def versionMatch = line =~ versionRegEx
def folderMatch = line =~ folderAssetRegEx
if (versionMatch.matches()) {
currentVersion = versionMatch.group(2)
} else if (folderMatch.matches()) {
isFolder = true
}
}
Boolean isNotVersioned = (isFolder ||
targetFile.name.startsWith(
"play-services-resolver"))
// Ignore folder assets, they don't need to be versioned.
if (isNotVersioned) return copyFile(sourceFile, targetFile)
Boolean versionChanged = currentVersion != project.ext.pluginVersion
List<String> outputLines = []
lines.each { line ->
if (versionChanged) {
def guidMatch = (line =~ /^(guid:)\s+(.*)/)
def versionLabelMatch = (line =~ versionRegEx)
def exportPathMatch = (line =~ exportPathRegEx)
if (guidMatch.matches() && (sourceFile.name != targetFile.name ||
sourceFile.parent != targetFile.parent ) ) {
// Update the metadata's GUID.
// If a file is renamed we want to make sure Unity imports it as a new
// asset with the new filename.
line = sprintf(
"%s %s",
guidMatch.group(1),
java.util.UUID.randomUUID().toString().replace("-", ""))
} else if (versionLabelMatch.matches()) {
// Update the version metadata for the asset.
line = sprintf("%s%s", versionLabelMatch.group(1),
project.ext.pluginVersion)
} else if (exportPathMatch.matches()) {
// Update the export path of the asset.
line = sprintf("%s%s", exportPathMatch.group(1),
targetFile.path.replaceFirst(/.*\/Assets\//, ""))
line = line.substring(0, line.length() -
project.ext.unityMetadataExtension.length())
}
}
outputLines.add(line)
// If the metadata file does not contain a version label, inject it.
if (currentVersion.isEmpty() && line.startsWith("labels:")) {
outputLines.add(sprintf("- gvh_version-%s", project.ext.pluginVersion))
}
}
targetFile.write(outputLines.join("\n") + "\n")
return targetFile
}
/*
* Build a project with xbuild.
*
* @param taskName Name of the task.
* @param taskDescription Description of the task.
* @param projectToBuild Path to the project to build.
* @param target Target to build in the project.
* @param inputFiles Input files for the project.
* @param outputDir Output directory.
* @param outputFiles List of output file paths relative to the output
* directory.
* @param dependsOn List of dependencies for the task.
*
* @returns Task which builds the specified target.
*/
Task createXbuildTask(String taskName, String taskDescription,
File projectToBuild, String target,
Iterable<File> inputFiles, File outputDir,
Iterable<File> outputFiles, Iterable<Task> dependsOn) {
File intermediatesDir = new File(outputDir, "obj")
File binaryOutputDir = new File(outputDir, "bin")
Iterable<File> outputFilesInBinaryOutputDir = outputFiles.collect {
return new File(binaryOutputDir, it.path)
}
if (project.ext.debugEnabled) {
outputFilesInBinaryOutputDir += outputFilesInBinaryOutputDir.findResults {
return it.name.endsWith(".dll") ?
new File(it.parentFile.path,
splitFilenameExtension(it)[0] +
project.ext.symbolDatabaseExtension) : null
}
}
Iterable<Task> dependsOnTasks = dependsOn ? dependsOn : []
Iterable<Task> compileTaskDependencies = dependsOnTasks.clone()
Iterable<Task> patchVersionFilesTasks = inputFiles.findResults {
if (it.name == "VersionNumber.cs") {
File versionFile = it
Task patchVersionTask = tasks.create(
name: taskName + "AddVersionTo" + it.name,
description: "Add version to " + it.path,