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