forked from googlesamples/unity-jar-resolver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
build.gradle
1465 lines (1364 loc) · 53.8 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 {
jcenter()
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(";") :
["**/PackageManager/Editor"]
// 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/UnityHub/*/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 ?
"**/Mono/bin/xbuild.bat" : "**/xbuild")
exclude unitySearchDirExcludes
}
})
if (xbuildExe == null) {
throw new StopActionException("xbuild not found (XBUILD_EXE)")
}
saveProperty("XBUILD_EXE", xbuildExe, cacheProperties)
// Find the NUnit framework dll.
unityNUnitDll = getFileFromPropertyOrFileTree(
"UNITY_NUNIT_PATH", true, {
unityRootDirTree.matching {
include "**/nunit.framework.dll"
exclude unitySearchDirExcludes
}
})
if (unityNUnitDll == null) {
logger.warn("Unity NUnit DLL not found, tests will not build.")
}
saveProperty("UNITY_NUNIT_PATH", unityNUnitDll, cacheProperties)
// nunit-console is used to run tests.
nunitConsoleExe = getFileFromPropertyOrFileTree(
"NUNIT_CONSOLE_EXE", false, {
unityRootDirTree.matching {
include (operatingSystem == OperatingSystem.WINDOWS ?
"**/Mono/bin/nunit-console2.bat" :
"**/nunit-console2")
exclude unitySearchDirExcludes
}
})
if (nunitConsoleExe == null) {
logger.warn("nunit_console not found (NUNIT_CONSOLE_EXE) C# unit test " +
"execution will fail.")
}
saveProperty("NUNIT_CONSOLE_EXE", nunitConsoleExe, cacheProperties)
// It can take a while to search for build tools, so cache paths in the project
// properties.
File projectPropertiesFile = new File("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 = findProperty("NDEBUG") == null
// Get the directory that contains this script.
scriptDirectory = buildscript.sourceFile.getParentFile()
// Directory for intermediate and final build outputs.
buildDir = new File(scriptDirectory, "build")
// Directory for testing.
testDir = new File(scriptDirectory, "test_output")
// 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")
// Where the exported plugin file is built before it's copied to the release
// location.
pluginExportFile = new File(buildDir, "plugin.unitypackage")
// Directory within the plugin staging area that just contains the plugin.
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("source")
// Solution which references all projects used by the plugin.
pluginSolutionFile = new File(pluginSourceDir, "JarResolver.sln")
// Version of the plugin (update this with CHANGELOG.md on each release).
pluginVersion = "1.2.135.0"
// Semantic version of the plugin.
pluginVersionSemVer = pluginVersion.tokenize(".")[0..2].join(".")
// Base filename of the released plugin.
currentPluginBasename = "play-services-resolver"
// Versioned release plugin file.
pluginReleaseFile = new File(scriptDirectory,
sprintf("%s-%s.unitypackage",
currentPluginBasename,
pluginVersion))
// Common arguments used to execute Unity in batch mode.
unityBatchModeArguments = ["-batchmode", "-nographics"]
// Extension for Unity asset metadata files.
unityMetadataExtension = ".meta"
// Extension for debug files.
dllMdbExtension = ".mdb"
// Changelog file.
changelog = new File(scriptDirectory, "CHANGELOG.md")
pythonBootstrapDir = new File(buildDir, "python_bootstrap")
// Python binary after it has been bootstrapped.
pythonExe = new File(new File(new File(pythonBootstrapDir, "python"), "bin"),
"python3")
}
// 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.7.4"
}
/*
* 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
}
}
/*
* 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))
}
/*
* Make sure the NUnit DLL property is set.
*/
void checkNUnitDllPath() {
if (project.ext.unityNUnitDll == null) {
throw new StopActionException("NUnit DLL not found.")
}
}
/*
* Make sure the NUnit console property is set.
*/
void checkNUnitConsolePath() {
if (project.ext.nunitConsoleExe == null) {
throw new StopActionException("NUnit Console not found.")
}
}
/*
* 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
int extensionIndex =
(filename - project.ext.unityMetadataExtension -
project.ext.dllMdbExtension).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. The encoded string takes the form
* ${filename}_v${version}.${extension}
* where extension is derived from the specified filename.
*
* @param fileObj File to add version to.
*
* @returns File which includes an encoded version.
*/
File versionedAssetFile(File fileObj) {
String basename
String extension
(basename, extension) = splitFilenameExtension(fileObj)
// Encode the DLL version and target names into the DLL in the form...
// ${dllname}_v${version}.dll
String targetName = basename
String version = project.ext.pluginVersion
if (!(version == null || version.isEmpty())) {
targetName += "_v" + version
}
String filename = targetName + extension
return fileObj.parent != null ? new File(fileObj.parent, filename) :
new File(filename)
}
/*
* Remove the version component from a filename.
*
* @param fileObj File to remove version from.
*
* @returns File with removed version string.
*/
File unversionedAssetFile(File fileObj) {
String basename
String extension
(basename, extension) = splitFilenameExtension(fileObj)
def versionRegEx = /^(.*)_(v[^v]+)$/
def versionMatch = basename =~ versionRegEx
if (versionMatch.matches()) {
basename = versionMatch.group(1)
}
String filename = basename + extension
return fileObj.parent != null ?
new File(fileObj.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.split("\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*$/
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
}
}
// Ignore folder assets, they don't need to be versioned.
if (isFolder) 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)
if (guidMatch.matches() && sourceFile.name != targetFile.name) {
// 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)
}
}
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)
}
Iterable<Task> dependsOnTasks = dependsOn ? dependsOn : []
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,
type: Task,
dependsOn: dependsOnTasks)
patchVersionTask.with {
inputs.files files([versionFile])
outputs.files files([versionFile])
doLast {
String[] lines = versionFile.text.split("\n")
List<String> outputLines = lines.collect {
it.replaceAll(
/(^.*VERSION_STRING[ ]*=[ ]*\")([^\"]+)(\".*)/,
'$1' + project.ext.pluginVersion + '$3')
}
String patchedFileString = (outputLines.join("\n") + "\n")
if (versionFile.text != patchedFileString) {
print("Patch " + versionFile.name)
versionFile.write(patchedFileString)
}
}
}
return patchVersionTask
}
}
Task task = tasks.create(name: taskName,
description: taskDescription,
type: Exec,
dependsOn: patchVersionFilesTasks ?
patchVersionFilesTasks :
dependsOnTasks).with {
inputs.files inputFiles
outputs.files files(outputFilesInBinaryOutputDir)
executable project.ext.xbuildExe
workingDir projectToBuild.parentFile.absolutePath
args ([sprintf("/target:%s", target),
sprintf("/property:UnityHintPath=%s",
project.ext.unityDllPath.absolutePath),
sprintf("/property:UnityIosPath=%s",
project.ext.unityIosPath.absolutePath),
sprintf("/property:NUnityHintPath=%s",
project.ext.unityNUnitDll ?
project.ext.unityNUnitDll.absolutePath: ""),
sprintf("/property:BaseIntermediateOutputPath=%s%s",
intermediatesDir.absolutePath,
File.separator),
sprintf("/property:OutputPath=%s%s",
binaryOutputDir.absolutePath,
File.separator),
projectToBuild.absolutePath])
}
task.ext.buildDir = outputDir
return task
}
/*
* Generates tasks to compile a plugin DLL and copy it to plugin staging
* area directory.
*
* @param componentName Basename of the generated tasks.
* @param projectName Name of the project under
* source/${projectName}/${projectName}.csproj to build.
* @param assemblyDllBasename Basename of the output DLL generated from the
* specified project.
* @param versionDll Whether the output DLL filename should contain the plugin
* version.
* @param dependsOn List of tasks that should be completed before this plugin
* task is executed.
*
* @returns Task that builds the DLL to the build output folder.
*/
Task createBuildPluginDllTask(String componentName,
String projectName,
String assemblyDllBasename,
Boolean versionDll,
Iterable<Task> dependsOn = null) {
File projectDir = new File(project.ext.pluginSourceDir, projectName)
File projectBuildDir = new File(project.ext.buildDir, projectName)
List<File> buildFiles = [new File(assemblyDllBasename)]
if (project.ext.debugEnabled) {
buildFiles += [new File(assemblyDllBasename + project.ext.dllMdbExtension)]
}
// Compile the C# project.
Task compileTask = createXbuildTask(
sprintf("compile%s", componentName), sprintf("Compile %s", projectName),
project.ext.pluginSolutionFile, projectName,
fileTree(new File(projectDir, "src")), projectBuildDir,
buildFiles, dependsOn)
compileTask.ext.componentName = componentName
// Template metadata for the built DLL.
Iterable<File> assemblyDllMetaFiles = buildFiles.collect {
new File(new File(project.ext.pluginTemplateDir,
project.ext.pluginEditorDllDir.path),
it.name + project.ext.unityMetadataExtension)
}
// Optionally map unversioned to versioned filenames.
Iterable<File> unversionedFiles = files(compileTask.outputs.files,
assemblyDllMetaFiles)
File stagingDir = new File(new File(projectBuildDir,
project.ext.pluginStagingAreaDir.name),
project.ext.pluginEditorDllDir.path)
Map<String, File> stagingFileMap =
unversionedFiles.collectEntries { File unversionedFile ->
File unversionedOutputFile = new File(stagingDir.path,
unversionedFile.name)
return [
unversionedFile.path,
versionDll ?
versionedAssetFile(unversionedOutputFile) :
unversionedOutputFile]
}
// Copy files to the staging directory for this project.
Task copyTask = tasks.create(
name: sprintf("copy%sStaging", componentName),
type: Task,
description: sprintf("Copy %s DLLs to the plugin staging dir.",
projectName),
dependsOn: [compileTask]).with {
inputs.files unversionedFiles
outputs.files stagingFileMap.values()
doLast {
inputs.files.each {
File inputFile ->
copyAssetMetadataFile(inputFile, stagingFileMap[inputFile.path])
}
}
}
copyTask.ext.stagingDir = stagingDir
copyTask.ext.componentName = componentName
// Generate a clean target for this project.
Task cleanTask = tasks.create(name: sprintf("clean%s", projectName),
description: sprintf("Clean %s plugin DLL", projectName),
type: Delete).with {
delete (files(compileTask.outputs.files,
copyTask.outputs.files,
projectBuildDir))
}
cleanTask.ext.componentName = componentName
// Return the build target for this project.
Task buildTask =
tasks.create(name: sprintf("build%s", componentName),
description: sprintf("Build %s plugin DLL",
projectName),
dependsOn: [copyTask])
buildTask.ext.componentName = componentName
return buildTask
}
/*
* Create a Nunit test task.
*
* @param name Name of the task.
* @param description Description of the task.
* @param testDll Test DLL to execute. The log file will be placed in the
* parent directory of this DLL path.
* @param dependsOn Dependencies of the new task.
*
* @returns Task which executes nunit-console.
*/
Task createNUnitTask(String name, String description, File testDll,
Iterable<Task> dependsOn) {
File logFileDir = testDll.parentFile.parentFile
File logFile = new File(logFileDir, name + ".log")
File xmlLogFile = new File(logFileDir, name + ".xml")
return tasks.create(name: name,
description: description,
type: Exec,
dependsOn: dependsOn).with {
workingDir project.ext.pluginSourceDir
inputs.files testDll
outputs.files logFile
executable project.ext.nunitConsoleExe
args ([sprintf("-output:%s", logFile.absolutePath),
sprintf("-xml:%s", xmlLogFile.absolutePath),
testDll.absolutePath])
doFirst { checkNUnitConsolePath() }
}
}
/*
* Create a task to run an executable.
*
* @param name Name of the task.
* @param description Description of the task.
* @param dependsOn Tasks this depends upon.
* @param executable Executable to run.
* @param arguments Arguments for the executable.
*
* @returns Task which runs the specified executable.
*/
Task createExecTask(String name, String description,
Iterable<Task> dependsOn, File executableToRun,
Iterable<String> arguments) {
Task execTask = tasks.create(name: name,
description: description,
type: Exec,
dependsOn: dependsOn)
execTask.with {
executable executableToRun
args arguments
}
return execTask
}
/*
* Create a task to execute Unity.
*
* @param taskName Name of the task to create.
* @param summary Description of the operation being performed with Unity.
* "create" is a reserved operation that creates a project. This is used to
* generate the log file name so should be unique for the project and ideally
* not contain whitespace.
* @param dependsOn Dependencies of the new task.
* @param projectName Name of the project directory to use.
* @param projectContainerDir Directory that contains the project directory.
* @param arguments Command line arguments to pass to Unity.
* @param batchMode Whether to run Unity in batch mode.
* @param createTaskClosure Optional task used to start Unity, this must
* conform to createExecTask()
*
* @returns Task which executes Unity.
* The following extended properties are set on the task:
* - ext.projectDir: Directory of the created Unity project.
* - ext.containerDir: Directory which contains the Unity project and the logs.
* This is the same as projectContainerDir.
* - ext.logFile: Unity log file from the operation.
*/
Task createUnityTask(String taskName, String summary,
Iterable<Task> dependsOn, String projectName,
File projectContainerDir, Iterable<String> arguments,
Boolean batchMode, createTaskClosure) {
Boolean createProject = summary == "create"
File logFile = new File(projectContainerDir,
sprintf("%s_%s.log", projectName, summary))
File projectDir = new File(projectContainerDir, projectName)
List<String> executeArguments = []
if (batchMode) executeArguments += unityBatchModeArguments
executeArguments += [
"-logFile", logFile.absolutePath,
createProject ? "-createProject" : "-projectPath", projectDir.absolutePath]
if (createProject) executeArguments += ["-quit"]
executeArguments += arguments
if (!createTaskClosure) {
createTaskClosure = {
String name, String description, Iterable<Task> depends,
File executable, Iterable<String> args ->
return createExecTask(name, description, depends, executable, args)
}
}
Task unityTask = createTaskClosure(taskName,
sprintf(
"Run Unity to %s (project: %s)",
summary, projectName),
dependsOn,
project.ext.unityExe,
executeArguments)
unityTask.with {
inputs.files fileTree(projectDir)
outputs.files files(logFile)
}
unityTask.ext.projectDir = projectDir
unityTask.ext.containerDir = projectContainerDir
unityTask.ext.logFile = logFile
return unityTask
}
/*
* Create a task that generates a Unity project.
*
* @param taskName Name of the task.
* @param dependsOn Dependencies of the new task.
* @param projectName Name of the project directory to create.
* @param projectContainerDir Directory to create the project directory in.
*
* @returns Task which executes Unity.
* The following extended properties are set on the task:
* - ext.projectDir: Directory of the created Unity project.
* - ext.containerDir: Directory which contains the Unity project and the logs.
* This is the same as projectContainerDir.
* - ext.logFile: Unity log file from the operation.
*/
Task createUnityProjectTask(String taskName, Iterable<Task> dependsOn,
String projectName, File projectContainerDir) {
return createUnityTask(taskName, "create", dependsOn, projectName,
projectContainerDir, [], true, null).with {
doFirst {
// Clean / create the output directory.
delete ext.containerDir
ext.containerDir.mkdirs()
}
}
}
/*
* Setup a Unity project for a testing task and import the plugin in
* preparation for testing.
*
* @param taskName Name of the test task.
* @param dependsOn Dependencies of the new task.
* @param projectName Name of the Unity project to create.
* @param batchMode Whether to run Unity in batch mode.
*
* @returns Task which sets up a Unity project.
* The following extended properties are set on the task:
* - ext.projectDir: Directory of the created Unity project.
* - ext.containerDir: Directory which contains the Unity project and the logs.
* - ext.logFile: Unity log file for the import operation.
*/
Task createSetupUnityProjectTask(String taskName, Iterable<Task> dependsOn,
String projectName, Boolean batchMode) {
File outputDir = new File(project.ext.testDir, projectName)
Task createProject = createUnityProjectTask(
sprintf("create%s", taskName), dependsOn, projectName, outputDir)
createProject.with {
inputs.files files(project.ext.pluginExportFile)
}
return createUnityTask(
taskName, "import_plugin", [createProject], projectName, outputDir,
["-importPackage", project.ext.pluginExportFile.absolutePath,
"-quit"], batchMode, null)
}
/*
* Creates a task which runs a test with the Unity plugin.
*
* @param taskName Name of the test.
* @param description Description of the task.
* @param dependsOn Dependencies of the new task.
* @param testScriptsDir Directory containing scripts to copy into the test
* project and execute for testing.
* @param additionalArguments Additional arguments to pass to Unity when
* executing the test.
* @param batchMode Whether to execute Unity in batch mode.
* @param createTaskClosure Optional task used to start Unity, this must
* conform to tasks.create(name, description, type, dependsOn).
*
* @returns Test task.
*/
Task createUnityTestTask(String taskName, String description,
Iterable<Task> dependsOn, File testScriptsDir,
Iterable<String> additionalArguments,
Boolean batchMode, createTaskClosure) {
List<File> inputFiles = fileTree(testScriptsDir).collect {
new File(it.absolutePath - testScriptsDir.absolutePath)
}
// Setup the Unity project.
Task setupTestProject = createSetupUnityProjectTask(
sprintf("setup%s", taskName), dependsOn, taskName, batchMode)
setupTestProject.with {
inputs.files inputFiles
}
// Task which copies test scripts into the project.
Task copyTestScripts = createCopyFilesTask(
sprintf("copyScriptsFor%s", taskName),
sprintf("Copy the test scripts into the %s Unity project.", taskName),
inputFiles, testScriptsDir, setupTestProject.ext.projectDir,
[setupTestProject], null)
// Create the test task.
Task testTask = createUnityTask(taskName, "test", [copyTestScripts],
setupTestProject.ext.projectDir.name,
setupTestProject.ext.containerDir,
additionalArguments, batchMode,
createTaskClosure)
testTask.description = description
// Create a clean task
Task cleanTestTask = tasks.create(name: sprintf("clean%s", taskName),
description: sprintf("Clean %s", taskName),
type: Delete).with {
delete setupTestProject.ext.containerDir
}
return testTask
}
/*
* Creates a task which runs tests with the Unity plugin in batch and
* non-batch modes.
*
* @param taskName Name of the test.
* @param description Description of the task.
* @param dependsOn Dependencies of the new task.
* @param testScriptsDir Directory containing scripts to copy into the test
* project and execute for testing.
* @param additionalArguments Additional arguments to pass to Unity.
* @param createTaskClosure Optional task used to start Unity, this must