Merge branch 'improvement/JAL-3394_added_categories_to_unix_shell_installer_desktop_f...
[jalview.git] / build.gradle
1 import org.apache.tools.ant.filters.ReplaceTokens
2 import org.gradle.internal.os.OperatingSystem
3 import org.gradle.plugins.ide.eclipse.model.Output
4 import org.gradle.plugins.ide.eclipse.model.Library
5 import java.security.MessageDigest
6 import groovy.transform.ExternalizeMethods
7 import groovy.util.XmlParser
8 import groovy.xml.XmlUtil
9
10
11 buildscript {
12   repositories {
13     mavenCentral()
14     mavenLocal()
15   }
16   dependencies {
17     classpath 'org.openclover:clover:4.4.1'
18   }
19 }
20
21
22 plugins {
23   id 'java'
24   id 'application'
25   id 'eclipse'
26   id 'com.github.johnrengelman.shadow' version '4.0.3'
27   id 'com.install4j.gradle' version '8.0.4'
28   id 'com.dorongold.task-tree' version '1.5' // only needed to display task dependency tree with  gradle task1 [task2 ...] taskTree
29 }
30
31 repositories {
32   jcenter()
33   mavenCentral()
34   mavenLocal()
35 }
36
37
38 // in ext the values are cast to Object. Ensure string values are cast as String (and not GStringImpl) for later use
39 def string(Object o) {
40   return o == null ? "" : o.toString()
41 }
42
43
44 ext {
45   jalviewDirAbsolutePath = file(jalviewDir).getAbsolutePath()
46   jalviewDirRelativePath = jalviewDir
47
48   // local build environment properties
49   // can be "projectDir/local.properties"
50   def localProps = "${projectDir}/local.properties"
51   def propsFile = null;
52   if (file(localProps).exists()) {
53     propsFile = localProps
54   }
55   // or "../projectDir_local.properties"
56   def dirLocalProps = projectDir.getParent() + "/" + projectDir.getName() + "_local.properties"
57   if (file(dirLocalProps).exists()) {
58     propsFile = dirLocalProps
59   }
60   if (propsFile != null) {
61     try {
62       def p = new Properties()
63       def localPropsFIS = new FileInputStream(propsFile)
64       p.load(localPropsFIS)
65       localPropsFIS.close()
66       p.each {
67         key, val -> 
68           def oldval = findProperty(key)
69           setProperty(key, val)
70           if (oldval != null) {
71             println("Overriding property '${key}' ('${oldval}') with ${file(propsFile).getName()} value '${val}'")
72           } else {
73             println("Setting unknown property '${key}' with ${file(propsFile).getName()}s value '${val}'")
74           }
75       }
76     } catch (Exception e) {
77       System.out.println("Exception reading local.properties")
78     }
79   }
80
81   // this property set when running Eclipse headlessly
82   j2sHeadlessBuildProperty = string("net.sf.j2s.core.headlessbuild")
83   // this property set by Eclipse
84   eclipseApplicationProperty = string("eclipse.application")
85   // CHECK IF RUNNING FROM WITHIN ECLIPSE
86   def eclipseApplicationPropertyVal = System.properties[eclipseApplicationProperty]
87   IN_ECLIPSE = eclipseApplicationPropertyVal != null && eclipseApplicationPropertyVal.startsWith("org.eclipse.ui.")
88   // BUT WITHOUT THE HEADLESS BUILD PROPERTY SET
89   if (System.properties[j2sHeadlessBuildProperty].equals("true")) {
90     println("Setting IN_ECLIPSE to ${IN_ECLIPSE} as System.properties['${j2sHeadlessBuildProperty}'] == '${System.properties[j2sHeadlessBuildProperty]}'")
91     IN_ECLIPSE = false
92   }
93   if (IN_ECLIPSE) {
94     println("WITHIN ECLIPSE IDE")
95   } else {
96     println("HEADLESS BUILD")
97   }
98   /* *-/
99   System.properties.sort { it.key }.each {
100     key, val -> println("SYSTEM PROPERTY ${key}='${val}'")
101   }
102   /-* *-/
103   if (false && IN_ECLIPSE) {
104     jalviewDir = jalviewDirAbsolutePath
105   }
106   */
107
108   // essentials
109   bareSourceDir = string(source_dir)
110   sourceDir = string("${jalviewDir}/${bareSourceDir}")
111   resourceDir = string("${jalviewDir}/${resource_dir}")
112   bareTestSourceDir = string(test_source_dir)
113   testSourceDir = string("${jalviewDir}/${bareTestSourceDir}")
114
115   // clover
116   cloverInstrDir = file("${buildDir}/${cloverSourcesInstrDir}")
117   cloverDb = string("${buildDir}/clover/clover.db")
118   classesDir = string("${jalviewDir}/${classes_dir}")
119   if (clover.equals("true")) {
120     use_clover = true
121     classesDir = string("${buildDir}/${cloverClassesDir}")
122   } else {
123     use_clover = false
124     classesDir = string("${jalviewDir}/${classes_dir}")
125   }
126
127   classes = classesDir
128
129   getdownWebsiteDir = string("${jalviewDir}/${getdown_website_dir}/${JAVA_VERSION}")
130   buildDist = true
131
132   // the following values might be overridden by the CHANNEL switch
133   getdownChannelName = CHANNEL.toLowerCase()
134   getdownDir = string("${getdownChannelName}/${JAVA_VERSION}")
135   getdownAppBase = string("${getdown_channel_base}/${getdownDir}")
136   getdownLauncher = string("${jalviewDir}/${getdown_lib_dir}/${getdown_launcher}")
137   getdownAppDistDir = getdown_app_dir_alt
138   buildProperties = string("${classesDir}/${build_properties_file}")
139   reportRsyncCmd = false
140   jvlChannelName = CHANNEL.toLowerCase()
141   switch (CHANNEL) {
142
143     case "BUILD":
144     // TODO: get bamboo build artifact URL for getdown artifacts
145     getdown_channel_base = bamboo_channelbase
146     getdownChannelName = string("${bamboo_planKey}/${JAVA_VERSION}")
147     getdownAppBase = string("${bamboo_channelbase}/${bamboo_planKey}${bamboo_getdown_channel_suffix}/${JAVA_VERSION}")
148     jvlChannelName += "_${getdownChannelName}"
149     // automatically add the test group Not-bamboo for exclusion 
150     if ("".equals(testngExcludedGroups)) { 
151       testngExcludedGroups = "Not-bamboo"
152     }
153     break
154
155     case "RELEASE":
156     getdownAppDistDir = getdown_app_dir_release
157     reportRsyncCommand = true
158     break
159
160     case "ARCHIVE":
161     getdownChannelName = CHANNEL.toLowerCase()+"/${JALVIEW_VERSION}"
162     getdownDir = string("${getdownChannelName}/${JAVA_VERSION}")
163     getdownAppBase = string("${getdown_channel_base}/${getdownDir}")
164     if (!file("${ARCHIVEDIR}/${packageDir}").exists()) {
165       throw new GradleException("Must provide an ARCHIVEDIR value to produce an archive distribution")
166     } else {
167       packageDir = string("${ARCHIVEDIR}/${packageDir}")
168       buildProperties = string("${ARCHIVEDIR}/${classes_dir}/${build_properties_file}")
169       buildDist = false
170     }
171     reportRsyncCommand = true
172     break
173
174     case "ARCHIVELOCAL":
175     getdownChannelName = string("archive/${JALVIEW_VERSION}")
176     getdownDir = string("${getdownChannelName}/${JAVA_VERSION}")
177     getdownAppBase = file(getdownWebsiteDir).toURI().toString()
178     if (!file("${ARCHIVEDIR}/${packageDir}").exists()) {
179       throw new GradleException("Must provide an ARCHIVEDIR value to produce an archive distribution")
180     } else {
181       packageDir = string("${ARCHIVEDIR}/${packageDir}")
182       buildProperties = string("${ARCHIVEDIR}/${classes_dir}/${build_properties_file}")
183       buildDist = false
184     }
185     reportRsyncCommand = true
186     getdownLauncher = string("${jalviewDir}/${getdown_lib_dir}/${getdown_launcher_local}")
187     break
188
189     case "DEVELOP":
190     reportRsyncCommand = true
191     break
192
193     case "TEST-RELEASE":
194     reportRsyncCommand = true
195     break
196
197     case ~/^SCRATCH(|-[-\w]*)$/:
198     getdownChannelName = CHANNEL
199     getdownDir = string("${getdownChannelName}/${JAVA_VERSION}")
200     getdownAppBase = string("${getdown_channel_base}/${getdownDir}")
201     reportRsyncCommand = true
202     break
203
204     case "TEST-LOCAL":
205     if (!file("${LOCALDIR}").exists()) {
206       throw new GradleException("Must provide a LOCALDIR value to produce a local distribution")
207     } else {
208       getdownAppBase = file(file("${LOCALDIR}").getAbsolutePath()).toURI().toString()
209       getdownLauncher = string("${jalviewDir}/${getdown_lib_dir}/${getdown_launcher_local}")
210     }
211     break
212
213     case "LOCAL":
214     getdownAppBase = file(getdownWebsiteDir).toURI().toString()
215     getdownLauncher = string("${jalviewDir}/${getdown_lib_dir}/${getdown_launcher_local}")
216     break
217
218     default: // something wrong specified
219     throw new GradleException("CHANNEL must be one of BUILD, RELEASE, ARCHIVE, DEVELOP, TEST-RELEASE, SCRATCH-..., LOCAL [default]")
220     break
221
222   }
223   // override getdownAppBase if requested
224   if (findProperty("getdown_appbase_override") != null) {
225     getdownAppBase = string(getProperty("getdown_appbase_override"))
226     println("Overriding getdown appbase with '${getdownAppBase}'")
227   }
228   // sanitise file name for jalview launcher file for this channel
229   jvlChannelName = jvlChannelName.replaceAll(/[^\w\-]/,"_")
230
231   getdownAppDir = string("${getdownWebsiteDir}/${getdownAppDistDir}")
232   //getdownJ11libDir = "${getdownWebsiteDir}/${getdown_j11lib_dir}"
233   getdownResourceDir = string("${getdownWebsiteDir}/${getdown_resource_dir}")
234   getdownInstallDir = string("${getdownWebsiteDir}/${getdown_install_dir}")
235   getdownFilesDir = string("${jalviewDir}/${getdown_files_dir}/${JAVA_VERSION}/")
236   getdownFilesInstallDir = string("${getdownFilesDir}/${getdown_install_dir}")
237   /* compile without modules -- using classpath libraries
238   modules_compileClasspath = fileTree(dir: "${jalviewDir}/${j11modDir}", include: ["*.jar"])
239   modules_runtimeClasspath = modules_compileClasspath
240   */
241   gitHash = string("")
242   gitBranch = string("")
243
244   println("Using a ${CHANNEL} profile.")
245
246   additional_compiler_args = []
247   // configure classpath/args for j8/j11 compilation
248   if (JAVA_VERSION.equals("1.8")) {
249     JAVA_INTEGER_VERSION = string("8")
250     //libDir = j8libDir
251     libDir = j11libDir
252     libDistDir = j8libDir
253     compile_source_compatibility = 1.8
254     compile_target_compatibility = 1.8
255     // these are getdown.txt properties defined dependent on the JAVA_VERSION
256     getdownAltJavaMinVersion = string(findProperty("getdown_alt_java8_min_version"))
257     getdownAltJavaMaxVersion = string(findProperty("getdown_alt_java8_max_version"))
258     // this property is assigned below and expanded to multiple lines in the getdown task
259     getdownAltMultiJavaLocation = string(findProperty("getdown_alt_java8_txt_multi_java_location"))
260     // this property is for the Java library used in eclipse
261     eclipseJavaRuntimeName = string("JavaSE-1.8")
262   } else if (JAVA_VERSION.equals("11")) {
263     JAVA_INTEGER_VERSION = string("11")
264     libDir = j11libDir
265     libDistDir = j11libDir
266     compile_source_compatibility = 11
267     compile_target_compatibility = 11
268     getdownAltJavaMinVersion = string(findProperty("getdown_alt_java11_min_version"))
269     getdownAltJavaMaxVersion = string(findProperty("getdown_alt_java11_max_version"))
270     getdownAltMultiJavaLocation = string(findProperty("getdown_alt_java11_txt_multi_java_location"))
271     eclipseJavaRuntimeName = string("JavaSE-11")
272     /* compile without modules -- using classpath libraries
273     additional_compiler_args += [
274     '--module-path', modules_compileClasspath.asPath,
275     '--add-modules', j11modules
276     ]
277      */
278   } else if (JAVA_VERSION.equals("12") || JAVA_VERSION.equals("13")) {
279     JAVA_INTEGER_VERSION = JAVA_VERSION
280     libDir = j11libDir
281     libDistDir = j11libDir
282     compile_source_compatibility = JAVA_VERSION
283     compile_target_compatibility = JAVA_VERSION
284     getdownAltJavaMinVersion = string(findProperty("getdown_alt_java11_min_version"))
285     getdownAltJavaMaxVersion = string(findProperty("getdown_alt_java11_max_version"))
286     getdownAltMultiJavaLocation = string(findProperty("getdown_alt_java11_txt_multi_java_location"))
287     eclipseJavaRuntimeName = string("JavaSE-11")
288     /* compile without modules -- using classpath libraries
289     additional_compiler_args += [
290     '--module-path', modules_compileClasspath.asPath,
291     '--add-modules', j11modules
292     ]
293      */
294   } else {
295     throw new GradleException("JAVA_VERSION=${JAVA_VERSION} not currently supported by Jalview")
296   }
297
298
299   // for install4j
300   JAVA_MIN_VERSION = JAVA_VERSION
301   JAVA_MAX_VERSION = JAVA_VERSION
302   def jreInstallsDir = string(jre_installs_dir)
303   if (jreInstallsDir.startsWith("~/")) {
304     jreInstallsDir = System.getProperty("user.home") + jreInstallsDir.substring(1)
305   }
306   macosJavaVMDir = string("${jreInstallsDir}/jre-${JAVA_INTEGER_VERSION}-mac-x64/jre")
307   macosJavaVMTgz = string("${jreInstallsDir}/tgz/jre-${JAVA_INTEGER_VERSION}-mac-x64.tar.gz")
308   windowsJavaVMDir = string("${jreInstallsDir}/jre-${JAVA_INTEGER_VERSION}-windows-x64/jre")
309   windowsJavaVMTgz = string("${jreInstallsDir}/tgz/jre-${JAVA_INTEGER_VERSION}-windows-x64.tar.gz")
310   linuxJavaVMDir = string("${jreInstallsDir}/jre-${JAVA_INTEGER_VERSION}-linux-x64/jre")
311   linuxJavaVMTgz = string("${jreInstallsDir}/tgz/jre-${JAVA_INTEGER_VERSION}-linux-x64.tar.gz")
312   install4jDir = string("${jalviewDir}/${install4j_utils_dir}")
313   install4jConfFileName = string("jalview-install4j-conf.install4j")
314   install4jConfFile = file("${install4jDir}/${install4jConfFileName}")
315   install4jHomeDir = install4j_home_dir
316   if (install4jHomeDir.startsWith("~/")) {
317     install4jHomeDir = System.getProperty("user.home") + install4jHomeDir.substring(1)
318   }
319
320
321
322   buildingHTML = string("${jalviewDir}/${docDir}/building.html")
323   helpFile = string("${classesDir}/${help_dir}/help.jhm")
324   helpParentDir = string("${jalviewDir}/${help_parent_dir}")
325   helpSourceDir = string("${helpParentDir}/${help_dir}")
326
327
328   relativeBuildDir = file(jalviewDirAbsolutePath).toPath().relativize(buildDir.toPath())
329   jalviewjsBuildDir = string("${relativeBuildDir}/jalviewjs")
330   jalviewjsSiteDir = string("${jalviewjsBuildDir}/${jalviewjs_site_dir}")
331   if (IN_ECLIPSE) {
332     jalviewjsTransferSiteJsDir = string(jalviewjsSiteDir)
333   } else {
334     jalviewjsTransferSiteJsDir = string("${jalviewjsBuildDir}/tmp/${jalviewjs_site_dir}_js")
335   }
336   jalviewjsTransferSiteLibDir = string("${jalviewjsBuildDir}/tmp/${jalviewjs_site_dir}_lib")
337   jalviewjsTransferSiteSwingJsDir = string("${jalviewjsBuildDir}/tmp/${jalviewjs_site_dir}_swingjs")
338   jalviewjsTransferSiteCoreDir = string("${jalviewjsBuildDir}/tmp/${jalviewjs_site_dir}_core")
339   jalviewjsJalviewCoreHtmlFile = string("")
340   jalviewjsJalviewCoreName = string(jalviewjs_core_name)
341   jalviewjsCoreClasslists = []
342   jalviewjsJalviewTemplateName = string(jalviewjs_name)
343   jalviewjsJ2sSettingsFileName = string("${jalviewDir}/${jalviewjs_j2s_settings}")
344   jalviewjsJ2sProps = null
345
346   eclipseWorkspace = null
347   eclipseBinary = string("")
348   eclipseVersion = string("")
349   eclipseDebug = false
350   // ENDEXT
351 }
352
353
354 sourceSets {
355   main {
356     java {
357       srcDirs sourceDir
358       outputDir = file(classesDir)
359     }
360
361     resources {
362       srcDirs resourceDir
363       srcDirs += helpParentDir
364     }
365
366     jar.destinationDir = file("${jalviewDir}/${packageDir}")
367
368     compileClasspath = files(sourceSets.main.java.outputDir)
369     //compileClasspath += files(sourceSets.main.resources.srcDirs)
370     compileClasspath += fileTree(dir: "${jalviewDir}/${libDir}", include: ["*.jar"])
371
372     runtimeClasspath = compileClasspath
373   }
374
375   clover {
376     java {
377       srcDirs = [ cloverInstrDir ]
378       outputDir = file("${buildDir}/${cloverClassesDir}")
379     }
380
381     resources {
382       srcDirs = sourceSets.main.resources.srcDirs
383     }
384     compileClasspath = configurations.cloverRuntime + files( sourceSets.clover.java.outputDir )
385     compileClasspath += files(sourceSets.main.java.outputDir)
386     compileClasspath += sourceSets.main.compileClasspath
387     compileClasspath += fileTree(dir: "${jalviewDir}/${utilsDir}", include: ["**/*.jar"])
388     compileClasspath += fileTree(dir: "${jalviewDir}/${libDir}", include: ["*.jar"])
389
390     runtimeClasspath = compileClasspath
391   }
392
393   test {
394     java {
395       srcDirs testSourceDir
396       outputDir = file("${jalviewDir}/${testOutputDir}")
397     }
398
399     resources {
400       srcDirs = sourceSets.main.resources.srcDirs
401     }
402
403     compileClasspath = files( sourceSets.test.java.outputDir )
404
405     if (use_clover) {
406       compileClasspath = sourceSets.clover.compileClasspath
407     } else {
408       compileClasspath += files(sourceSets.main.java.outputDir)
409     }
410
411     compileClasspath += fileTree(dir: "${jalviewDir}/${libDir}", include: ["*.jar"])
412     compileClasspath += fileTree(dir: "${jalviewDir}/${utilsDir}/testnglibs", include: ["**/*.jar"])
413     compileClasspath += fileTree(dir: "${jalviewDir}/${utilsDir}/testlibs", include: ["**/*.jar"])
414
415     runtimeClasspath = compileClasspath
416   }
417 }
418
419
420 // clover bits
421 dependencies {
422   if (use_clover) {
423     cloverCompile 'org.openclover:clover:4.4.1'
424     testCompile 'org.openclover:clover:4.4.1'
425   }
426 }
427
428 configurations {
429   cloverRuntime
430   cloverRuntime.extendsFrom cloverCompile
431 }
432
433
434 // eclipse project and settings files creation, also used by buildship
435 eclipse {
436   project {
437     name = eclipse_project_name
438
439     natures 'org.eclipse.jdt.core.javanature',
440     'org.eclipse.jdt.groovy.core.groovyNature',
441     'org.eclipse.buildship.core.gradleprojectnature'
442
443     buildCommand 'org.eclipse.jdt.core.javabuilder'
444     buildCommand 'org.eclipse.buildship.core.gradleprojectbuilder'
445   }
446
447   classpath {
448     //defaultOutputDir = sourceSets.main.java.outputDir
449     def removeThese = []
450     configurations.each{
451       if (it.isCanBeResolved()) {
452         removeThese += it
453       }
454     }
455
456     minusConfigurations += removeThese
457     plusConfigurations = [ ]
458     file {
459
460       whenMerged { cp ->
461         def removeTheseToo = []
462         HashMap<String, Boolean> alreadyAddedSrcPath = new HashMap<>();
463         cp.entries.each { entry ->
464           // This conditional removes all src classpathentries that a) have already been added or b) aren't "src" or "test".
465           // e.g. this removes the resources dir being copied into bin/main, bin/test AND bin/clover
466           // we add the resources and help/help dirs in as libs afterwards (see below)
467           if (entry.kind == 'src') {
468             if (alreadyAddedSrcPath.getAt(entry.path) || !(entry.path == bareSourceDir || entry.path == bareTestSourceDir)) {
469               removeTheseToo += entry
470             } else {
471               alreadyAddedSrcPath.putAt(entry.path, true)
472             }
473           }
474
475         }
476         cp.entries.removeAll(removeTheseToo)
477
478         //cp.entries += new Output("${eclipse_bin_dir}/main")
479         if (file(helpParentDir).isDirectory()) {
480           cp.entries += new Library(fileReference(helpParentDir))
481         }
482         if (file(resourceDir).isDirectory()) {
483           cp.entries += new Library(fileReference(resourceDir))
484         }
485
486         HashMap<String, Boolean> alreadyAddedLibPath = new HashMap<>();
487
488         sourceSets.main.compileClasspath.findAll { it.name.endsWith(".jar") }.any {
489           //don't want to add outputDir as eclipse is using its own output dir in bin/main
490           if (it.isDirectory() || ! it.exists()) {
491             // don't add dirs to classpath, especially if they don't exist
492             return false // groovy "continue" in .any closure
493           }
494           def itPath = it.toString()
495           if (itPath.startsWith("${jalviewDirAbsolutePath}/")) {
496             // make relative path
497             itPath = itPath.substring(jalviewDirAbsolutePath.length()+1)
498           }
499           if (alreadyAddedLibPath.get(itPath)) {
500             //println("Not adding duplicate entry "+itPath)
501           } else {
502             //println("Adding entry "+itPath)
503             cp.entries += new Library(fileReference(itPath))
504             alreadyAddedLibPath.put(itPath, true)
505           }
506         }
507
508         sourceSets.test.compileClasspath.findAll { it.name.endsWith(".jar") }.any {
509           //no longer want to add outputDir as eclipse is using its own output dir in bin/main
510           if (it.isDirectory() || ! it.exists()) {
511             // don't add dirs to classpath
512             return false // groovy "continue" in .any closure
513           }
514
515           def itPath = it.toString()
516           if (itPath.startsWith("${jalviewDirAbsolutePath}/")) {
517             itPath = itPath.substring(jalviewDirAbsolutePath.length()+1)
518           }
519           if (alreadyAddedLibPath.get(itPath)) {
520             // don't duplicate
521           } else {
522             def lib = new Library(fileReference(itPath))
523             lib.entryAttributes["test"] = "true"
524             cp.entries += lib
525             alreadyAddedLibPath.put(itPath, true)
526           }
527         }
528
529       } // whenMerged
530
531     } // file
532
533     containers 'org.eclipse.buildship.core.gradleclasspathcontainer'
534
535   } // classpath
536
537   jdt {
538     // for the IDE, use java 11 compatibility
539     sourceCompatibility = compile_source_compatibility
540     targetCompatibility = compile_target_compatibility
541     javaRuntimeName = eclipseJavaRuntimeName
542
543     // add in jalview project specific properties/preferences into eclipse core preferences
544     file {
545       withProperties { props ->
546         def jalview_prefs = new Properties()
547         def ins = new FileInputStream("${jalviewDirAbsolutePath}/${eclipse_extra_jdt_prefs_file}")
548         jalview_prefs.load(ins)
549         ins.close()
550         jalview_prefs.forEach { t, v ->
551           if (props.getAt(t) == null) {
552             props.putAt(t, v)
553           }
554         }
555       }
556     }
557
558   } // jdt
559
560   if (IN_ECLIPSE) {
561     // Don't want these to be activated if in headless build
562     synchronizationTasks "eclipseSynchronizationTask"
563     autoBuildTasks "eclipseAutoBuildTask"
564
565   }
566 }
567
568
569 task cloverInstr {
570   // only instrument source, we build test classes as normal
571   inputs.files files (sourceSets.main.allJava,sourceSets.test.allJava) // , fileTree(dir:"$jalviewDir/$testSourceDir", include: ["**/*.java"]))
572   outputs.dir cloverInstrDir
573
574   doFirst {
575     delete cloverInstrDir
576     def argsList = [
577       "--initstring",
578       cloverDb,
579       "-d",
580       cloverInstrDir.getPath(),
581     ]
582     argsList.addAll(
583       inputs.files.files.collect(
584         { file -> file.absolutePath }
585       )
586     )
587     String[] args = argsList.toArray()
588     println("About to instrument "+args.length +" files")
589     com.atlassian.clover.CloverInstr.mainImpl(args)
590   }
591 }
592
593
594 cloverClasses.dependsOn cloverInstr
595
596
597 task cloverReport {
598   group = "Verification"
599   description = "Creates the Clover report"
600   inputs.dir "${buildDir}/clover"
601   outputs.dir "${reportsDir}/clover"
602   onlyIf {
603     file(cloverDb).exists()
604   }
605   doFirst {
606     def argsList = [
607       "--initstring",
608       cloverDb,
609       "-o",
610       "${reportsDir}/clover"
611     ]
612     String[] args = argsList.toArray()
613     com.atlassian.clover.reporters.html.HtmlReporter.runReport(args)
614
615     // and generate ${reportsDir}/clover/clover.xml
616     args = [
617       "--initstring",
618       cloverDb,
619       "-o",
620       "${reportsDir}/clover/clover.xml"
621     ].toArray()
622     com.atlassian.clover.reporters.xml.XMLReporter.runReport(args)
623   }
624 }
625
626
627 compileCloverJava {
628
629   doFirst {
630     sourceCompatibility = compile_source_compatibility
631     targetCompatibility = compile_target_compatibility
632     options.compilerArgs += additional_compiler_args
633     print ("Setting target compatibility to "+targetCompatibility+"\n")
634   }
635   classpath += configurations.cloverRuntime
636 }
637
638
639 task cleanClover {
640   doFirst {
641     delete cloverInstrDir
642     delete cloverDb
643   }
644 }
645 // end clover bits
646
647
648 compileJava {
649
650   doFirst {
651     sourceCompatibility = compile_source_compatibility
652     targetCompatibility = compile_target_compatibility
653     options.compilerArgs = additional_compiler_args
654     print ("Setting target compatibility to "+targetCompatibility+"\n")
655   }
656
657 }
658
659
660 compileTestJava {
661   if (use_clover) {
662     dependsOn compileCloverJava
663     classpath += configurations.cloverRuntime
664   } else {
665     classpath += sourceSets.main.runtimeClasspath
666   }
667   doFirst {
668     sourceCompatibility = compile_source_compatibility
669     targetCompatibility = compile_target_compatibility
670     options.compilerArgs = additional_compiler_args
671     print ("Setting target compatibility to "+targetCompatibility+"\n")
672   }
673 }
674
675
676 clean {
677   doFirst {
678     delete sourceSets.main.java.outputDir
679   }
680 }
681
682
683 cleanTest {
684   dependsOn cleanClover
685   doFirst {
686     delete sourceSets.test.java.outputDir
687   }
688 }
689
690
691 // format is a string like date.format("dd MMMM yyyy")
692 def getDate(format) {
693   def date = new Date()
694   return date.format(format)
695 }
696
697
698 task setGitVals {
699   def hashStdOut = new ByteArrayOutputStream()
700   exec {
701     commandLine "git", "rev-parse", "--short", "HEAD"
702     standardOutput = hashStdOut
703     ignoreExitValue true
704   }
705
706   def branchStdOut = new ByteArrayOutputStream()
707   exec {
708     commandLine "git", "rev-parse", "--abbrev-ref", "HEAD"
709     standardOutput = branchStdOut
710     ignoreExitValue true
711   }
712
713   gitHash = hashStdOut.toString().trim()
714   gitBranch = branchStdOut.toString().trim()
715
716   outputs.upToDateWhen { false }
717 }
718
719
720 task createBuildProperties(type: WriteProperties) {
721   dependsOn setGitVals
722   inputs.dir(sourceDir)
723   inputs.dir(resourceDir)
724   file(buildProperties).getParentFile().mkdirs()
725   outputFile (buildProperties)
726   // taking time specific comment out to allow better incremental builds
727   comment "--Jalview Build Details--\n"+getDate("yyyy-MM-dd HH:mm:ss")
728   //comment "--Jalview Build Details--\n"+getDate("yyyy-MM-dd")
729   property "BUILD_DATE", getDate("HH:mm:ss dd MMMM yyyy")
730   property "VERSION", JALVIEW_VERSION
731   property "INSTALLATION", INSTALLATION+" git-commit:"+gitHash+" ["+gitBranch+"]"
732   outputs.file(outputFile)
733 }
734
735
736 task cleanBuildingHTML(type: Delete) {
737   doFirst {
738     delete buildingHTML
739   }
740 }
741
742
743 task convertBuildingMD(type: Exec) {
744   dependsOn cleanBuildingHTML
745   def buildingMD = "${jalviewDir}/${docDir}/building.md"
746   def css = "${jalviewDir}/${docDir}/github.css"
747
748   def pandoc = null
749   pandoc_exec.split(",").each {
750     if (file(it.trim()).exists()) {
751       pandoc = it.trim()
752       return true
753     }
754   }
755
756   def hostname = "hostname".execute().text.trim()
757   def buildtoolsPandoc = System.getProperty("user.home")+"/buildtools/pandoc/bin/pandoc"
758   if ((pandoc == null || ! file(pandoc).exists()) && file(buildtoolsPandoc).exists()) {
759     pandoc = System.getProperty("user.home")+"/buildtools/pandoc/bin/pandoc"
760   }
761
762   doFirst {
763     if (pandoc != null && file(pandoc).exists()) {
764         commandLine pandoc, '-s', '-o', buildingHTML, '--metadata', 'pagetitle="Building Jalview from Source"', '--toc', '-H', css, buildingMD
765     } else {
766         println("Cannot find pandoc. Skipping convert building.md to HTML")
767         throw new StopExecutionException("Cannot find pandoc. Skipping convert building.md to HTML")
768     }
769   }
770
771   ignoreExitValue true
772
773   inputs.file(buildingMD)
774   inputs.file(css)
775   outputs.file(buildingHTML)
776 }
777
778
779 clean {
780   doFirst {
781     delete buildingHTML
782   }
783 }
784
785
786 task syncDocs(type: Sync) {
787   dependsOn convertBuildingMD
788   def syncDir = "${classesDir}/${docDir}"
789   from fileTree("${jalviewDir}/${docDir}")
790   into syncDir
791
792 }
793
794
795 task copyHelp(type: Copy) {
796   def inputDir = helpSourceDir
797   def outputDir = "${classesDir}/${help_dir}"
798   from(inputDir) {
799     exclude '**/*.gif'
800     exclude '**/*.jpg'
801     exclude '**/*.png'
802     filter(ReplaceTokens,
803       beginToken: '$$',
804       endToken: '$$',
805       tokens: [
806         'Version-Rel': JALVIEW_VERSION,
807         'Year-Rel': getDate("yyyy")
808       ]
809     )
810   }
811   from(inputDir) {
812     include '**/*.gif'
813     include '**/*.jpg'
814     include '**/*.png'
815   }
816   into outputDir
817
818   inputs.dir(inputDir)
819   outputs.files(helpFile)
820   outputs.dir(outputDir)
821 }
822
823
824 task syncLib(type: Sync) {
825   def syncDir = "${classesDir}/${libDistDir}"
826   from fileTree("${jalviewDir}/${libDistDir}")
827   into syncDir
828 }
829
830
831 task syncResources(type: Sync) {
832   from resourceDir
833   include "**/*.*"
834   into "${classesDir}"
835   preserve {
836     include "**"
837   }
838 }
839
840
841 task prepare {
842   dependsOn syncResources
843   dependsOn syncDocs
844   dependsOn copyHelp
845 }
846
847
848 //testReportDirName = "test-reports" // note that test workingDir will be $jalviewDir
849 test {
850   dependsOn prepare
851   dependsOn compileJava
852   if (use_clover) {
853     dependsOn cloverInstr
854   }
855
856   if (use_clover) {
857     print("Running tests " + (use_clover?"WITH":"WITHOUT") + " clover [clover="+use_clover+"]\n")
858   }
859
860   useTestNG() {
861     includeGroups testngGroups
862     excludeGroups testngExcludedGroups
863     preserveOrder true
864     useDefaultListeners=true
865   }
866
867   maxHeapSize = "1024m"
868
869   workingDir = jalviewDir
870   //systemProperties 'clover.jar' System.properties.clover.jar
871   sourceCompatibility = compile_source_compatibility
872   targetCompatibility = compile_target_compatibility
873   jvmArgs += additional_compiler_args
874
875 }
876
877
878 task buildIndices(type: JavaExec) {
879   dependsOn copyHelp
880   classpath = sourceSets.main.compileClasspath
881   main = "com.sun.java.help.search.Indexer"
882   workingDir = "${classesDir}/${help_dir}"
883   def argDir = "html"
884   args = [ argDir ]
885   inputs.dir("${workingDir}/${argDir}")
886
887   outputs.dir("${classesDir}/doc")
888   outputs.dir("${classesDir}/help")
889   outputs.file("${workingDir}/JavaHelpSearch/DOCS")
890   outputs.file("${workingDir}/JavaHelpSearch/DOCS.TAB")
891   outputs.file("${workingDir}/JavaHelpSearch/OFFSETS")
892   outputs.file("${workingDir}/JavaHelpSearch/POSITIONS")
893   outputs.file("${workingDir}/JavaHelpSearch/SCHEMA")
894   outputs.file("${workingDir}/JavaHelpSearch/TMAP")
895 }
896
897
898 task compileLinkCheck(type: JavaCompile) {
899   options.fork = true
900   classpath = files("${jalviewDir}/${utilsDir}")
901   destinationDir = file("${jalviewDir}/${utilsDir}")
902   source = fileTree(dir: "${jalviewDir}/${utilsDir}", include: ["HelpLinksChecker.java", "BufferedLineReader.java"])
903
904   inputs.file("${jalviewDir}/${utilsDir}/HelpLinksChecker.java")
905   inputs.file("${jalviewDir}/${utilsDir}/HelpLinksChecker.java")
906   outputs.file("${jalviewDir}/${utilsDir}/HelpLinksChecker.class")
907   outputs.file("${jalviewDir}/${utilsDir}/BufferedLineReader.class")
908 }
909
910
911 task linkCheck(type: JavaExec) {
912   dependsOn prepare, compileLinkCheck
913
914   def helpLinksCheckerOutFile = file("${jalviewDir}/${utilsDir}/HelpLinksChecker.out")
915   classpath = files("${jalviewDir}/${utilsDir}")
916   main = "HelpLinksChecker"
917   workingDir = jalviewDir
918   args = [ "${classesDir}/${help_dir}", "-nointernet" ]
919
920   def outFOS = new FileOutputStream(helpLinksCheckerOutFile, false) // false == don't append
921   def errFOS = outFOS
922   standardOutput = new org.apache.tools.ant.util.TeeOutputStream(
923     outFOS,
924     standardOutput)
925   errorOutput = new org.apache.tools.ant.util.TeeOutputStream(
926     outFOS,
927     errorOutput)
928
929   inputs.dir("${classesDir}/${help_dir}")
930   outputs.file(helpLinksCheckerOutFile)
931 }
932
933 // import the pubhtmlhelp target
934 ant.properties.basedir = "${jalviewDir}"
935 ant.properties.helpBuildDir = "${jalviewDirAbsolutePath}/${classes_dir}/${help_dir}"
936 ant.importBuild "${utilsDir}/publishHelp.xml"
937
938
939 task cleanPackageDir(type: Delete) {
940   doFirst {
941     delete fileTree(dir: "${jalviewDir}/${packageDir}", include: "*.jar")
942   }
943 }
944
945 jar {
946   dependsOn linkCheck
947   dependsOn buildIndices
948   dependsOn createBuildProperties
949
950   manifest {
951     attributes "Main-Class": mainClass,
952     "Permissions": "all-permissions",
953     "Application-Name": "Jalview Desktop",
954     "Codebase": application_codebase
955   }
956
957   destinationDir = file("${jalviewDir}/${packageDir}")
958   archiveName = rootProject.name+".jar"
959
960   exclude "cache*/**"
961   exclude "*.jar"
962   exclude "*.jar.*"
963   exclude "**/*.jar"
964   exclude "**/*.jar.*"
965
966   inputs.dir(classesDir)
967   outputs.file("${jalviewDir}/${packageDir}/${archiveName}")
968 }
969
970
971 task copyJars(type: Copy) {
972   from fileTree(dir: classesDir, include: "**/*.jar").files
973   into "${jalviewDir}/${packageDir}"
974 }
975
976
977 // doing a Sync instead of Copy as Copy doesn't deal with "outputs" very well
978 task syncJars(type: Sync) {
979   from fileTree(dir: "${jalviewDir}/${libDistDir}", include: "**/*.jar").files
980   into "${jalviewDir}/${packageDir}"
981   preserve {
982     include jar.archiveName
983   }
984 }
985
986
987 task makeDist {
988   group = "build"
989   description = "Put all required libraries in dist"
990   // order of "cleanPackageDir", "copyJars", "jar" important!
991   jar.mustRunAfter cleanPackageDir
992   syncJars.mustRunAfter cleanPackageDir
993   dependsOn cleanPackageDir
994   dependsOn syncJars
995   dependsOn jar
996   outputs.dir("${jalviewDir}/${packageDir}")
997 }
998
999
1000 task cleanDist {
1001   dependsOn cleanPackageDir
1002   dependsOn cleanTest
1003   dependsOn clean
1004 }
1005
1006 shadowJar {
1007   group = "distribution"
1008   if (buildDist) {
1009     dependsOn makeDist
1010   }
1011   from ("${jalviewDir}/${libDistDir}") {
1012     include("*.jar")
1013   }
1014   manifest {
1015     attributes 'Implementation-Version': JALVIEW_VERSION
1016   }
1017   mainClassName = shadowJarMainClass
1018   mergeServiceFiles()
1019   classifier = "all-"+JALVIEW_VERSION+"-j"+JAVA_VERSION
1020   minimize()
1021 }
1022
1023
1024 task getdownWebsite() {
1025   group = "distribution"
1026   description = "Create the getdown minimal app folder, and website folder for this version of jalview. Website folder also used for offline app installer"
1027   if (buildDist) {
1028     dependsOn makeDist
1029   }
1030
1031   def getdownWebsiteResourceFilenames = []
1032   def getdownTextString = ""
1033   def getdownResourceDir = getdownResourceDir
1034   def getdownResourceFilenames = []
1035
1036   doFirst {
1037     // clean the getdown website and files dir before creating getdown folders
1038     delete getdownWebsiteDir
1039     delete getdownFilesDir
1040
1041     copy {
1042       from buildProperties
1043       rename(build_properties_file, getdown_build_properties)
1044       into getdownAppDir
1045     }
1046     getdownWebsiteResourceFilenames += "${getdownAppDistDir}/${getdown_build_properties}"
1047
1048     // go through properties looking for getdown_txt_...
1049     def props = project.properties.sort { it.key }
1050     if (getdownAltJavaMinVersion != null && getdownAltJavaMinVersion.length() > 0) {
1051       props.put("getdown_txt_java_min_version", getdownAltJavaMinVersion)
1052     }
1053     if (getdownAltJavaMaxVersion != null && getdownAltJavaMaxVersion.length() > 0) {
1054       props.put("getdown_txt_java_max_version", getdownAltJavaMaxVersion)
1055     }
1056     if (getdownAltMultiJavaLocation != null && getdownAltMultiJavaLocation.length() > 0) {
1057       props.put("getdown_txt_multi_java_location", getdownAltMultiJavaLocation)
1058     }
1059
1060     props.put("getdown_txt_appbase", getdownAppBase)
1061     props.each{ prop, val ->
1062       if (prop.startsWith("getdown_txt_") && val != null) {
1063         if (prop.startsWith("getdown_txt_multi_")) {
1064           def key = prop.substring(18)
1065           val.split(",").each{ v ->
1066             def line = "${key} = ${v}\n"
1067             getdownTextString += line
1068           }
1069         } else {
1070           // file values rationalised
1071           if (val.indexOf('/') > -1 || prop.startsWith("getdown_txt_resource")) {
1072             def r = null
1073             if (val.indexOf('/') == 0) {
1074               // absolute path
1075               r = file(val)
1076             } else if (val.indexOf('/') > 0) {
1077               // relative path (relative to jalviewDir)
1078               r = file( "${jalviewDir}/${val}" )
1079             }
1080             if (r.exists()) {
1081               val = "${getdown_resource_dir}/" + r.getName()
1082               getdownWebsiteResourceFilenames += val
1083               getdownResourceFilenames += r.getPath()
1084             }
1085           }
1086           if (! prop.startsWith("getdown_txt_resource")) {
1087             def line = prop.substring(12) + " = ${val}\n"
1088             getdownTextString += line
1089           }
1090         }
1091       }
1092     }
1093
1094     getdownWebsiteResourceFilenames.each{ filename ->
1095       getdownTextString += "resource = ${filename}\n"
1096     }
1097     getdownResourceFilenames.each{ filename ->
1098       copy {
1099         from filename
1100         into getdownResourceDir
1101       }
1102     }
1103
1104     def codeFiles = []
1105     fileTree(file(packageDir)).each{ f ->
1106       if (f.isDirectory()) {
1107         def files = fileTree(dir: f, include: ["*"]).getFiles()
1108         codeFiles += files
1109       } else if (f.exists()) {
1110         codeFiles += f
1111       }
1112     }
1113     codeFiles.sort().each{f ->
1114       def name = f.getName()
1115       def line = "code = ${getdownAppDistDir}/${name}\n"
1116       getdownTextString += line
1117       copy {
1118         from f.getPath()
1119         into getdownAppDir
1120       }
1121     }
1122
1123     // NOT USING MODULES YET, EVERYTHING SHOULD BE IN dist
1124     /*
1125     if (JAVA_VERSION.equals("11")) {
1126     def j11libFiles = fileTree(dir: "${jalviewDir}/${j11libDir}", include: ["*.jar"]).getFiles()
1127     j11libFiles.sort().each{f ->
1128     def name = f.getName()
1129     def line = "code = ${getdown_j11lib_dir}/${name}\n"
1130     getdownTextString += line
1131     copy {
1132     from f.getPath()
1133     into getdownJ11libDir
1134     }
1135     }
1136     }
1137      */
1138
1139     // getdown-launcher.jar should not be in main application class path so the main application can move it when updated.  Listed as a resource so it gets updated.
1140     //getdownTextString += "class = " + file(getdownLauncher).getName() + "\n"
1141     getdownTextString += "resource = ${getdown_launcher_new}\n"
1142     getdownTextString += "class = ${mainClass}\n"
1143
1144     def getdown_txt = file("${getdownWebsiteDir}/getdown.txt")
1145     getdown_txt.write(getdownTextString)
1146
1147     def getdownLaunchJvl = getdown_launch_jvl_name + ( (jvlChannelName != null && jvlChannelName.length() > 0)?"-${jvlChannelName}":"" ) + ".jvl"
1148     def launchJvl = file("${getdownWebsiteDir}/${getdownLaunchJvl}")
1149     launchJvl.write("appbase="+props.get("getdown_txt_appbase"))
1150
1151     copy {
1152       from getdownLauncher
1153       rename(file(getdownLauncher).getName(), getdown_launcher_new)
1154       into getdownWebsiteDir
1155     }
1156
1157     copy {
1158       from getdownLauncher
1159       if (file(getdownLauncher).getName() != getdown_launcher) {
1160         rename(file(getdownLauncher).getName(), getdown_launcher)
1161       }
1162       into getdownWebsiteDir
1163     }
1164
1165     if (! (CHANNEL.startsWith("ARCHIVE") || CHANNEL.startsWith("DEVELOP"))) {
1166       copy {
1167         from getdown_txt
1168         from getdownLauncher
1169         from "${getdownWebsiteDir}/${getdown_build_properties}"
1170         if (file(getdownLauncher).getName() != getdown_launcher) {
1171           rename(file(getdownLauncher).getName(), getdown_launcher)
1172         }
1173         into getdownInstallDir
1174       }
1175
1176       copy {
1177         from getdownInstallDir
1178         into getdownFilesInstallDir
1179       }
1180     }
1181
1182     copy {
1183       from getdown_txt
1184       from launchJvl
1185       from getdownLauncher
1186       from "${getdownWebsiteDir}/${getdown_build_properties}"
1187       if (file(getdownLauncher).getName() != getdown_launcher) {
1188         rename(file(getdownLauncher).getName(), getdown_launcher)
1189       }
1190       into getdownFilesDir
1191     }
1192
1193     copy {
1194       from getdownResourceDir
1195       into "${getdownFilesDir}/${getdown_resource_dir}"
1196     }
1197   }
1198
1199   if (buildDist) {
1200     inputs.dir("${jalviewDir}/${packageDir}")
1201   }
1202   outputs.dir(getdownWebsiteDir)
1203   outputs.dir(getdownFilesDir)
1204 }
1205
1206
1207 // a helper task to allow getdown digest of any dir: `gradle getdownDigestDir -PDIGESTDIR=/path/to/my/random/getdown/dir
1208 task getdownDigestDir(type: JavaExec) {
1209   def digestDirPropertyName = "DIGESTDIR"
1210   description = "Digest a local dir (-P${digestDirPropertyName}=...) for getdown"
1211   doFirst {
1212     classpath = files(getdownLauncher)
1213     def digestDir = findProperty(digestDirPropertyName)
1214     if (digestDir == null) {
1215       throw new GradleException("Must provide a DIGESTDIR value to produce an alternative getdown digest")
1216     }
1217     args digestDir
1218   }
1219   main = "com.threerings.getdown.tools.Digester"
1220 }
1221
1222
1223 task getdownDigest(type: JavaExec) {
1224   group = "distribution"
1225   description = "Digest the getdown website folder"
1226   dependsOn getdownWebsite
1227   doFirst {
1228     classpath = files(getdownLauncher)
1229   }
1230   main = "com.threerings.getdown.tools.Digester"
1231   args getdownWebsiteDir
1232   inputs.dir(getdownWebsiteDir)
1233   outputs.file("${getdownWebsiteDir}/digest2.txt")
1234 }
1235
1236
1237 task getdown() {
1238   group = "distribution"
1239   description = "Create the minimal and full getdown app folder for installers and website and create digest file"
1240   dependsOn getdownDigest
1241   doLast {
1242     if (reportRsyncCommand) {
1243       def fromDir = getdownWebsiteDir + (getdownWebsiteDir.endsWith('/')?'':'/')
1244       def toDir = "${getdown_rsync_dest}/${getdownDir}" + (getdownDir.endsWith('/')?'':'/')
1245       println "LIKELY RSYNC COMMAND:"
1246       println "mkdir -p '$toDir'\nrsync -avh --delete '$fromDir' '$toDir'"
1247       if (RUNRSYNC == "true") {
1248         exec {
1249           commandLine "mkdir", "-p", toDir
1250         }
1251         exec {
1252           commandLine "rsync", "-avh", "--delete", fromDir, toDir
1253         }
1254       }
1255     }
1256   }
1257 }
1258
1259
1260 clean {
1261   doFirst {
1262     delete getdownWebsiteDir
1263     delete getdownFilesDir
1264   }
1265 }
1266
1267
1268 install4j {
1269   if (file(install4jHomeDir).exists()) {
1270     // good to go!
1271   } else if (file(System.getProperty("user.home")+"/buildtools/install4j").exists()) {
1272     install4jHomeDir = System.getProperty("user.home")+"/buildtools/install4j"
1273   } else if (file("/Applications/install4j.app/Contents/Resources/app").exists()) {
1274     install4jHomeDir = "/Applications/install4j.app/Contents/Resources/app"
1275   }
1276   installDir(file(install4jHomeDir))
1277
1278   mediaTypes = Arrays.asList(install4j_media_types.split(","))
1279 }
1280
1281
1282 task copyInstall4jTemplate {
1283   def install4jTemplateFile = file("${install4jDir}/${install4j_template}")
1284   def install4jFileAssociationsFile = file("${install4jDir}/${install4j_installer_file_associations}")
1285   inputs.file(install4jTemplateFile)
1286   inputs.file(install4jFileAssociationsFile)
1287   outputs.file(install4jConfFile)
1288
1289   doLast {
1290     def install4jConfigXml = new XmlParser().parse(install4jTemplateFile)
1291
1292     // turn off code signing if no OSX_KEYPASS
1293     if (OSX_KEYPASS == "") {
1294       install4jConfigXml.'**'.codeSigning.each { codeSigning ->
1295         codeSigning.'@macEnabled' = "false"
1296       }
1297       install4jConfigXml.'**'.windows.each { windows ->
1298         windows.'@runPostProcessor' = "false"
1299       }
1300     }
1301
1302     // turn off checksum creation for LOCAL channel
1303     def e = install4jConfigXml.application[0]
1304     if (CHANNEL == "LOCAL") {
1305       e.'@createChecksums' = "false"
1306     } else {
1307       e.'@createChecksums' = "true"
1308     }
1309
1310     // put file association actions where placeholder action is
1311     def install4jFileAssociationsText = install4jFileAssociationsFile.text
1312     def fileAssociationActions = new XmlParser().parseText("<actions>${install4jFileAssociationsText}</actions>")
1313     install4jConfigXml.'**'.action.any { a ->
1314       if (a.'@name' == 'EXTENSIONS_REPLACED_BY_GRADLE') {
1315         def parent = a.parent()
1316         parent.remove(a)
1317         fileAssociationActions.each { faa ->
1318             parent.append(faa)
1319         }
1320         // don't need to continue in .any loop once replacements have been made
1321         return true
1322       }
1323     }
1324
1325     // write install4j file
1326     install4jConfFile.text = XmlUtil.serialize(install4jConfigXml)
1327   }
1328 }
1329
1330
1331 clean {
1332   doFirst {
1333     delete install4jConfFile
1334   }
1335 }
1336
1337
1338 task installers(type: com.install4j.gradle.Install4jTask) {
1339   group = "distribution"
1340   description = "Create the install4j installers"
1341   dependsOn setGitVals
1342   dependsOn getdown
1343   dependsOn copyInstall4jTemplate
1344
1345   projectFile = install4jConfFile
1346
1347   // create an md5 for the input files to use as version for install4j conf file
1348   def digest = MessageDigest.getInstance("MD5")
1349   digest.update(
1350     (file("${install4jDir}/${install4j_template}").text + 
1351     file("${install4jDir}/${install4j_info_plist_file_associations}").text +
1352     file("${install4jDir}/${install4j_installer_file_associations}").text).bytes)
1353   def filesMd5 = new BigInteger(1, digest.digest()).toString(16)
1354   if (filesMd5.length() >= 8) {
1355     filesMd5 = filesMd5.substring(0,8)
1356   }
1357   def install4jTemplateVersion = "${JALVIEW_VERSION}_F${filesMd5}_C${gitHash}"
1358   // make install4jBuildDir relative to jalviewDir
1359   def install4jBuildDir = "${install4j_build_dir}/${JAVA_VERSION}"
1360
1361   variables = [
1362     'JALVIEW_NAME': getdown_txt_title,
1363     'JALVIEW_DIR': "../..",
1364     'OSX_KEYSTORE': OSX_KEYSTORE,
1365     'JSIGN_SH': JSIGN_SH,
1366     'JRE_DIR': getdown_app_dir_java,
1367     'INSTALLER_TEMPLATE_VERSION': install4jTemplateVersion,
1368     'JALVIEW_VERSION': JALVIEW_VERSION,
1369     'JAVA_MIN_VERSION': JAVA_MIN_VERSION,
1370     'JAVA_MAX_VERSION': JAVA_MAX_VERSION,
1371     'JAVA_VERSION': JAVA_VERSION,
1372     'JAVA_INTEGER_VERSION': JAVA_INTEGER_VERSION,
1373     'VERSION': JALVIEW_VERSION,
1374     'MACOS_JAVA_VM_DIR': macosJavaVMDir,
1375     'WINDOWS_JAVA_VM_DIR': windowsJavaVMDir,
1376     'LINUX_JAVA_VM_DIR': linuxJavaVMDir,
1377     'MACOS_JAVA_VM_TGZ': macosJavaVMTgz,
1378     'WINDOWS_JAVA_VM_TGZ': windowsJavaVMTgz,
1379     'LINUX_JAVA_VM_TGZ': linuxJavaVMTgz,
1380     'COPYRIGHT_MESSAGE': install4j_copyright_message,
1381     'MACOS_BUNDLE_ID': install4j_macOS_bundle_id,
1382     'INSTALLER_NAME': install4j_installer_name,
1383     'INSTALL4J_UTILS_DIR': install4j_utils_dir,
1384     'GETDOWN_WEBSITE_DIR': getdown_website_dir,
1385     'GETDOWN_FILES_DIR': getdown_files_dir,
1386     'GETDOWN_RESOURCE_DIR': getdown_resource_dir,
1387     'GETDOWN_DIST_DIR': getdownAppDistDir,
1388     'GETDOWN_ALT_DIR': getdown_app_dir_alt,
1389     'GETDOWN_INSTALL_DIR': getdown_install_dir,
1390     'INFO_PLIST_FILE_ASSOCIATIONS_FILE': install4j_info_plist_file_associations,
1391     'BUILD_DIR': install4jBuildDir,
1392     'UNIX_DESKTOP_ADDITIONS': install4j_unix_desktop_additions,
1393   ]
1394
1395   destination = "${jalviewDir}/${install4jBuildDir}"
1396   buildSelected = true
1397
1398   if (install4j_faster.equals("true") || CHANNEL.startsWith("LOCAL")) {
1399     faster = true
1400     disableSigning = true
1401   }
1402
1403   if (OSX_KEYPASS) {
1404     macKeystorePassword = OSX_KEYPASS
1405   }
1406
1407   doFirst {
1408     println("Using projectFile "+projectFile)
1409   }
1410
1411   inputs.dir(getdownWebsiteDir)
1412   inputs.file(install4jConfFile)
1413   inputs.file("${install4jDir}/${install4j_info_plist_file_associations}")
1414   inputs.dir(macosJavaVMDir)
1415   inputs.dir(windowsJavaVMDir)
1416   outputs.dir("${jalviewDir}/${install4j_build_dir}/${JAVA_VERSION}")
1417 }
1418
1419
1420 task sourceDist(type: Tar) {
1421   
1422   def VERSION_UNDERSCORES = JALVIEW_VERSION.replaceAll("\\.", "_")
1423   def outputFileName = "${project.name}_${VERSION_UNDERSCORES}.tar.gz"
1424   // cater for buildship < 3.1 [3.0.1 is max version in eclipse 2018-09]
1425   try {
1426     archiveFileName = outputFileName
1427   } catch (Exception e) {
1428     archiveName = outputFileName
1429   }
1430   
1431   compression Compression.GZIP
1432   
1433   into project.name
1434
1435   def EXCLUDE_FILES=[
1436     "build/*",
1437     "bin/*",
1438     "test-output/",
1439     "test-reports",
1440     "tests",
1441     "clover*/*",
1442     ".*",
1443     "benchmarking/*",
1444     "**/.*",
1445     "*.class",
1446     "**/*.class","$j11modDir/**/*.jar","appletlib","**/*locales",
1447     "*locales/**",
1448     "utils/InstallAnywhere",
1449     "**/*.log",
1450   ] 
1451   def PROCESS_FILES=[
1452     "AUTHORS",
1453     "CITATION",
1454     "FEATURETODO",
1455     "JAVA-11-README",
1456     "FEATURETODO",
1457     "LICENSE",
1458     "**/README",
1459     "RELEASE",
1460     "THIRDPARTYLIBS",
1461     "TESTNG",
1462     "build.gradle",
1463     "gradle.properties",
1464     "**/*.java",
1465     "**/*.html",
1466     "**/*.xml",
1467     "**/*.gradle",
1468     "**/*.groovy",
1469     "**/*.properties",
1470     "**/*.perl",
1471     "**/*.sh",
1472   ]
1473   def INCLUDE_FILES=[
1474     ".settings/org.eclipse.jdt.core.jalview.prefs",
1475   ]
1476
1477   from(jalviewDir) {
1478     exclude (EXCLUDE_FILES)
1479     include (PROCESS_FILES)
1480     filter(ReplaceTokens,
1481       beginToken: '$$',
1482       endToken: '$$',
1483       tokens: [
1484         'Version-Rel': JALVIEW_VERSION,
1485         'Year-Rel': getDate("yyyy")
1486       ]
1487     )
1488   }
1489   from(jalviewDir) {
1490     exclude (EXCLUDE_FILES)
1491     exclude (PROCESS_FILES)
1492     exclude ("appletlib")
1493     exclude ("**/*locales")
1494     exclude ("*locales/**")
1495     exclude ("utils/InstallAnywhere")
1496
1497     exclude (getdown_files_dir)
1498     exclude (getdown_website_dir)
1499
1500     // exluding these as not using jars as modules yet
1501     exclude ("$j11modDir/**/*.jar")
1502   }
1503   from(jalviewDir) {
1504     include(INCLUDE_FILES)
1505   }
1506 //  from (jalviewDir) {
1507 //    // explicit includes for stuff that seemed to not get included
1508 //    include(fileTree("test/**/*."))
1509 //    exclude(EXCLUDE_FILES)
1510 //    exclude(PROCESS_FILES)
1511 //  }
1512 }
1513
1514
1515 task helppages {
1516   dependsOn copyHelp
1517   dependsOn pubhtmlhelp
1518   
1519   inputs.dir("${classesDir}/${help_dir}")
1520   outputs.dir("${buildDir}/distributions/${help_dir}")
1521 }
1522
1523 // LARGE AMOUNT OF JALVIEWJS STUFF DELETED HERE
1524 task eclipseAutoBuildTask {}
1525 task eclipseSynchronizationTask {}