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