-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathinstallerutils.gradle
919 lines (830 loc) · 33.6 KB
/
installerutils.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
/**
* Copies the installer artifacts to the destination folder
*
* */
String copyArtifacts(String destination, String platform, boolean dev) {
configurations.providedModule.each { File file ->
println("Copying module ${file.name} to " + destination)
logger.quiet("Copying module ${file.name} to " + destination)
copy {
from file
into destination
}
}
def extension = ""
if (dev) {
extension = "Dev"
}
copy {
from {
zipTree(fatJarDev.archivePath)
}
{
exclude 'version/version.xml'
exclude 'META-INF/license/' //exclude the licence folder which is a pain because a licence file exists already
}
from {
getVersionFilePath(platform, jdk, "installer", extension)
}
{
into 'version/'
}
into "${buildDir.getAbsolutePath()}${File.separator}tmp${File.separator}simplejar"
}
File archivePath = new File(destination + "/" + applicationName + ".jar")
ant.zip(destfile: archivePath.getAbsolutePath()) {
fileset(dir: "${buildDir.getAbsolutePath()}${File.separator}tmp${File.separator}simplejar") {
}
}
signJar(archivePath)
return archivePath.getName()
}
public void platformImage(String inputFolder, String platform, boolean dev, String mainJar) {
if (jdk != null && !jdk.isEmpty()) {
String enableAssertions = ""
String extension = ""
if (dev) {
enableAssertions = "-ea"
extension = "dev"
}
String destination = "${project.projectDir.absolutePath}${File.separator}deploy${File.separator}${platform}${extension}${File.separator}bundle";
file(destination).list().each {
f -> delete "$destination/${f}"
}
//bundle
String packageType = "app-image"
String modulePath = "\$APPDIR"
String icon = "deploy/icon.ico"
def javafxpackager;
if (platform.contains("mac")) {
packageType = "pkg";
icon = "deploy/icon.icns";
javafxpackager = exec {
environment "JAVA_HOME", "${jdk}" //why oh why...
workingDir "${project.projectDir.absolutePath}"
commandLine "${jdk}/bin/jpackage",
"--type", packageType,
"--input", inputFolder,
"--dest", destination,
"--name", "${applicationName}",
"--main-class", "${mainClass}",
"--main-jar", mainJar,
"--icon", icon,
"--app-version", "${applicationVersion}",
"--vendor", "ACS-Embrace",
// don't specify --add-modules, will override and prevent default module extraction for runtime generation
"--verbose",
"--mac-sign",
"--mac-signing-key-user-name","Associated Computer Solutions Pty Ltd (6HJK32YW76)",
"--mac-signing-keychain","${keychain_path}",
"--java-options",
"\"--module-path=" + modulePath + "\"",
"--java-options", (enableAssertions + " " + getPackagerProperties() + getPackagerOptions()).trim()
logger.quiet(commandLine.toString())
}
} else {
javafxpackager = exec {
environment "JAVA_HOME", "${jdk}" //why oh why...
workingDir "${project.projectDir.absolutePath}"
commandLine "${jdk}/bin/jpackage",
"--type", packageType,
"--input", inputFolder,
"--dest", destination,
"--name", "${applicationName}",
"--main-class", "${mainClass}",
"--main-jar", mainJar,
"--icon", icon,
"--app-version", "${applicationVersion}",
"--vendor", "ACS-Embrace",
// don't specify --add-modules, will override and prevent default module extraction for runtime generation
"--verbose",
"--java-options",
"\"--module-path=" + modulePath + "\"",
"--java-options", (enableAssertions + " " + getPackagerProperties() + getPackagerOptions()).trim()
//NB!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//to debug, run with --win-console option!
// commandLine "${jdk}/bin/jpackager",
// "create-image",
// "--input",inputFolder,
// "--output","${project.projectDir.absolutePath}${File.separator}deploy${File.separator}${platform}${extension}${File.separator}bundle",
// "--name", "${applicationName}",
// "--class", "${mainClass}",
// "--main-jar", mainJar,
// "--icon", "deploy/icon.ico",
// "--version","${applicationVersion}",
// "--vendor", "ACS-Embrace",
// "--add-modules", "jdk.unsupported.desktop", //specifically add this module to the runtime because the new swing needs it
// "--verbose",
// "--jvm-args", (enableAssertions + " --module-path=. " + getPackagerProperties() + getPackagerOptions()).trim()
logger.quiet(commandLine.toString())
// doLast {
// if (execResult != 0) {
// throw new GradleException("Error in packaging")
// }
// }
}
}
if (platform.contains("linux")) {
packageType = "deb";
}
if (platform.contains("win")) {
removeInvalidOptions(destination);
} //removes 2 lines that jpackage adds after 15.0.2 which break the installer
//make executable
logger.quiet("Building executable")
buildDistributable(platform, platform, dev);
File file = new File("${project.projectDir.absolutePath}/deploy/${platform}service/MakeInstaller.iss");
logger.quiet("Checking for service installer files")
if (file.exists()) {
logger.quiet("Building service installer")
String serviceDestination = "${project.projectDir.absolutePath}${File.separator}deploy${File.separator}${platform}service${File.separator}bundle";
logger.quiet("Service bundle " + serviceDestination)
File serviceBundle = new File(serviceDestination)
serviceBundle.mkdirs()
serviceBundle.list().each {
f -> delete "$serviceDestination/${f}"
}
copy {
from destination
into serviceDestination
}
buildDistributable(platform, platform + "service", dev); //try and build a service version
}
}
}
void removeInvalidOptions(String destination) {
File configFile = new File(destination + "/${applicationName}/app/${applicationName}.cfg")
def lines = configFile.readLines()
BufferedWriter w = configFile.newWriter()
for (String line : lines) {
if (!line.equals("java-options=--module-path") && !line.equals("java-options=\$APPDIR\\mods")) {
w.write(line)
}
w.newLine()
}
w.close()
}
void buildDistributable(String platform, String folder, boolean dev) {
println("Building distributable");
String extension = "";
if (dev) {
folder = folder + "dev";
extension = "Dev";
}
println("output folder " + folder)
String appDesc = ""
String appName = ""
String ext = ""
if (platform.contains("win")) {
ext = ".exe";
appDesc = "windows-x64"
if (dev) {
appDesc = appDesc + "-dev"
}
if (folder.contains("service")) {
appDesc = appDesc + "-service";
}
fileTree("${project.projectDir.absolutePath}/deploy/${folder}/").matching {
include "MakeInstaller*"
}.each { File it ->
println("Running " + it.getName())
// do some operations
String[] split = it.getName().replace(".iss", "").split("-");
String client = "";
if (split.length > 1) {
client = "-" + split[1];
}
appName = getAppName(appDesc) + client + ext
println("App name: " + appName)
setIssVersionAndName(it.getAbsolutePath(), getAppName(appDesc) + client) //no ext on this
println("Iss version has been set")
String issFileName = it.getName();
def runInno = exec {
workingDir "${project.projectDir.absolutePath}/deploy/${folder}"
//commandLine "Compil32", "/cc", "MakeInstaller.iss"
println(issFileName)
if (project.hasProperty('Compil32Path')) {
println("compil32 " + Compil32Path)
commandLine Compil32Path, "/cc", issFileName
} else {
println("no compil32 specified")
commandLine "compil32", "/cc", issFileName
}
println(commandLine.toString())
}
println("Built " + it.getName())
copy{
from "${project.projectDir.absolutePath}/deploy/${folder}/Output/${appName}"
into "${project.projectDir.absolutePath}/deploy/artifacts"
}
}
appName = getAppName(appDesc) + ext //without the client part
} else if (platform.contains("mac")) {
ext = ".pkg";
appDesc = "macos-x64"
if (dev) {
appDesc = appDesc + "-dev"
}
appName = getAppName(appDesc) + ext
// on macOS, move and rename the generated .pkg to match our convention
String generatedFile = "${applicationName}-${applicationVersion}" + ext
String desiredName = getAppName(appDesc) + ext
String prefixPath = "${project.projectDir.absolutePath}/deploy/${folder}"
copy {
from "${prefixPath}/bundle/${generatedFile}"
into "${prefixPath}/Output"
}
file("${prefixPath}/Output/${generatedFile}").renameTo(file("${prefixPath}/Output/${desiredName}"))
} else if (platform.contains("linux")){
ext = "-1_amd64.deb";
appDesc = "linux-x64"
if (dev) {
appDesc = appDesc + "-dev"
}
appName = getAppName(appDesc) + ext
//move and rename the generated .deb to match our convention
String generatedFile = ("${applicationName}").toLowerCase()+"_${applicationVersion}" + ext
String desiredName = getAppName(appDesc) + ext
String prefixPath = "${project.projectDir.absolutePath}/deploy/${folder}"
copy {
from "${prefixPath}/bundle/${generatedFile}"
into "${prefixPath}/Output"
}
file("${prefixPath}/Output/${generatedFile}").renameTo(file("${prefixPath}/Output/${desiredName}"))
}
copy{
from "${project.projectDir.absolutePath}/deploy/${folder}/Output/${appName}"
into "${project.projectDir.absolutePath}/deploy/artifacts"
}
//copy it to the artifacts folder
copy {
from "${project.projectDir.absolutePath}/deploy/${folder}/Output/${appName}"
into "${project.projectDir.absolutePath}/deploy/artifacts"
}
def archName = getAppName("${appDesc}-installer") + ".jar"
def outPath = "${project.projectDir.absolutePath}/deploy/${folder}/Output/"
copy {
from {
getVersionFilePath(platform, jdk, "installer", extension)
}
from {
"${project.projectDir.absolutePath}/deploy/${folder}/Output/${appName}"
} {
into "installer/"
}
into "${buildDir.getAbsolutePath()}${File.separator}tmp${File.separator}installerjar"
}
String installerJar = outPath + archName
File archivePath = new File(installerJar)
ant.zip(destfile: archivePath.getAbsolutePath()) {
fileset(dir: "${buildDir.getAbsolutePath()}${File.separator}tmp${File.separator}installerjar") {
}
}
signJar(archivePath)
copy {
from outPath + archName
into "${project.projectDir.absolutePath}/deploy/artifacts"
}
delete {
delete(outPath + archName)
delete(outPath + appName)
}
}
//task javaFXInstallerDev (dependsOn: fatJarDev) {
// doFirst {
// configurations.providedModule.each { File file ->
// logger.quiet("Copying module ${file.name} to libs dir")
// copy {
// from file
// into "${buildDir.name}${File.separator}${libsDir.name}"
// }
// }
// signJar(fatJarDev.archivePath)
// if (jdk != null && !jdk.isEmpty()) {
// def javafxpackager = exec {
// environment "JAVA_HOME", "${jdk}" //why oh why...
// workingDir "${project.projectDir.absolutePath}"
// commandLine "${jdk}/bin/jpackager",
// "create-image",
// "--input","${buildDir.name}${File.separator}${libsDir.name}",
// "--output","${project.projectDir.absolutePath}${File.separator}deploy${File.separator}win64dev${File.separator}bundle",
// "--name", "${applicationName}",
// "--class", "${mainClass}",
// //"--module", "ALL-UNNAMED",
// //"--add-modules", "java.xml",
// "--main-jar", fatJarDev.archiveName,
// "--icon", "deploy/icon.ico",
// "--version","${applicationVersion}",
// "--vendor", "ACS-Embrace",
// "--verbose",
// "--jvm-args", ("-ea --module-path=. " + getPackagerProperties() + getPackagerOptions()).trim()
//
//
// //args(getBundleProperties())
// //args(getBundleOptions())
// logger.quiet(commandLine.toString())
// //logger.quiet(commandLine.toString())
// }
//
// //make executable
// setIssVersionAndName("${project.projectDir.absolutePath}/deploy/win64dev/MakeInstaller.iss", getAppName("windows-x64-dev"))
// def runInno = exec {
// workingDir "${project.projectDir.absolutePath}/deploy/win64dev"
// commandLine "compil32", "/cc", "MakeInstaller.iss"
// logger.quiet(commandLine.toString())
// }
// //copy it to the artifacts folder
// def appName = getAppName("windows-x64-dev") + ".exe"
// copy {
// from "${project.projectDir.absolutePath}/deploy/win64dev/Output/${appName}"
// into "${project.projectDir.absolutePath}/deploy/artifacts"
// }
//
// def archName = getAppName("windows-x64-dev-installer") + ".jar"
// def outPath = "${project.projectDir.absolutePath}/deploy/win64dev/Output/"
//
// def result = simpleJar {
// baseName = archName
// archivesBaseName = archName
// archiveName = archName
// destinationDir = new File(outPath)
// from "${project.projectDir.absolutePath}${File.separator}src${File.separator}main${File.separator}resources${File.separator}version${File.separator}"
// from {
// "${project.projectDir.absolutePath}/deploy/win64dev/Output/${appName}"
// }{
// into "installer/"
// }
// }
// result.execute()
// signJar(new File(outPath + archName))
// copy {
// from outPath + archName
// into "${project.projectDir.absolutePath}/deploy/artifacts"
// }
// delete {
// delete(outPath + archName)
// delete(outPath + appName)
// }
//
// }
// }
//}
String getAppName(String operatingSystem) {
def fName = fullName.toLowerCase();
fName = fName.replace(" ", "_")
fName = fName.replace("-", "")
fName = fName + "-" + applicationVersion.replace(".", "_")
fName = fName + "-" + operatingSystem
return fName
}
defineProperty("embrace_key", "unknown")
void signJar(File jarPath) {
File jarFile = jarPath
String dir = jarFile.getParent()
String keystoreKey = System.getenv('EMBRACE_KEY');
if (keystoreKey == null) {
keystoreKey = project.ext.embrace_key;
}
def javafxpackager = exec {
workingDir "${project.projectDir.absolutePath}"
commandLine "${jdk}/bin/jarsigner",
"-keypass", keystoreKey,
"-keystore", "${rootProject.projectDir.absolutePath}/InstallerFiles/embrace-ca-signed-private-key.p12",
"-storepass", keystoreKey, jarPath, "selfsigned"
logger.quiet(commandLine.toString())
}
}
void setIssVersionAndName(def issFilePath, def fileName) {
def lines = new File(issFilePath).readLines()
BufferedWriter w = (new File(issFilePath)).newWriter()
for (String line : lines) {
if (line.contains("#define MyAppVersion \"")) {
w.write("#define MyAppVersion \"" + applicationVersion + "\" ;this line is populated automatically, don't remove it")
} else if (line.contains("OutputBaseFilename=")) {
w.write("OutputBaseFilename=${fileName}")
} else {
w.write(line)
}
w.newLine()
}
w.close()
}
public List<String> getCommandLineArgs() {
def cmdLineArgs = Project.hasProperty('cmdLineArgs') ? Project.cmdLineArgs : ''
cmdLineArgs = cmdLineArgs?.toString()?.trim()
if (cmdLineArgs == null || cmdLineArgs == '') {
return []
} else {
return splitArgs(cmdLineArgs)
}
}
void updateDebugTaskArgs() {
List debuggerAttachArgs = null;
if (Project.hasProperty('debuggerJpdaPort')) {
def debuggerPort = project.debuggerJpdaPort
debuggerAttachArgs = ['-Xdebug', "-Xrunjdwp:transport=dt_socket,server=n,address=${debuggerPort}".toString()]
}
if (debuggerAttachArgs == null || !Project.hasProperty('debuggedTaskName')) {
return
}
String debuggedTaskName = Project.debuggedTaskName.toString()
String localTaskName = debuggedTaskName
int projectPathSepIndex = debuggedTaskName.lastIndexOf(':')
if (projectPathSepIndex >= 0) {
String projectPath = normalizePath(debuggedTaskName.substring(0, projectPathSepIndex).trim())
if (projectPath != project.path) {
return
}
localTaskName = debuggedTaskName.substring(projectPathSepIndex + 1).trim()
}
def task = Project.tasks.findByName(localTaskName)
if (task instanceof JavaExec) {
def cmdLineArgs = getCmdLineArgs(project)
if (!cmdLineArgs.isEmpty()) {
task.args = cmdLineArgs
}
}
if ((task instanceof JavaExec) || (task instanceof Test)) {
updateJvmArgs(task, debuggerAttachArgs)
}
}
String normalizePath(String rawPath) {
boolean changed = false
StringBuilder result = new StringBuilder(rawPath.length())
if (!rawPath.startsWith(':')) {
result.append(':')
changed = true
}
boolean prevColon = false
for (int i = 0; i < rawPath.length(); i++) {
char ch = rawPath.getAt(i)
boolean colon = ch == ':'
if (!colon || !prevColon) {
result.append(ch)
} else {
changed = true
}
prevColon = colon
}
return changed ? result.toString() : rawPath
}
List<String> getEmbraceJVMOptions(boolean dev) {
List<String> props = embraceJvmOptionsProduction
if (dev) {
props = embraceJvmOptionsDev
}
List<String> ret = new ArrayList<>();
for (String prop : props) {
ret.add("-" + prop)
}
return ret
}
List<String> getEmbraceJVMProperties(boolean dev) {
List<String> props = embraceJvmPropertiesProduction
if (dev) {
props = embraceJvmPropertiesDev
}
List<String> ret = new ArrayList<>();
for (String prop : props) {
ret.add("-D" + prop)
}
return ret
}
List<String> getEmbraceJVMOptionsDebug() {
List<String> props = embraceJvmOptionsDebug
List<String> ret = new ArrayList<>();
for (String prop : props) {
ret.add("-" + prop)
}
return ret
}
List<String> getEmbraceJVMPropertiesDebug() {
List<String> props = embraceJvmPropertiesDebug
List<String> ret = new ArrayList<>();
for (String prop : props) {
ret.add("-D" + prop)
}
return ret
}
String getPackagerProperties() {
String ret = "";
List<String> props = project.ext.embraceJvmPropertiesProduction
for (String prop : props) {
ret += "-D" + prop + " ";
}
return ret;
}
String getPackagerOptions() {
List<String> props = project.ext.embraceJvmOptionsProduction
String ret = "";
for (String prop : props) {
ret += "-" + prop + " ";
}
return ret;
}
String getVersionFile(def platform, def jdk, def type, def programNameExtension) {
String jdkVersion = getJDKVersion(jdk)
String programNameExtension2 = programNameExtension
if (!programNameExtension.equals("")) {
programNameExtension2 = " " + programNameExtension
}
return "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n" +
"<root>\n" +
" <version>${applicationVersion}</version>\n" +
" <runtimeversion>${jdkVersion}</runtimeversion>\n" +
" <appname>${fullName + programNameExtension2}</appname>\n" +
" <shortname>${applicationName + programNameExtension}</shortname>\n" +
" <operatingsystem>${platform}</operatingsystem>\n" +
" <releasenotes>${groovy.xml.XmlUtil.escapeXml(applicationReleaseNotes)}</releasenotes>\n" +
" <type>${type}</type>\n" +
"</root>\n"
}
void updateVersionFile(def operatingSystem, def jdk, def type) {
updateVersionFile(operatingSystem, jdk, type, "")
}
File getVersionFilePath(def operatingSystem, def jdk, def type, def programNameExtension) {
updateVersionFile(operatingSystem, jdk, type, programNameExtension)
return getVersionFilePath()
}
File getVersionFilePath() {
File versionFile = new File("${project.projectDir.absolutePath}${File.separator}src${File.separator}main${File.separator}resources${File.separator}version${File.separator}version.xml")
return versionFile
}
void updateVersionFile(def operatingSystem, def jdk, def type, def programNameExtension) {
String versionF = getVersionFile(operatingSystem, jdk, type, programNameExtension)
File versionFile = new File("${project.projectDir.absolutePath}${File.separator}src${File.separator}main${File.separator}resources${File.separator}version${File.separator}version.xml")
versionFile.getParentFile().mkdirs()
versionFile.write(versionF)
}
void deleteVersionFiles() {
println "test delete version files"
rootProject.subprojects.each {
File f = new File(it.projectDir)
println f.toString()
}
}
String getJDKVersion(def pathToJDK) {
ByteArrayOutputStream output = new ByteArrayOutputStream()
def ver = exec {
workingDir "${project.projectDir.absolutePath}"
commandLine "${pathToJDK}/bin/java",
"-version"
errorOutput = output
}
String out = output.toString().split("[\\s\"]+")[2]
out = out.replace("0_", "")
return out
}
void updateJvmArgs(def task, List additionalArgs) {
logger.quiet("updating jvm args")
// Note: The list might contain non-string instances, so first convert them.
Set additionalArgsSet = new LinkedHashSet(additionalArgs*.toString())
List currentArgs = task.jvmArgs;
for (def arg : task.jvmArgs) {
additionalArgsSet.remove(arg?.toString())
}
task.jvmArgs(additionalArgsSet)
logger.quiet("Final args " + task.jvmArgs.toString())
}
List<String> splitArgs(String cmdLine) {
char quoteChar = '"'
List<String> result = new ArrayList<>();
int index = indexOfNonWs(cmdLine, 0);
while (index < cmdLine.length()) {
if (cmdLine.charAt(index) == quoteChar) {
int argStartIndex = index + 1;
index = unescapedIndexOf(cmdLine, argStartIndex, quoteChar);
int argEndIndex;
if (index < 0) {
index = cmdLine.length();
argEndIndex = index;
} else {
argEndIndex = index;
index++;
}
result.add(unescapeString(cmdLine.substring(argStartIndex, argEndIndex)));
} else {
int argStartIndex = index;
index = indexOfWs(cmdLine, index);
result.add(cmdLine.substring(argStartIndex, index));
}
index = indexOfNonWs(cmdLine, index);
}
return result;
}
int indexOfNonWs(String str, int startIndex) {
return indexOfWs(str, startIndex, false);
}
int indexOfWs(String str, int startIndex) {
return indexOfWs(str, startIndex, true);
}
int indexOfWs(String str, int startIndex, boolean findWs) {
char spaceChar = ' '
for (int i = startIndex; i < str.length(); i++) {
if ((str.charAt(i) <= spaceChar) == findWs) {
return i;
}
}
return str.length();
}
int unescapedIndexOf(String str, int startIndex, char toFind) {
char escapeChar = '\\'
int i = startIndex;
while (i < str.length()) {
char ch = str.charAt(i);
if (ch == toFind) {
return i;
}
if (ch == escapeChar) i += 2;
else i++;
}
return -1;
}
String unescapeString(String str) {
char escapeChar = '\\'
StringBuilder result = new StringBuilder(str.length());
int i = 0;
while (i < str.length()) {
char ch = str.charAt(i);
if (ch == escapeChar) {
if (i + 1 < str.length()) {
result.append(str.charAt(i + 1));
i += 2;
continue;
}
}
result.append(ch);
i++;
}
return result.toString();
}
abstract class DuplicateFileManager {
abstract public void resolveDuplicates(File destination, File mainFile, List<File> duplicates);
/**
* Reads the contents of the given file into the stringbuilder.
*/
public void readFile(StringBuilder sb, File f) {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
def chars = new char[1024];
int r = 0;
while ((r = reader.read(chars, 0, chars.length)) != -1) {
sb.append(chars, 0, r);
}
reader.close();
}
}
class ConcatenateDuplicates extends DuplicateFileManager {
public void resolveDuplicates(File destination, File mainFile, List<File> duplicates) {
StringBuilder sb = new StringBuilder();
if (mainFile != null) {
readFile(sb, mainFile);
}
for (File f : duplicates) {
readFile(sb, f);
}
destination.getParentFile().mkdirs();
destination.write(sb.toString());
}
}
class PickMain extends DuplicateFileManager {
public void resolveDuplicates(File destination, File mainFile, List<File> duplicates) {
if (mainFile != null) {
destination.getParentFile().mkdirs();
java.nio.file.Files.copy(mainFile.toPath(), destination.toPath(), java.nio.file.StandardCopyOption.REPLACE_EXISTING);
}
}
}
class Log4j2Concatenator extends DuplicateFileManager {
/**
* Log4j2Plugins.dat merge based off https://gist.github.com/riccardobl/bdbbae9f2e8fefcd28dc5482ddc6b374
*/
public void resolveDuplicates(File destination, File mainFile, List<File> duplicates) {
def globalCount = 0;
def writer = new ByteArrayOutputStream();
if (mainFile != null) {
duplicates.add(mainFile);
}
for (File f : duplicates) {
if (f != null && f.exists()) {
def individualPluginWriter = new DataOutputStream(writer);
def reader = new DataInputStream(new BufferedInputStream(new FileInputStream(f)));
def count = reader.readInt();
globalCount += count;
println("Merge $count entries");
for (def k = 0; k < count; k++) {
individualPluginWriter.writeUTF(reader.readUTF());
def entries = reader.readInt();
individualPluginWriter.writeInt(entries);
for (def j = 0; j < entries; j++) {
individualPluginWriter.writeUTF(reader.readUTF());
individualPluginWriter.writeUTF(reader.readUTF());
individualPluginWriter.writeUTF(reader.readUTF());
individualPluginWriter.writeBoolean(reader.readBoolean());
individualPluginWriter.writeBoolean(reader.readBoolean());
}
}
reader.close()
individualPluginWriter.flush();
}
}
def bytes = writer.toByteArray();
writer.close();
destination.getParentFile().mkdirs();
writer = new DataOutputStream(new FileOutputStream(destination));
writer.writeInt(globalCount);
writer.write(bytes);
writer.close();
}
}
/**
* Takes a list of dependencies (jars and folders), finds duplicate files in those folders, merges them appropriately, writes them all into one jar and returns that jar.
*
*/
List<File> getMergedDuplicates(def input) {
File root = new File("$buildDir/merged")
root.deleteDir()
root.mkdirs()
HashMap<String, ArrayList<File>> modifiedFiles = new HashMap<>();
input.files.each {
File folder ->
def tree
if (folder.isDirectory()) { //either normal directory, or jar
tree = fileTree(folder);
tree.each {
File innerFile ->
//String fileName = innerFile.relativePath.toString();
String fileName = (folder.toURI()).relativize(innerFile.toURI()).toString()
if (!modifiedFiles.containsKey(fileName)) {
modifiedFiles.put(fileName, new ArrayList<File>());
}
modifiedFiles.get(fileName).add(innerFile);
}
} else {
tree = zipTree(folder);
String folderName = folder.name
try {
tree.each {
File innerFile ->
//String fileName = innerFile.relativePath.toString();
File parent = innerFile
while (!parent.name.contains(folderName)) {
parent = parent.getParentFile();
}
String fileName = (parent.toURI()).relativize(innerFile.toURI()).toString()
if (!modifiedFiles.containsKey(fileName)) {
modifiedFiles.put(fileName, new ArrayList<File>());
}
modifiedFiles.get(fileName).add(innerFile);
}
}
catch (Exception e) {
}
}
}
ArrayList<File> merged = new ArrayList<File>();
for (Map.Entry<String, Object> entry : modifiedFiles.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
if (value.size() > 1) {
resolveDuplicates(key, new File("$buildDir/merged/" + key), value.get(0), value);
println("Duplicated " + value.get(0).name);
}
}
return merged;
}
ext.mergers = new HashMap<String, DuplicateFileManager>();
ext.mergers.put('META-INF/LICENSE.txt', new ConcatenateDuplicates());
ext.mergers.put('version/version.xml', new PickMain());
ext.mergers.put('version/embracetrust.tst', new PickMain());
ext.mergers.put('META-INF/DEPENDENCIES', new PickMain());
ext.mergers.put('META-INF/DEPENDENCIES.txt', new PickMain());
ext.mergers.put('META-INF/NOTICE.txt', new PickMain());
ext.mergers.put('META-INF/NOTICE', new PickMain());
ext.mergers.put('META-INF/LICENSE', new ConcatenateDuplicates());
ext.mergers.put('license/LICENSE.txt', new ConcatenateDuplicates());
ext.mergers.put('META-INF/org/apache/logging/log4j/core/config/plugins/Log4j2Plugins.dat', new Log4j2Concatenator());
ext.pickMain = new PickMain();
void resolveDuplicates(String relativeFileName, File mergeResult, File mainFile, List<File> allFiles) {
if (ext.mergers.containsKey(relativeFileName)) {
ext.mergers.get(relativeFileName).resolveDuplicates(mergeResult, mainFile, allFiles);
} else {
ext.pickMain.resolveDuplicates(mergeResult, mainFile, allFiles);
}
}
void defineProperty(String name, String defaultValue) {
if (!project.hasProperty(name)) {
project.ext.set(name, defaultValue);
}
}
// Export methods by turning them into closures
// https://stackoverflow.com/a/23290820/4489577 hero
ext {
getCommandLineArgs = this.&getCommandLineArgs
updateDebugTaskArgs = this.&updateDebugTaskArgs
getVersionFilePath = this.&getVersionFilePath
copyArtifacts = this.©Artifacts
platformImage = this.&platformImage
getAppName = this.&getAppName
getMergedDuplicates = this.&getMergedDuplicates
signJar = this.&signJar
}