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