JAL-3521 Minimal plugins and tasks needed to run tests and build jalview.jar
[jalview.git] / build.gradle
1 /* Convention for properties.  Read from gradle.properties, use lower_case_underlines for property names.
2  * For properties set within build.gradle, use camelCaseNoSpace.
3  */
4 import org.apache.tools.ant.filters.ReplaceTokens
5
6
7
8
9 plugins {
10   id 'java'
11 }
12
13
14
15 // in ext the values are cast to Object. Ensure string values are cast as String (and not GStringImpl) for later use
16 def string(Object o) {
17   return o == null ? "" : o.toString()
18 }
19
20
21 ext {
22   jalviewDirAbsolutePath = file(jalviewDir).getAbsolutePath()
23   jalviewDirRelativePath = jalviewDir
24
25   // local build environment properties
26   // can be "projectDir/local.properties"
27   def localProps = "${projectDir}/local.properties"
28   def propsFile = null;
29   if (file(localProps).exists()) {
30     propsFile = localProps
31   }
32   // or "../projectDir_local.properties"
33   def dirLocalProps = projectDir.getParent() + "/" + projectDir.getName() + "_local.properties"
34   if (file(dirLocalProps).exists()) {
35     propsFile = dirLocalProps
36   }
37   if (propsFile != null) {
38     try {
39       def p = new Properties()
40       def localPropsFIS = new FileInputStream(propsFile)
41       p.load(localPropsFIS)
42       localPropsFIS.close()
43       p.each {
44         key, val -> 
45           def oldval = findProperty(key)
46           setProperty(key, val)
47           if (oldval != null) {
48             println("Overriding property '${key}' ('${oldval}') with ${file(propsFile).getName()} value '${val}'")
49           } else {
50             println("Setting unknown property '${key}' with ${file(propsFile).getName()}s value '${val}'")
51           }
52       }
53     } catch (Exception e) {
54       System.out.println("Exception reading local.properties")
55     }
56   }
57
58   ////  
59   // Import releaseProps from the RELEASE file
60   // or a file specified via JALVIEW_RELEASE_FILE if defined
61   // Expect jalview.version and target release branch in jalview.release        
62   def releaseProps = new Properties();
63   def releasePropFile = findProperty("JALVIEW_RELEASE_FILE");
64   def defaultReleasePropFile = "${jalviewDirAbsolutePath}/RELEASE";
65   try {
66     (new File(releasePropFile!=null ? releasePropFile : defaultReleasePropFile)).withInputStream { 
67      releaseProps.load(it)
68     }
69   } catch (Exception fileLoadError) {
70     throw new Error("Couldn't load release properties file "+(releasePropFile==null ? defaultReleasePropFile : "from custom location: releasePropFile"),fileLoadError);
71   }
72   ////
73   // Set JALVIEW_VERSION if it is not already set
74   if (findProperty("JALVIEW_VERSION")==null || "".equals(JALVIEW_VERSION)) {
75     JALVIEW_VERSION = releaseProps.get("jalview.version")
76   }
77   
78   // this property set when running Eclipse headlessly
79   j2sHeadlessBuildProperty = string("net.sf.j2s.core.headlessbuild")
80   // this property set by Eclipse
81   eclipseApplicationProperty = string("eclipse.application")
82   // CHECK IF RUNNING FROM WITHIN ECLIPSE
83   def eclipseApplicationPropertyVal = System.properties[eclipseApplicationProperty]
84   IN_ECLIPSE = eclipseApplicationPropertyVal != null && eclipseApplicationPropertyVal.startsWith("org.eclipse.ui.")
85   // BUT WITHOUT THE HEADLESS BUILD PROPERTY SET
86   if (System.properties[j2sHeadlessBuildProperty].equals("true")) {
87     println("Setting IN_ECLIPSE to ${IN_ECLIPSE} as System.properties['${j2sHeadlessBuildProperty}'] == '${System.properties[j2sHeadlessBuildProperty]}'")
88     IN_ECLIPSE = false
89   }
90   if (IN_ECLIPSE) {
91     println("WITHIN ECLIPSE IDE")
92   } else {
93     println("HEADLESS BUILD")
94   }
95   /* *-/
96   System.properties.sort { it.key }.each {
97     key, val -> println("SYSTEM PROPERTY ${key}='${val}'")
98   }
99   /-* *-/
100   if (false && IN_ECLIPSE) {
101     jalviewDir = jalviewDirAbsolutePath
102   }
103   */
104
105   // essentials
106   bareSourceDir = string(source_dir)
107   sourceDir = string("${jalviewDir}/${bareSourceDir}")
108   resourceDir = string("${jalviewDir}/${resource_dir}")
109   bareTestSourceDir = string(test_source_dir)
110   testDir = string("${jalviewDir}/${bareTestSourceDir}")
111
112   classesDir = string("${jalviewDir}/${classes_dir}")
113
114   // clover
115   useClover = clover.equals("true")
116   cloverBuildDir = "${buildDir}/clover"
117   cloverInstrDir = file("${cloverBuildDir}/clover-instr")
118   cloverClassesDir = file("${cloverBuildDir}/clover-classes")
119   cloverReportDir = file("${buildDir}/reports/clover")
120   cloverTestInstrDir = file("${cloverBuildDir}/clover-test-instr")
121   cloverTestClassesDir = file("${cloverBuildDir}/clover-test-classes")
122   //cloverTestClassesDir = cloverClassesDir
123   cloverDb = string("${cloverBuildDir}/clover.db")
124
125   resourceClassesDir = useClover ? cloverClassesDir : classesDir
126
127   testSourceDir = useClover ? cloverTestInstrDir : testDir
128   testClassesDir = useClover ? cloverTestClassesDir : "${jalviewDir}/${test_output_dir}"
129
130   getdownWebsiteDir = string("${jalviewDir}/${getdown_website_dir}/${JAVA_VERSION}")
131   buildDist = true
132
133   // the following values might be overridden by the CHANNEL switch
134   getdownChannelName = CHANNEL.toLowerCase()
135   getdownDir = string("${getdownChannelName}/${JAVA_VERSION}")
136   getdownAppBase = string("${getdown_channel_base}/${getdownDir}")
137   getdownLauncher = string("${jalviewDir}/${getdown_lib_dir}/${getdown_launcher}")
138   getdownAppDistDir = getdown_app_dir_alt
139   buildProperties = string("${classesDir}/${build_properties_file}")
140   reportRsyncCommand = false
141   jvlChannelName = CHANNEL.toLowerCase()
142   install4jSuffix = CHANNEL.substring(0, 1).toUpperCase() + CHANNEL.substring(1).toLowerCase(); // BUILD -> Build
143   install4jDSStore = "DS_Store-NON-RELEASE"
144   install4jDMGBackgroundImage = "jalview_dmg_background-NON-RELEASE.png"
145   install4jInstallerName = "${jalview_name} Non-Release Installer"
146   install4jExecutableName = jalview_name.replaceAll("[^\\w]+", "_").toLowerCase()
147   install4jExtraScheme = "jalviewx"
148   switch (CHANNEL) {
149
150     case "BUILD":
151     // TODO: get bamboo build artifact URL for getdown artifacts
152     getdown_channel_base = bamboo_channelbase
153     getdownChannelName = string("${bamboo_planKey}/${JAVA_VERSION}")
154     getdownAppBase = string("${bamboo_channelbase}/${bamboo_planKey}${bamboo_getdown_channel_suffix}/${JAVA_VERSION}")
155     jvlChannelName += "_${getdownChannelName}"
156     // automatically add the test group Not-bamboo for exclusion 
157     if ("".equals(testng_excluded_groups)) { 
158       testng_excluded_groups = "Not-bamboo"
159     }
160     install4jExtraScheme = "jalviewb"
161     break
162
163     case "RELEASE":
164     getdownAppDistDir = getdown_app_dir_release
165     reportRsyncCommand = true
166     install4jSuffix = ""
167     install4jDSStore = "DS_Store"
168     install4jDMGBackgroundImage = "jalview_dmg_background.png"
169     install4jInstallerName = "${jalview_name} Installer"
170     break
171
172     case "ARCHIVE":
173     getdownChannelName = CHANNEL.toLowerCase()+"/${JALVIEW_VERSION}"
174     getdownDir = string("${getdownChannelName}/${JAVA_VERSION}")
175     getdownAppBase = string("${getdown_channel_base}/${getdownDir}")
176     if (!file("${ARCHIVEDIR}/${package_dir}").exists()) {
177       throw new GradleException("Must provide an ARCHIVEDIR value to produce an archive distribution")
178     } else {
179       package_dir = string("${ARCHIVEDIR}/${package_dir}")
180       buildProperties = string("${ARCHIVEDIR}/${classes_dir}/${build_properties_file}")
181       buildDist = false
182     }
183     reportRsyncCommand = true
184     install4jExtraScheme = "jalviewa"
185     break
186
187     case "ARCHIVELOCAL":
188     getdownChannelName = string("archive/${JALVIEW_VERSION}")
189     getdownDir = string("${getdownChannelName}/${JAVA_VERSION}")
190     getdownAppBase = file(getdownWebsiteDir).toURI().toString()
191     if (!file("${ARCHIVEDIR}/${package_dir}").exists()) {
192       throw new GradleException("Must provide an ARCHIVEDIR value to produce an archive distribution")
193     } else {
194       package_dir = string("${ARCHIVEDIR}/${package_dir}")
195       buildProperties = string("${ARCHIVEDIR}/${classes_dir}/${build_properties_file}")
196       buildDist = false
197     }
198     reportRsyncCommand = true
199     getdownLauncher = string("${jalviewDir}/${getdown_lib_dir}/${getdown_launcher_local}")
200     install4jSuffix = "Archive"
201     install4jExtraScheme = "jalviewa"
202     break
203
204     case "DEVELOP":
205     reportRsyncCommand = true
206     
207     // DEVELOP-RELEASE is usually associated with a Jalview release series so set the version
208     JALVIEW_VERSION=JALVIEW_VERSION+"-develop"
209     
210     install4jSuffix = "Develop"
211     install4jDSStore = "DS_Store-DEVELOP"
212     install4jDMGBackgroundImage = "jalview_dmg_background-DEVELOP.png"
213     install4jExtraScheme = "jalviewd"
214     install4jInstallerName = "${jalview_name} Develop Installer"
215     break
216
217     case "TEST-RELEASE":
218     reportRsyncCommand = true
219     
220     // TEST-RELEASE is usually associated with a Jalview release series so set the version
221     JALVIEW_VERSION=JALVIEW_VERSION+"-test"
222     
223     install4jSuffix = "Test"
224     install4jDSStore = "DS_Store-TEST-RELEASE"
225     install4jDMGBackgroundImage = "jalview_dmg_background-TEST.png"
226     install4jExtraScheme = "jalviewt"
227     install4jInstallerName = "${jalview_name} Test Installer"
228     break
229
230     case ~/^SCRATCH(|-[-\w]*)$/:
231     getdownChannelName = CHANNEL
232     getdownDir = string("${getdownChannelName}/${JAVA_VERSION}")
233     getdownAppBase = string("${getdown_channel_base}/${getdownDir}")
234     reportRsyncCommand = true
235     install4jSuffix = "Scratch"
236     break
237
238     case "TEST-LOCAL":
239     if (!file("${LOCALDIR}").exists()) {
240       throw new GradleException("Must provide a LOCALDIR value to produce a local distribution")
241     } else {
242       getdownAppBase = file(file("${LOCALDIR}").getAbsolutePath()).toURI().toString()
243       getdownLauncher = string("${jalviewDir}/${getdown_lib_dir}/${getdown_launcher_local}")
244     }
245     JALVIEW_VERSION = "TEST"
246     install4jSuffix = "Test-Local"
247     install4jDSStore = "DS_Store-TEST-RELEASE"
248     install4jDMGBackgroundImage = "jalview_dmg_background-TEST.png"
249     install4jExtraScheme = "jalviewt"
250     install4jInstallerName = "${jalview_name} Test Installer"
251     break
252
253     case "LOCAL":
254     getdownAppBase = file(getdownWebsiteDir).toURI().toString()
255     getdownLauncher = string("${jalviewDir}/${getdown_lib_dir}/${getdown_launcher_local}")
256     install4jExtraScheme = "jalviewl"
257     break
258
259     default: // something wrong specified
260     throw new GradleException("CHANNEL must be one of BUILD, RELEASE, ARCHIVE, DEVELOP, TEST-RELEASE, SCRATCH-..., LOCAL [default]")
261     break
262
263   }
264   // override getdownAppBase if requested
265   if (findProperty("getdown_appbase_override") != null) {
266     getdownAppBase = string(getProperty("getdown_appbase_override"))
267     println("Overriding getdown appbase with '${getdownAppBase}'")
268   }
269   // sanitise file name for jalview launcher file for this channel
270   jvlChannelName = jvlChannelName.replaceAll("[^\\w\\-]+", "_")
271   // install4j application and folder names
272   if (install4jSuffix == "") {
273     install4jApplicationName = "${jalview_name}"
274     install4jBundleId = "${install4j_bundle_id}"
275     install4jWinApplicationId = install4j_release_win_application_id
276   } else {
277     install4jApplicationName = "${jalview_name} ${install4jSuffix}"
278     install4jBundleId = "${install4j_bundle_id}-" + install4jSuffix.toLowerCase()
279     // add int hash of install4jSuffix to the last part of the application_id
280     def id = install4j_release_win_application_id
281     def idsplitreverse = id.split("-").reverse()
282     idsplitreverse[0] = idsplitreverse[0].toInteger() + install4jSuffix.hashCode()
283     install4jWinApplicationId = idsplitreverse.reverse().join("-")
284   }
285   // sanitise folder and id names
286   // install4jApplicationFolder = e.g. "Jalview Build"
287   install4jApplicationFolder = install4jApplicationName
288                                     .replaceAll("[\"'~:/\\\\\\s]", "_") // replace all awkward filename chars " ' ~ : / \
289                                     .replaceAll("_+", "_") // collapse __
290   install4jInternalId = install4jApplicationName
291                                     .replaceAll(" ","_")
292                                     .replaceAll("[^\\w\\-\\.]", "_") // replace other non [alphanumeric,_,-,.]
293                                     .replaceAll("_+", "") // collapse __
294                                     //.replaceAll("_*-_*", "-") // collapse _-_
295   install4jUnixApplicationFolder = install4jApplicationName
296                                     .replaceAll(" ","_")
297                                     .replaceAll("[^\\w\\-\\.]", "_") // replace other non [alphanumeric,_,-,.]
298                                     .replaceAll("_+", "_") // collapse __
299                                     .replaceAll("_*-_*", "-") // collapse _-_
300                                     .toLowerCase()
301
302   getdownAppDir = string("${getdownWebsiteDir}/${getdownAppDistDir}")
303   //getdownJ11libDir = "${getdownWebsiteDir}/${getdown_j11lib_dir}"
304   getdownResourceDir = string("${getdownWebsiteDir}/${getdown_resource_dir}")
305   getdownInstallDir = string("${getdownWebsiteDir}/${getdown_install_dir}")
306   getdownFilesDir = string("${jalviewDir}/${getdown_files_dir}/${JAVA_VERSION}/")
307   getdownFilesInstallDir = string("${getdownFilesDir}/${getdown_install_dir}")
308   /* compile without modules -- using classpath libraries
309   modules_compileClasspath = fileTree(dir: "${jalviewDir}/${j11modDir}", include: ["*.jar"])
310   modules_runtimeClasspath = modules_compileClasspath
311   */
312   gitHash = string("")
313   gitBranch = string("")
314
315   println("Using a ${CHANNEL} profile.")
316
317   additional_compiler_args = []
318   // configure classpath/args for j8/j11 compilation
319   if (JAVA_VERSION.equals("1.8")) {
320     JAVA_INTEGER_VERSION = string("8")
321     //libDir = j8libDir
322     libDir = j11libDir
323     libDistDir = j8libDir
324     digestonlyDir = j8digestonlyDir
325     compile_source_compatibility = 1.8
326     compile_target_compatibility = 1.8
327     // these are getdown.txt properties defined dependent on the JAVA_VERSION
328     getdownAltJavaMinVersion = string(findProperty("getdown_alt_java8_min_version"))
329     getdownAltJavaMaxVersion = string(findProperty("getdown_alt_java8_max_version"))
330     // this property is assigned below and expanded to multiple lines in the getdown task
331     getdownAltMultiJavaLocation = string(findProperty("getdown_alt_java8_txt_multi_java_location"))
332     // this property is for the Java library used in eclipse
333     eclipseJavaRuntimeName = string("JavaSE-1.8")
334   } else if (JAVA_VERSION.equals("11")) {
335     JAVA_INTEGER_VERSION = string("11")
336     libDir = j11libDir
337     libDistDir = j11libDir
338     digestonlyDir = j11digestonlyDir
339     compile_source_compatibility = 11
340     compile_target_compatibility = 11
341     getdownAltJavaMinVersion = string(findProperty("getdown_alt_java11_min_version"))
342     getdownAltJavaMaxVersion = string(findProperty("getdown_alt_java11_max_version"))
343     getdownAltMultiJavaLocation = string(findProperty("getdown_alt_java11_txt_multi_java_location"))
344     eclipseJavaRuntimeName = string("JavaSE-11")
345     /* compile without modules -- using classpath libraries
346     additional_compiler_args += [
347     '--module-path', modules_compileClasspath.asPath,
348     '--add-modules', j11modules
349     ]
350      */
351   } else if (JAVA_VERSION.equals("12") || JAVA_VERSION.equals("13")) {
352     JAVA_INTEGER_VERSION = JAVA_VERSION
353     libDir = j11libDir
354     libDistDir = j11libDir
355     compile_source_compatibility = JAVA_VERSION
356     compile_target_compatibility = JAVA_VERSION
357     getdownAltJavaMinVersion = string(findProperty("getdown_alt_java11_min_version"))
358     getdownAltJavaMaxVersion = string(findProperty("getdown_alt_java11_max_version"))
359     getdownAltMultiJavaLocation = string(findProperty("getdown_alt_java11_txt_multi_java_location"))
360     eclipseJavaRuntimeName = string("JavaSE-11")
361     /* compile without modules -- using classpath libraries
362     additional_compiler_args += [
363     '--module-path', modules_compileClasspath.asPath,
364     '--add-modules', j11modules
365     ]
366      */
367   } else {
368     throw new GradleException("JAVA_VERSION=${JAVA_VERSION} not currently supported by Jalview")
369   }
370
371
372   // for install4j
373   JAVA_MIN_VERSION = JAVA_VERSION
374   JAVA_MAX_VERSION = JAVA_VERSION
375   def jreInstallsDir = string(jre_installs_dir)
376   if (jreInstallsDir.startsWith("~/")) {
377     jreInstallsDir = System.getProperty("user.home") + jreInstallsDir.substring(1)
378   }
379   macosJavaVMDir = string("${jreInstallsDir}/jre-${JAVA_INTEGER_VERSION}-mac-x64/jre")
380   macosJavaVMTgz = string("${jreInstallsDir}/tgz/jre-${JAVA_INTEGER_VERSION}-mac-x64.tar.gz")
381   windowsJavaVMDir = string("${jreInstallsDir}/jre-${JAVA_INTEGER_VERSION}-windows-x64/jre")
382   windowsJavaVMTgz = string("${jreInstallsDir}/tgz/jre-${JAVA_INTEGER_VERSION}-windows-x64.tar.gz")
383   linuxJavaVMDir = string("${jreInstallsDir}/jre-${JAVA_INTEGER_VERSION}-linux-x64/jre")
384   linuxJavaVMTgz = string("${jreInstallsDir}/tgz/jre-${JAVA_INTEGER_VERSION}-linux-x64.tar.gz")
385   install4jDir = string("${jalviewDir}/${install4j_utils_dir}")
386   install4jConfFileName = string("jalview-install4j-conf.install4j")
387   install4jConfFile = file("${install4jDir}/${install4jConfFileName}")
388   install4jHomeDir = install4j_home_dir
389   if (install4jHomeDir.startsWith("~/")) {
390     install4jHomeDir = System.getProperty("user.home") + install4jHomeDir.substring(1)
391   }
392
393
394
395   buildingHTML = string("${jalviewDir}/${doc_dir}/building.html")
396   helpFile = string("${resourceClassesDir}/${help_dir}/help.jhm")
397   helpParentDir = string("${jalviewDir}/${help_parent_dir}")
398   helpSourceDir = string("${helpParentDir}/${help_dir}")
399
400
401   relativeBuildDir = file(jalviewDirAbsolutePath).toPath().relativize(buildDir.toPath())
402   jalviewjsBuildDir = string("${relativeBuildDir}/jalviewjs")
403   jalviewjsSiteDir = string("${jalviewjsBuildDir}/${jalviewjs_site_dir}")
404   if (IN_ECLIPSE) {
405     jalviewjsTransferSiteJsDir = string(jalviewjsSiteDir)
406   } else {
407     jalviewjsTransferSiteJsDir = string("${jalviewjsBuildDir}/tmp/${jalviewjs_site_dir}_js")
408   }
409   jalviewjsTransferSiteLibDir = string("${jalviewjsBuildDir}/tmp/${jalviewjs_site_dir}_lib")
410   jalviewjsTransferSiteSwingJsDir = string("${jalviewjsBuildDir}/tmp/${jalviewjs_site_dir}_swingjs")
411   jalviewjsTransferSiteCoreDir = string("${jalviewjsBuildDir}/tmp/${jalviewjs_site_dir}_core")
412   jalviewjsJalviewCoreHtmlFile = string("")
413   jalviewjsJalviewCoreName = string(jalviewjs_core_name)
414   jalviewjsCoreClasslists = []
415   jalviewjsJalviewTemplateName = string(jalviewjs_name)
416   jalviewjsJ2sSettingsFileName = string("${jalviewDir}/${jalviewjs_j2s_settings}")
417   jalviewjsJ2sProps = null
418
419   eclipseWorkspace = null
420   eclipseBinary = string("")
421   eclipseVersion = string("")
422   eclipseDebug = false
423   // ENDEXT
424 }
425
426
427 sourceSets {
428   main {
429     java {
430       srcDirs sourceDir
431       outputDir = file(classesDir)
432     }
433
434     resources {
435       srcDirs resourceDir
436       srcDirs += helpParentDir
437     }
438
439     jar.destinationDir = file("${jalviewDir}/${package_dir}")
440
441     compileClasspath = files(sourceSets.main.java.outputDir)
442     compileClasspath += fileTree(dir: "${jalviewDir}/${libDir}", include: ["*.jar"])
443
444     runtimeClasspath = compileClasspath
445   }
446
447   test {
448     java {
449       srcDirs testSourceDir
450       outputDir = file(testClassesDir)
451     }
452
453     resources {
454       srcDirs = sourceSets.main.resources.srcDirs
455     }
456
457     compileClasspath = files( sourceSets.test.java.outputDir )
458     compileClasspath += sourceSets.main.compileClasspath
459     compileClasspath += fileTree(dir: "${jalviewDir}/${utils_dir}/testnglibs", include: ["**/*.jar"])
460
461     runtimeClasspath = compileClasspath
462   }
463
464 }
465
466
467
468
469 compileJava {
470
471   doFirst {
472     sourceCompatibility = compile_source_compatibility
473     targetCompatibility = compile_target_compatibility
474     options.compilerArgs = additional_compiler_args
475     print ("Setting target compatibility to "+targetCompatibility+"\n")
476   }
477
478 }
479
480
481 compileTestJava {
482   doFirst {
483     sourceCompatibility = compile_source_compatibility
484     targetCompatibility = compile_target_compatibility
485     options.compilerArgs = additional_compiler_args
486     print ("Setting target compatibility to "+targetCompatibility+"\n")
487   }
488 }
489
490
491 clean {
492   doFirst {
493     delete sourceSets.main.java.outputDir
494   }
495 }
496
497
498 cleanTest {
499   doFirst {
500     delete sourceSets.test.java.outputDir
501   }
502 }
503
504
505 // format is a string like date.format("dd MMMM yyyy")
506 def getDate(format) {
507   def date = new Date()
508   return date.format(format)
509 }
510
511
512 task setGitVals {
513   def hashStdOut = new ByteArrayOutputStream()
514   exec {
515     commandLine "git", "rev-parse", "--short", "HEAD"
516     standardOutput = hashStdOut
517     ignoreExitValue true
518   }
519
520   def branchStdOut = new ByteArrayOutputStream()
521   exec {
522     commandLine "git", "rev-parse", "--abbrev-ref", "HEAD"
523     standardOutput = branchStdOut
524     ignoreExitValue true
525   }
526
527   gitHash = hashStdOut.toString().trim()
528   gitBranch = branchStdOut.toString().trim()
529
530   outputs.upToDateWhen { false }
531 }
532
533
534 task createBuildProperties(type: WriteProperties) {
535   dependsOn setGitVals
536   inputs.dir(sourceDir)
537   inputs.dir(resourceDir)
538   file(buildProperties).getParentFile().mkdirs()
539   outputFile (buildProperties)
540   // taking time specific comment out to allow better incremental builds
541   comment "--Jalview Build Details--\n"+getDate("yyyy-MM-dd HH:mm:ss")
542   //comment "--Jalview Build Details--\n"+getDate("yyyy-MM-dd")
543   property "BUILD_DATE", getDate("HH:mm:ss dd MMMM yyyy")
544   property "VERSION", JALVIEW_VERSION
545   property "INSTALLATION", INSTALLATION+" git-commit:"+gitHash+" ["+gitBranch+"]"
546   outputs.file(outputFile)
547 }
548
549
550 task cleanBuildingHTML(type: Delete) {
551   doFirst {
552     delete buildingHTML
553   }
554 }
555
556
557 task convertBuildingMD(type: Exec) {
558   dependsOn cleanBuildingHTML
559   def buildingMD = "${jalviewDir}/${doc_dir}/building.md"
560   def css = "${jalviewDir}/${doc_dir}/github.css"
561
562   def pandoc = null
563   pandoc_exec.split(",").each {
564     if (file(it.trim()).exists()) {
565       pandoc = it.trim()
566       return true
567     }
568   }
569
570   def hostname = "hostname".execute().text.trim()
571   def buildtoolsPandoc = System.getProperty("user.home")+"/buildtools/pandoc/bin/pandoc"
572   if ((pandoc == null || ! file(pandoc).exists()) && file(buildtoolsPandoc).exists()) {
573     pandoc = System.getProperty("user.home")+"/buildtools/pandoc/bin/pandoc"
574   }
575
576   doFirst {
577     if (pandoc != null && file(pandoc).exists()) {
578         commandLine pandoc, '-s', '-o', buildingHTML, '--metadata', 'pagetitle="Building Jalview from Source"', '--toc', '-H', css, buildingMD
579     } else {
580         println("Cannot find pandoc. Skipping convert building.md to HTML")
581         throw new StopExecutionException("Cannot find pandoc. Skipping convert building.md to HTML")
582     }
583   }
584
585   ignoreExitValue true
586
587   inputs.file(buildingMD)
588   inputs.file(css)
589   outputs.file(buildingHTML)
590 }
591
592
593 clean {
594   doFirst {
595     delete buildingHTML
596   }
597 }
598
599
600 task syncDocs(type: Sync) {
601   dependsOn convertBuildingMD
602   def syncDir = "${resourceClassesDir}/${doc_dir}"
603   from fileTree("${jalviewDir}/${doc_dir}")
604   into syncDir
605
606 }
607
608
609 task copyHelp(type: Copy) {
610   def inputDir = helpSourceDir
611   def outputDir = "${resourceClassesDir}/${help_dir}"
612   from(inputDir) {
613     exclude '**/*.gif'
614     exclude '**/*.jpg'
615     exclude '**/*.png'
616     filter(ReplaceTokens,
617       beginToken: '$$',
618       endToken: '$$',
619       tokens: [
620         'Version-Rel': JALVIEW_VERSION,
621         'Year-Rel': getDate("yyyy")
622       ]
623     )
624   }
625   from(inputDir) {
626     include '**/*.gif'
627     include '**/*.jpg'
628     include '**/*.png'
629   }
630   into outputDir
631
632   inputs.dir(inputDir)
633   outputs.files(helpFile)
634   outputs.dir(outputDir)
635 }
636
637
638 task syncResources(type: Sync) {
639   from resourceDir
640   include "**/*.*"
641   into "${resourceClassesDir}"
642   preserve {
643     include "**"
644   }
645 }
646
647
648 task prepare {
649   dependsOn syncResources
650   dependsOn syncDocs
651   dependsOn copyHelp
652 }
653
654
655 //testReportDirName = "test-reports" // note that test workingDir will be $jalviewDir
656 test {
657   dependsOn prepare
658   //dependsOn compileJava ////? DELETE
659
660   dependsOn compileJava //?
661
662   useTestNG() {
663     includeGroups testng_groups
664     excludeGroups testng_excluded_groups
665     preserveOrder true
666     useDefaultListeners=true
667   }
668
669   maxHeapSize = "1024m"
670
671   workingDir = jalviewDir
672   //systemProperties 'clover.jar' System.properties.clover.jar
673   def testLaf = project.findProperty("test_laf")
674   if (testLaf != null) {
675     println("Setting Test LaF to '${testLaf}'")
676     systemProperty "laf", testLaf
677   }
678   def testHiDPIScale = project.findProperty("test_HiDPIScale")
679   if (testHiDPIScale != null) {
680     println("Setting Test HiDPI Scale to '${testHiDPIScale}'")
681     systemProperty "sun.java2d.uiScale", testHiDPIScale
682   }
683   sourceCompatibility = compile_source_compatibility
684   targetCompatibility = compile_target_compatibility
685   jvmArgs += additional_compiler_args
686
687   doFirst {
688   }
689 }
690
691
692 task buildIndices(type: JavaExec) {
693   dependsOn copyHelp
694   classpath = sourceSets.main.compileClasspath
695   main = "com.sun.java.help.search.Indexer"
696   workingDir = "${classesDir}/${help_dir}"
697   def argDir = "html"
698   args = [ argDir ]
699   inputs.dir("${workingDir}/${argDir}")
700
701   outputs.dir("${classesDir}/doc")
702   outputs.dir("${classesDir}/help")
703   outputs.file("${workingDir}/JavaHelpSearch/DOCS")
704   outputs.file("${workingDir}/JavaHelpSearch/DOCS.TAB")
705   outputs.file("${workingDir}/JavaHelpSearch/OFFSETS")
706   outputs.file("${workingDir}/JavaHelpSearch/POSITIONS")
707   outputs.file("${workingDir}/JavaHelpSearch/SCHEMA")
708   outputs.file("${workingDir}/JavaHelpSearch/TMAP")
709 }
710
711
712 task compileLinkCheck(type: JavaCompile) {
713   options.fork = true
714   classpath = files("${jalviewDir}/${utils_dir}")
715   destinationDir = file("${jalviewDir}/${utils_dir}")
716   source = fileTree(dir: "${jalviewDir}/${utils_dir}", include: ["HelpLinksChecker.java", "BufferedLineReader.java"])
717
718   inputs.file("${jalviewDir}/${utils_dir}/HelpLinksChecker.java")
719   inputs.file("${jalviewDir}/${utils_dir}/HelpLinksChecker.java")
720   outputs.file("${jalviewDir}/${utils_dir}/HelpLinksChecker.class")
721   outputs.file("${jalviewDir}/${utils_dir}/BufferedLineReader.class")
722 }
723
724
725 task linkCheck(type: JavaExec) {
726   dependsOn prepare, compileLinkCheck
727
728   def helpLinksCheckerOutFile = file("${jalviewDir}/${utils_dir}/HelpLinksChecker.out")
729   classpath = files("${jalviewDir}/${utils_dir}")
730   main = "HelpLinksChecker"
731   workingDir = jalviewDir
732   args = [ "${classesDir}/${help_dir}", "-nointernet" ]
733
734   def outFOS = new FileOutputStream(helpLinksCheckerOutFile, false) // false == don't append
735   def errFOS = outFOS
736   standardOutput = new org.apache.tools.ant.util.TeeOutputStream(
737     outFOS,
738     standardOutput)
739   errorOutput = new org.apache.tools.ant.util.TeeOutputStream(
740     outFOS,
741     errorOutput)
742
743   inputs.dir("${classesDir}/${help_dir}")
744   outputs.file(helpLinksCheckerOutFile)
745 }
746
747 // import the pubhtmlhelp target
748 ant.properties.basedir = "${jalviewDir}"
749 ant.properties.helpBuildDir = "${jalviewDirAbsolutePath}/${classes_dir}/${help_dir}"
750 ant.importBuild "${utils_dir}/publishHelp.xml"
751
752
753 task cleanPackageDir(type: Delete) {
754   doFirst {
755     delete fileTree(dir: "${jalviewDir}/${package_dir}", include: "*.jar")
756   }
757 }
758
759 jar {
760   dependsOn linkCheck
761   dependsOn buildIndices
762   dependsOn createBuildProperties
763
764   manifest {
765     attributes "Main-Class": main_class,
766     "Permissions": "all-permissions",
767     "Application-Name": "Jalview Desktop",
768     "Codebase": application_codebase
769   }
770
771   destinationDir = file("${jalviewDir}/${package_dir}")
772   archiveName = rootProject.name+".jar"
773
774   exclude "cache*/**"
775   exclude "*.jar"
776   exclude "*.jar.*"
777   exclude "**/*.jar"
778   exclude "**/*.jar.*"
779
780   inputs.dir(classesDir)
781   outputs.file("${jalviewDir}/${package_dir}/${archiveName}")
782 }