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