JAL-3111 JAL-3348 JVL file documentation
[jalview.git] / build.gradle
1 import org.apache.tools.ant.filters.ReplaceTokens
2 //import org.apache.tools.ant.filters.ReplaceRegexp
3 import org.gradle.internal.os.OperatingSystem
4 import org.gradle.plugins.ide.eclipse.model.*
5
6
7 import groovy.transform.ExternalizeMethods
8
9 buildscript {
10   dependencies {
11     classpath 'org.openclover:clover:4.3.1'
12     classpath 'org.apache.commons:commons-compress:1.18'
13   }
14 }
15
16 plugins {
17   id 'java'
18   id 'application'
19   id 'eclipse'
20   id 'com.github.johnrengelman.shadow' version '4.0.3'
21   id 'com.install4j.gradle' version '7.0.9'
22 }
23
24 repositories {
25   jcenter()
26   mavenCentral()
27   mavenLocal()
28   flatDir {
29     dirs gradlePluginsDir
30   }
31 }
32
33 mainClassName = launcherClass
34 def cloverInstrDir = file("$buildDir/$cloverSourcesInstrDir")
35 def classes = "$jalviewDir/$classesDir"
36
37 if (clover.equals("true")) {
38   use_clover = true
39   classes = "$buildDir/$cloverClassesDir"
40 } else {
41   use_clover = false
42   classes = "$jalviewDir/$classesDir"
43 }
44
45 // configure classpath/args for j8/j11 compilation
46
47 def jalviewDirAbsolutePath = file(jalviewDir).getAbsolutePath()
48 def libDir
49 def libDistDir
50 def compile_source_compatibility
51 def compile_target_compatibility
52
53 ext {
54   getdownWebsiteDir = jalviewDir + '/' + getdown_website_dir + '/' + JAVA_VERSION
55   getdownDir = ""
56   reportRsyncCmd = false
57   buildDist = true
58   buildProperties = buildPropertiesFile
59   switch (CHANNEL) {
60
61     case "BUILD":
62     // TODO: get bamboo build artifact URL for getdown artifacts
63     getdown_app_dir = getdown_app_dir_alt
64     buildProperties = jalviewDir + "/" + classesDir +"/" + buildPropertiesFile
65     break
66
67     case "RELEASE":
68     getdown_channel_name = CHANNEL.toLowerCase()
69     getdownDir = getdown_channel_name + "/" + JAVA_VERSION
70     getdown_app_base = getdown_channel_base + "/" + getdownDir
71     getdown_app_dir = getdown_app_dir_release
72     buildProperties = jalviewDir + "/" + classesDir +"/" + buildPropertiesFile
73     reportRsyncCommand = true
74     break
75
76     case "ARCHIVE":
77     getdown_channel_name = CHANNEL.toLowerCase()+"/"+JALVIEW_VERSION
78     getdownDir = getdown_channel_name + "/" + JAVA_VERSION
79     getdown_app_base = getdown_channel_base + "/" + getdownDir
80     getdown_app_dir = getdown_app_dir_alt
81     if (!file(ARCHIVEDIR+"/"+packageDir).exists()) {
82       print "Must provide an ARCHIVEDIR value to produce an archive distribution"
83       exit
84     } else {
85       packageDir = ARCHIVEDIR + "/" + packageDir
86       buildProperties = ARCHIVEDIR +"/" + classesDir + "/" + buildPropertiesFile
87       buildDist = false
88     }
89     reportRsyncCommand = true
90     break
91
92     case "ARCHIVELOCAL":
93     getdown_channel_name = "archive" + "/" + JALVIEW_VERSION
94     getdownDir = getdown_channel_name + "/" + JAVA_VERSION
95     getdown_app_base = file(getdownWebsiteDir).toURI().toString()
96     getdown_app_dir = getdown_app_dir_alt
97     if (!file(ARCHIVEDIR+"/"+packageDir).exists()) {
98       print "Must provide an ARCHIVEDIR value to produce an archive distribution"
99       exit
100     } else {
101       packageDir = ARCHIVEDIR + "/" + packageDir
102       buildProperties = ARCHIVEDIR +"/" + classesDir + "/" + buildPropertiesFile
103       buildDist = false
104     }
105     reportRsyncCommand = true
106     break
107
108     case "DEVELOP":
109     getdown_channel_name = CHANNEL.toLowerCase()
110     getdownDir = getdown_channel_name + "/" + JAVA_VERSION
111     getdown_app_base = getdown_channel_base + "/" + getdownDir
112     getdown_app_dir = getdown_app_dir_alt
113     buildProperties = jalviewDir + "/" + classesDir +"/" + buildPropertiesFile
114     reportRsyncCommand = true
115     break
116
117     case "TEST-RELEASE":
118     getdown_channel_name = CHANNEL.toLowerCase()
119     getdownDir = getdown_channel_name + "/" + JAVA_VERSION
120     getdown_app_base = getdown_channel_base + "/" + getdownDir
121     getdown_app_dir = getdown_app_dir_alt
122     buildProperties = jalviewDir + "/" + classesDir +"/" + buildPropertiesFile
123     reportRsyncCommand = true
124     break
125
126     case ~/^SCRATCH(|-[-\w]*)$/:
127     getdown_channel_name = CHANNEL
128     getdownDir = getdown_channel_name + "/" + JAVA_VERSION
129     getdown_app_base = getdown_channel_base + "/" + getdownDir
130     getdown_app_dir = getdown_app_dir_alt
131     buildProperties = jalviewDir + "/" + classesDir +"/" + buildPropertiesFile
132     reportRsyncCommand = true
133     break
134
135     case "LOCAL":
136     getdown_app_base = file(getdownWebsiteDir).toURI().toString()
137     getdown_app_dir = getdown_app_dir_alt
138     buildProperties = jalviewDir + "/" + classesDir +"/" + buildPropertiesFile
139     break
140
141     default: // something wrong specified
142     print("CHANNEL must be one of BUILD, RELEASE, ARCHIVE, DEVELOP, TEST-RELEASE, SCRATCH-..., LOCAL [default]")
143     exit
144     break
145
146   }
147
148   println("Using a "+CHANNEL+" profile. appbase="+getdown_app_base)
149   getdownAppDir = getdownWebsiteDir + '/' + getdown_app_dir
150   //getdownJ11libDir = getdownWebsiteDir + '/' + getdown_j11lib_dir
151   getdownResourceDir = getdownWebsiteDir + '/' + getdown_resource_dir
152   getdownInstallDir = getdownWebsiteDir + '/' + getdown_install_dir
153   getdownLauncher = jalviewDir + '/' + getdown_launcher
154   getdownFilesDir = jalviewDir + '/' + getdown_files_dir + '/' + JAVA_VERSION + '/'
155   getdownFilesInstallDir = getdownFilesDir+"/"+getdown_install_dir
156   /* compile without modules -- using classpath libraries
157   modules_compileClasspath = fileTree(dir: "$jalviewDir/$j11modDir", include: ["*.jar"])
158   modules_runtimeClasspath = modules_compileClasspath
159   */
160   gitHash = ""
161   gitBranch = ""
162 }
163
164 def JAVA_INTEGER_VERSION
165 def additional_compiler_args = []
166 // these are getdown.txt properties defined dependent on the JAVA_VERSION
167 def getdown_alt_java_min_version
168 def getdown_alt_java_max_version
169 // this property is assigned below and expanded to multiple lines in the getdown task
170 def getdown_alt_multi_java_location
171 // this property is for the Java library used in eclipse
172 def eclipse_java_runtime_name
173 if (JAVA_VERSION.equals("1.8")) {
174   JAVA_INTEGER_VERSION = "8"
175   //libDir = j8libDir
176   libDir = j11libDir
177   libDistDir = j8libDir
178   compile_source_compatibility = 1.8
179   compile_target_compatibility = 1.8
180   getdown_alt_java_min_version = getdown_alt_java8_min_version
181   getdown_alt_java_max_version = getdown_alt_java8_max_version
182   getdown_alt_multi_java_location = getdown_alt_java8_txt_multi_java_location
183   eclipse_java_runtime_name = "JavaSE-1.8"
184 } else if (JAVA_VERSION.equals("11")) {
185   JAVA_INTEGER_VERSION = "11"
186   libDir = j11libDir
187   libDistDir = j11libDir
188   compile_source_compatibility = 11
189   compile_target_compatibility = 11
190   getdown_alt_java_min_version = getdown_alt_java11_min_version
191   getdown_alt_java_max_version = getdown_alt_java11_max_version
192   getdown_alt_multi_java_location = getdown_alt_java11_txt_multi_java_location
193   eclipse_java_runtime_name = "JavaSE-11"
194   /* compile without modules -- using classpath libraries
195   additional_compiler_args += [
196   '--module-path', ext.modules_compileClasspath.asPath,
197   '--add-modules', j11modules
198   ]
199   */
200 } else if (JAVA_VERSION.equals("12") || JAVA_VERSION.equals("13")) {
201   JAVA_INTEGER_VERSION = JAVA_VERSION
202   libDir = j11libDir
203   libDistDir = j11libDir
204   compile_source_compatibility = JAVA_VERSION
205   compile_target_compatibility = JAVA_VERSION
206   getdown_alt_java_min_version = getdown_alt_java11_min_version
207   getdown_alt_java_max_version = getdown_alt_java11_max_version
208   getdown_alt_multi_java_location = getdown_alt_java11_txt_multi_java_location
209   eclipse_java_runtime_name = "JavaSE-11"
210   /* compile without modules -- using classpath libraries
211   additional_compiler_args += [
212   '--module-path', ext.modules_compileClasspath.asPath,
213   '--add-modules', j11modules
214   ]
215   */
216 } else {
217   throw new GradleException("JAVA_VERSION=$JAVA_VERSION not currently supported by Jalview")
218 }
219
220 sourceSets {
221
222   main {
223     java {
224       srcDirs "$jalviewDir/$sourceDir"
225       outputDir = file("$classes")
226     }
227
228     resources {
229       srcDirs "$jalviewDir/$resourceDir"
230     }
231
232     jar.destinationDir = file("$jalviewDir/$packageDir")
233
234     compileClasspath = files(sourceSets.main.java.outputDir)
235     compileClasspath += fileTree(dir: "$jalviewDir/$libDir", include: ["*.jar"])
236
237     runtimeClasspath = compileClasspath
238   }
239   clover {
240     java {
241       srcDirs = [ cloverInstrDir ]
242       outputDir = file("${buildDir}/${cloverClassesDir}")
243     }
244
245     resources {
246       srcDirs = sourceSets.main.resources.srcDirs
247     }
248     compileClasspath = configurations.cloverRuntime + files( sourceSets.clover.java.outputDir )
249     compileClasspath += files(sourceSets.main.java.outputDir)
250     compileClasspath += sourceSets.main.compileClasspath
251     compileClasspath += fileTree(dir: "$jalviewDir/$utilsDir", include: ["**/*.jar"])
252     compileClasspath += fileTree(dir: "$jalviewDir/$libDir", include: ["*.jar"])
253
254     runtimeClasspath = compileClasspath
255   }
256
257   test {
258     java {
259       srcDirs "$jalviewDir/$testSourceDir"
260       outputDir = file("$jalviewDir/$testOutputDir")
261     }
262
263     resources {
264       srcDirs = sourceSets.main.resources.srcDirs
265     }
266
267     compileClasspath = files( sourceSets.test.java.outputDir )
268
269     if (use_clover) {
270       compileClasspath += sourceSets.clover.compileClasspath
271     } else {
272       compileClasspath += files(sourceSets.main.java.outputDir)
273     }
274
275     compileClasspath += fileTree(dir: "$jalviewDir/$utilsDir", include: ["**/*.jar"])
276     compileClasspath += fileTree(dir: "$jalviewDir/$libDir", include: ["*.jar"])
277
278     runtimeClasspath = compileClasspath
279   }
280 }
281
282 // clover bits
283 dependencies {
284   if (use_clover) {
285     cloverCompile 'org.openclover:clover:4.3.1'
286     testCompile 'org.openclover:clover:4.3.1'
287   }
288 }
289
290 configurations {
291   cloverRuntime
292   cloverRuntime.extendsFrom cloverCompile
293 }
294
295 eclipse {
296   project {
297     name = "Jalview with gradle build"
298
299     natures 'org.eclipse.jdt.core.javanature',
300     'org.eclipse.jdt.groovy.core.groovyNature',
301     'org.eclipse.buildship.core.gradleprojectnature'
302
303     buildCommand 'org.eclipse.jdt.core.javabuilder'
304     buildCommand 'org.eclipse.buildship.core.gradleprojectbuilder'
305   }
306
307   classpath {
308     //defaultOutputDir = sourceSets.main.java.outputDir
309     def removeThese = []
310     configurations.each{ if (it.isCanBeResolved()) {
311       removeThese += it
312     }
313   }
314
315   minusConfigurations += removeThese
316   plusConfigurations = [ ]
317   file {
318
319     whenMerged { cp ->
320       def removeTheseToo = []
321       HashMap<String, Boolean> addedSrcPath = new HashMap<>();
322       cp.entries.each { entry ->
323         if (entry.kind == 'src') {
324           if (addedSrcPath.getAt(entry.path) || !(entry.path == "src" || entry.path == "test")) {
325             removeTheseToo += entry
326           } else {
327             addedSrcPath.putAt(entry.path, true)
328           }
329         }
330       }
331       cp.entries.removeAll(removeTheseToo)
332
333       print ("CP="+cp.inspect())
334
335       cp.entries += new Output("bin/main")
336       cp.entries += new Library(fileReference(helpParentDir))
337       cp.entries += new Library(fileReference(resourceDir))
338
339       HashMap<String, Boolean> addedLibPath = new HashMap<>();
340
341       // changing from sourcesets.main.classpath to specific Java version lib
342       //sourceSets.main.compileClasspath.each{
343       fileTree("$jalviewDir/$libDistDir").include("**/*.jar").include("*.jar").each {
344         //don't want to add outputDir as eclipse is using its own output dir in bin/main
345         if (it.isDirectory() || ! it.exists()) {
346           // don't add dirs to classpath
347           return
348         }
349         def itPath = it.toString()
350         if (itPath.startsWith(jalviewDirAbsolutePath+"/")) {
351           itPath = itPath.substring(jalviewDirAbsolutePath.length()+1)
352         }
353         if (addedLibPath.get(itPath)) {
354           //println("Not adding duplicate entry "+itPath)
355         } else {
356           //println("Adding entry "+itPath)
357           cp.entries += new Library(fileReference(itPath))
358           addedLibPath.put(itPath, true)
359         }
360       }
361
362       // changing from sourcesets.main.classpath to specific Java version lib
363       //sourceSets.test.compileClasspath.each{
364       fileTree(dir: "$jalviewDir/$utilsDir", include: ["**/*.jar"]).each {
365         //if ((it.isDirectory() || ! it.exists()) && ! (it.equals(sourceSets.main.java.outputDir))) {
366         //no longer want to add outputDir as eclipse is using its own output dir in bin/main
367         if (it.isDirectory() || ! it.exists()) {
368           // don't add dirs to classpath
369           return false // groovy "break" in .each loop
370         }
371         def itPath = it.toString()
372         if (itPath.startsWith(jalviewDirAbsolutePath+"/")) {
373           itPath = itPath.substring(jalviewDirAbsolutePath.length()+1)
374         }
375         if (addedLibPath.get(itPath)) {
376           // don't duplicate
377         } else {
378           def lib = new Library(fileReference(itPath))
379           // this doesn't work... yet.  Adding test=true attribute using withXml below
380           //def attrs = new Node(null, 'attributes', ["test":"true"])
381           //lib.appendNode(attrs) //
382           cp.entries += lib
383           addedLibPath.put(itPath, true)
384         }
385         }
386       }
387
388       // withXml changes ignored by buildship, these add the "test=true" attribute
389       withXml {
390         def node = it.asNode()
391
392         def srcTestAttributes
393         node.children().each{ cpe ->
394           def attributes = cpe.attributes()
395           if (attributes.get("kind") == "src" && attributes.get("path") == "test") {
396             srcTestAttributes = cpe.find { a -> a.name() == "attributes" }
397             return
398           }
399         }
400         def addTestAttribute = true
401         srcTestAttributes.each{a ->
402           if (a.name() == "attribute" && a.attributes().getAt("name") == "test") {
403             addTestAttribute = false
404           }
405         }
406         if (addTestAttribute) {
407           srcTestAttributes.append(new Node(null, "attribute", [name:"test", value:"true"]))
408         }
409
410         node.children().each{ cpe ->
411           def attributes = cpe.attributes()
412           if (attributes.get("kind") == "lib" && attributes.get("path").startsWith("utils/")) {
413             cpe.appendNode('attributes')
414             .appendNode('attribute', [name:"test", value:"true"])
415           }
416         }
417       } // withXML
418     } // file
419
420     containers 'org.eclipse.buildship.core.gradleclasspathcontainer'
421   } // classpath
422
423   jdt {
424     // for the IDE, use java 11 compatibility
425     sourceCompatibility = compile_source_compatibility
426     targetCompatibility = compile_target_compatibility
427     javaRuntimeName = eclipse_java_runtime_name
428
429     file {
430       withProperties { props ->
431         def jalview_prefs = new Properties()
432         def ins = new FileInputStream(jalviewDirAbsolutePath+"/"+eclipse_extra_jdt_prefs_file)
433         jalview_prefs.load(ins)
434         ins.close()
435         jalview_prefs.forEach { t, v ->
436           if (props.getAt(t) == null) {
437             props.putAt(t, v)
438           }
439         }
440       }
441     }
442   }
443
444   //synchronizationTasks eclipseClasspath
445   //autoBuildTasks eclipseClasspath
446 }
447
448 task cloverInstr() {
449   // only instrument source, we build test classes as normal
450   inputs.files files (sourceSets.main.allJava) // , fileTree(dir:"$jalviewDir/$testSourceDir", include: ["**/*.java"]))
451   outputs.dir cloverInstrDir
452
453   doFirst {
454     delete cloverInstrDir
455     def argsList = ["--initstring", "${buildDir}/clover/clover.db",
456     "-d", "${buildDir}/${cloverSourcesInstrDir}"]
457     argsList.addAll(inputs.files.files.collect({ file ->
458       file.absolutePath
459     }))
460     String[] args = argsList.toArray()
461     println("About to instrument "+args.length +" files")
462     com.atlassian.clover.CloverInstr.mainImpl(args)
463   }
464 }
465
466
467 task cloverReport {
468   group = "Verification"
469     description = "Createst the Clover report"
470     inputs.dir "${buildDir}/clover"
471     outputs.dir "${reportsDir}/clover"
472     onlyIf {
473       file("${buildDir}/clover/clover.db").exists()
474     }
475   doFirst {
476     def argsList = ["--initstring", "${buildDir}/clover/clover.db",
477     "-o", "${reportsDir}/clover"]
478     String[] args = argsList.toArray()
479     com.atlassian.clover.reporters.html.HtmlReporter.runReport(args)
480
481     // and generate ${reportsDir}/clover/clover.xml
482     args = ["--initstring", "${buildDir}/clover/clover.db",
483     "-o", "${reportsDir}/clover/clover.xml"].toArray()
484     com.atlassian.clover.reporters.xml.XMLReporter.runReport(args)
485   }
486 }
487
488 // end clover bits
489
490
491 compileJava {
492
493   doFirst {
494     sourceCompatibility = compile_source_compatibility
495     targetCompatibility = compile_target_compatibility
496     options.compilerArgs = additional_compiler_args
497     print ("Setting target compatibility to "+targetCompatibility+"\n")
498   }
499
500 }
501
502 compileTestJava {
503   if (use_clover) {
504     dependsOn compileCloverJava
505     classpath += configurations.cloverRuntime
506   } else {
507     classpath += sourceSets.main.runtimeClasspath
508   }
509   doFirst {
510     sourceCompatibility = compile_source_compatibility
511     targetCompatibility = compile_target_compatibility
512     options.compilerArgs = additional_compiler_args
513     print ("Setting target compatibility to "+targetCompatibility+"\n")
514   }
515 }
516
517
518 compileCloverJava {
519
520   doFirst {
521     sourceCompatibility = compile_source_compatibility
522     targetCompatibility = compile_target_compatibility
523     options.compilerArgs += additional_compiler_args
524     print ("Setting target compatibility to "+targetCompatibility+"\n")
525   }
526   classpath += configurations.cloverRuntime
527 }
528
529 clean {
530   delete sourceSets.main.java.outputDir
531 }
532
533 cleanTest {
534   delete sourceSets.test.java.outputDir
535   delete cloverInstrDir
536 }
537
538 // format is a string like date.format("dd MMMM yyyy")
539 def getDate(format) {
540   def date = new Date()
541   return date.format(format)
542 }
543
544 task setGitVals {
545   def hashStdOut = new ByteArrayOutputStream()
546   exec {
547     commandLine "git", "rev-parse", "--short", "HEAD"
548     standardOutput = hashStdOut
549     ignoreExitValue true
550   }
551
552   def branchStdOut = new ByteArrayOutputStream()
553   exec {
554     commandLine "git", "rev-parse", "--abbrev-ref", "HEAD"
555     standardOutput = branchStdOut
556     ignoreExitValue true
557   }
558
559   project.ext.gitHash = hashStdOut.toString().trim()
560   project.ext.gitBranch = branchStdOut.toString().trim()
561
562   outputs.upToDateWhen { false }
563 }
564
565 task createBuildProperties(type: WriteProperties) {
566   dependsOn setGitVals
567   inputs.dir("$jalviewDir/$sourceDir")
568   inputs.dir("$classes")
569   inputs.dir("$jalviewDir/$resourceDir")
570   outputFile (buildProperties)
571   // taking time specific comment out to allow better incremental builds
572   comment "--Jalview Build Details--\n"+getDate("yyyy-MM-dd HH:mm:ss")
573   //comment "--Jalview Build Details--\n"+getDate("yyyy-MM-dd")
574   property "BUILD_DATE", getDate("HH:mm:ss dd MMMM yyyy")
575   property "VERSION", JALVIEW_VERSION
576   property "INSTALLATION", INSTALLATION+" git-commit:"+project.ext.gitHash+" ["+project.ext.gitBranch+"]"
577   outputs.file(outputFile)
578 }
579
580 def buildingHTML = "$jalviewDir/$docDir/building.html"
581 task deleteBuildingHTML(type: Delete) {
582   delete buildingHTML
583 }
584
585 task convertBuildingMD(type: Exec) {
586   dependsOn deleteBuildingHTML
587   def buildingMD = "$jalviewDir/$docDir/building.md"
588   def css = "$jalviewDir/$docDir/github.css"
589
590   def pandoc = null
591   pandoc_exec.split(",").each {
592     if (file(it.trim()).exists()) {
593       pandoc = it.trim()
594       return true
595     }
596   }
597
598   def hostname = "hostname".execute().text.trim()
599   if ((pandoc == null || ! file(pandoc).exists()) && hostname.equals("jv-bamboo")) {
600     pandoc = System.getProperty("user.home")+"/buildtools/pandoc/bin/pandoc"
601   }
602
603   doFirst {
604     if (pandoc != null && file(pandoc).exists()) {
605         commandLine pandoc, '-s', '-o', buildingHTML, '--metadata', 'pagetitle="Building Jalview from Source"', '--toc', '-H', css, buildingMD
606     } else {
607         println("Cannot find pandoc. Skipping convert building.md to HTML")
608         throw new StopExecutionException()
609     }
610   }
611
612   ignoreExitValue true
613
614   inputs.file(buildingMD)
615   inputs.file(css)
616   outputs.file(buildingHTML)
617 }
618 clean {
619   delete buildingHTML
620 }
621
622 task syncDocs(type: Sync) {
623   dependsOn convertBuildingMD
624   def syncDir = "$classes/$docDir"
625   from fileTree("$jalviewDir/$docDir")
626   into syncDir
627
628 }
629
630 def helpFile = "$classes/$helpDir/help.jhm"
631
632 task copyHelp(type: Copy) {
633   def inputDir = "$jalviewDir/$helpParentDir/$helpDir"
634   def outputDir = "$classes/$helpDir"
635   from(inputDir) {
636     exclude '**/*.gif'
637       exclude '**/*.jpg'
638       exclude '**/*.png'
639       filter(ReplaceTokens, beginToken: '$$', endToken: '$$', tokens: ['Version-Rel': JALVIEW_VERSION])
640   }
641   from(inputDir) {
642     include '**/*.gif'
643       include '**/*.jpg'
644       include '**/*.png'
645   }
646   into outputDir
647
648   inputs.dir(inputDir)
649   outputs.files(helpFile)
650   outputs.dir(outputDir)
651 }
652
653 task syncLib(type: Sync) {
654   def syncDir = "$classes/$libDistDir"
655   from fileTree("$jalviewDir/$libDistDir")
656   into syncDir
657 }
658
659 task syncResources(type: Sync) {
660   from "$jalviewDir/$resourceDir"
661   include "**/*.*"
662   exclude "install4j"
663   into "$classes"
664   preserve {
665     include "**"
666   }
667 }
668
669 task prepare {
670   dependsOn syncResources
671   dependsOn syncDocs
672   dependsOn copyHelp
673 }
674
675
676 //testReportDirName = "test-reports" // note that test workingDir will be $jalviewDir
677 test {
678   dependsOn prepare
679   dependsOn compileJava
680   if (use_clover) {
681     dependsOn cloverInstr
682   }
683
684   if (use_clover) {
685     print("Running tests " + (use_clover?"WITH":"WITHOUT") + " clover [clover="+use_clover+"]\n")
686   }
687
688   useTestNG() {
689     includeGroups testngGroups
690     preserveOrder true
691     useDefaultListeners=true
692   }
693
694   workingDir = jalviewDir
695   //systemProperties 'clover.jar' System.properties.clover.jar
696   sourceCompatibility = compile_source_compatibility
697   targetCompatibility = compile_target_compatibility
698   jvmArgs += additional_compiler_args
699   print ("Setting target compatibility to "+targetCompatibility+"\n")
700 }
701
702 task buildIndices(type: JavaExec) {
703   dependsOn copyHelp
704   classpath = sourceSets.main.compileClasspath
705   main = "com.sun.java.help.search.Indexer"
706   workingDir = "$classes/$helpDir"
707   def argDir = "html"
708   args = [ argDir ]
709   inputs.dir("$workingDir/$argDir")
710
711   outputs.dir("$classes/doc")
712   outputs.dir("$classes/help")
713   outputs.file("$workingDir/JavaHelpSearch/DOCS")
714   outputs.file("$workingDir/JavaHelpSearch/DOCS.TAB")
715   outputs.file("$workingDir/JavaHelpSearch/OFFSETS")
716   outputs.file("$workingDir/JavaHelpSearch/POSITIONS")
717   outputs.file("$workingDir/JavaHelpSearch/SCHEMA")
718   outputs.file("$workingDir/JavaHelpSearch/TMAP")
719 }
720
721 task compileLinkCheck(type: JavaCompile) {
722   options.fork = true
723   classpath = files("$jalviewDir/$utilsDir")
724   destinationDir = file("$jalviewDir/$utilsDir")
725   source = fileTree(dir: "$jalviewDir/$utilsDir", include: ["HelpLinksChecker.java", "BufferedLineReader.java"])
726
727   inputs.file("$jalviewDir/$utilsDir/HelpLinksChecker.java")
728   inputs.file("$jalviewDir/$utilsDir/HelpLinksChecker.java")
729   outputs.file("$jalviewDir/$utilsDir/HelpLinksChecker.class")
730   outputs.file("$jalviewDir/$utilsDir/BufferedLineReader.class")
731 }
732
733 def helplinkscheckertouchfile = file("$jalviewDir/$utilsDir/HelpLinksChecker.touch")
734 task linkCheck(type: JavaExec) {
735   dependsOn prepare, compileLinkCheck
736   classpath = files("$jalviewDir/$utilsDir")
737   main = "HelpLinksChecker"
738   workingDir = jalviewDir
739   def help = "$classes/$helpDir"
740   args = [ "$classes/$helpDir", "-nointernet" ]
741
742   doLast {
743     helplinkscheckertouchfile.createNewFile()
744   }
745
746   inputs.dir("$classes/$helpDir")
747   outputs.file(helplinkscheckertouchfile)
748 }
749
750 // import the pubhtmlhelp target
751 ant.properties.basedir = "$jalviewDir"
752 ant.properties.helpBuildDir = jalviewDirAbsolutePath+"/$classes/$helpDir"
753 ant.importBuild "$utilsDir/publishHelp.xml"
754
755
756 task cleanPackageDir(type: Delete) {
757   delete fileTree("$jalviewDir/$packageDir").include("*.jar")
758 }
759
760 jar {
761   dependsOn linkCheck
762   dependsOn buildIndices
763   dependsOn createBuildProperties
764
765   manifest {
766     attributes "Main-Class": mainClass,
767     "Permissions": "all-permissions",
768     "Application-Name": "Jalview Desktop",
769     "Codebase": application_codebase
770   }
771
772   destinationDir = file("$jalviewDir/$packageDir")
773   archiveName = rootProject.name+".jar"
774
775   exclude "cache*/**"
776   exclude "*.jar"
777   exclude "*.jar.*"
778   exclude "**/*.jar"
779   exclude "**/*.jar.*"
780
781   inputs.dir("$classes")
782   outputs.file("$jalviewDir/$packageDir/$archiveName")
783 }
784
785 task copyJars(type: Copy) {
786   from fileTree("$classes").include("**/*.jar").include("*.jar").files
787   into "$jalviewDir/$packageDir"
788 }
789
790 // doing a Sync instead of Copy as Copy doesn't deal with "outputs" very well
791 task syncJars(type: Sync) {
792   from fileTree("$jalviewDir/$libDistDir").include("**/*.jar").include("*.jar").files
793   into "$jalviewDir/$packageDir"
794   preserve {
795     include jar.archiveName
796   }
797 }
798
799 task makeDist {
800   group = "build"
801   description = "Put all required libraries in dist"
802   // order of "cleanPackageDir", "copyJars", "jar" important!
803   jar.mustRunAfter cleanPackageDir
804   syncJars.mustRunAfter cleanPackageDir
805   dependsOn cleanPackageDir
806   dependsOn syncJars
807   dependsOn jar
808   outputs.dir("$jalviewDir/$packageDir")
809 }
810
811 task cleanDist {
812   dependsOn cleanPackageDir
813   dependsOn cleanTest
814   dependsOn clean
815 }
816
817 shadowJar {
818   group = "distribution"
819   if (buildDist) {
820     dependsOn makeDist
821   }
822   from ("$jalviewDir/$libDistDir") {
823     include("*.jar")
824   }
825   manifest {
826     attributes 'Implementation-Version': JALVIEW_VERSION
827   }
828   mainClassName = shadowJarMainClass
829   mergeServiceFiles()
830   classifier = "all-"+JALVIEW_VERSION+"-j"+JAVA_VERSION
831   minimize()
832 }
833
834 task getdownWebsite() {
835   group = "distribution"
836   description = "Create the getdown minimal app folder, and website folder for this version of jalview. Website folder also used for offline app installer"
837   if (buildDist) {
838     dependsOn makeDist
839   }
840
841         // clean the getdown website and files dir before creating getdown folders
842         delete project.ext.getdownWebsiteDir
843         delete project.ext.getdownFilesDir
844
845   def getdownWebsiteResourceFilenames = []
846   def getdownTextString = ""
847   def getdownResourceDir = project.ext.getdownResourceDir
848   def getdownAppDir = project.ext.getdownAppDir
849   def getdownResourceFilenames = []
850
851   doFirst {
852     copy {
853       from buildProperties
854       rename(buildPropertiesFile, getdown_build_properties)
855       into project.ext.getdownAppDir
856     }
857     getdownWebsiteResourceFilenames += getdown_app_dir+"/"+getdown_build_properties
858
859     // go through properties looking for getdown_txt_...
860     def props = project.properties.sort { it.key }
861         if (getdown_alt_java_min_version.length() > 0) {
862                 props.put("getdown_txt_java_min_version", getdown_alt_java_min_version)
863         }
864         if (getdown_alt_java_max_version.length() > 0) {
865                 props.put("getdown_txt_java_max_version", getdown_alt_java_max_version)
866         }
867         props.put("getdown_txt_multi_java_location", getdown_alt_multi_java_location)
868
869     props.put("getdown_txt_appbase", getdown_app_base)
870     props.each{ prop, val ->
871       if (prop.startsWith("getdown_txt_") && val != null) {
872         if (prop.startsWith("getdown_txt_multi_")) {
873           def key = prop.substring(18)
874           val.split(",").each{ v ->
875             def line = key + " = " + v + "\n"
876             getdownTextString += line
877           }
878         } else {
879           // file values rationalised
880           if (val.indexOf('/') > -1 || prop.startsWith("getdown_txt_resource")) {
881             def r = null
882             if (val.indexOf('/') == 0) {
883               // absolute path
884               r = file(val)
885             } else if (val.indexOf('/') > 0) {
886               // relative path (relative to jalviewDir)
887               r = file( jalviewDir + '/' + val )
888             }
889             if (r.exists()) {
890               val = getdown_resource_dir + '/' + r.getName()
891               getdownWebsiteResourceFilenames += val
892               getdownResourceFilenames += r.getPath()
893             }
894           }
895           if (! prop.startsWith("getdown_txt_resource")) {
896             def line = prop.substring(12) + " = " + val + "\n"
897             getdownTextString += line
898           }
899         }
900       }
901     }
902
903     getdownWebsiteResourceFilenames.each{ filename ->
904       getdownTextString += "resource = "+filename+"\n"
905     }
906     getdownResourceFilenames.each{ filename ->
907       copy {
908         from filename
909         into project.ext.getdownResourceDir
910       }
911     }
912
913     def codeFiles = []
914     fileTree(file(packageDir)).each{ f ->
915       if (f.isDirectory()) {
916         def files = fileTree(dir: f, include: ["*"]).getFiles()
917         codeFiles += files
918       } else if (f.exists()) {
919         codeFiles += f
920       }
921     }
922     codeFiles.sort().each{f ->
923       def line = "code = " + getdown_app_dir + '/' + f.getName() + "\n"
924       getdownTextString += line
925       copy {
926         from f.getPath()
927         into project.ext.getdownAppDir
928       }
929     }
930
931     // NOT USING MODULES YET, EVERYTHING SHOULD BE IN dist
932     /*
933     if (JAVA_VERSION.equals("11")) {
934     def j11libFiles = fileTree(dir: "$jalviewDir/$j11libDir", include: ["*.jar"]).getFiles()
935     j11libFiles.sort().each{f ->
936     def line = "code = " + getdown_j11lib_dir + '/' + f.getName() + "\n"
937     getdownTextString += line
938     copy {
939     from f.getPath()
940     into project.ext.getdownJ11libDir
941     }
942     }
943     }
944      */
945
946     // 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.
947     //getdownTextString += "class = " + file(getdownLauncher).getName() + "\n"
948     getdownTextString += "resource = " + getdown_launcher_new + "\n"
949     getdownTextString += "class = " + mainClass + "\n"
950
951     def getdown_txt = file(project.ext.getdownWebsiteDir + "/getdown.txt")
952     getdown_txt.write(getdownTextString)
953
954     def launch_jvl = file(project.ext.getdownWebsiteDir + "/" + getdown_launch_jvl)
955     launch_jvl.write("appbase="+props.get("getdown_txt_appbase"))
956
957     copy {
958       from getdownLauncher
959       rename(file(getdownLauncher).getName(), getdown_launcher_new)
960       into project.ext.getdownWebsiteDir
961     }
962
963     copy {
964       from getdownLauncher
965       into project.ext.getdownWebsiteDir
966     }
967
968     if (! (CHANNEL.startsWith("ARCHIVE") || CHANNEL.startsWith("DEVELOP"))) {
969       copy {
970         from getdown_txt
971         from getdownLauncher
972         from getdownWebsiteDir+"/"+getdown_build_properties
973         into getdownInstallDir
974       }
975
976       copy {
977         from getdownInstallDir
978         into getdownFilesInstallDir
979       }
980     }
981
982     copy {
983       from getdown_txt
984       from launch_jvl
985       from getdownLauncher
986       from getdownWebsiteDir+"/"+getdown_build_properties
987       into getdownFilesDir
988     }
989
990     copy {
991           from getdownResourceDir
992       into project.ext.getdownFilesDir + '/' + getdown_resource_dir
993     }
994   }
995
996   if (buildDist) {
997     inputs.dir(jalviewDir + '/' + packageDir)
998   }
999   outputs.dir(project.ext.getdownWebsiteDir)
1000   outputs.dir(project.ext.getdownFilesDir)
1001 }
1002
1003 task getdownDigest(type: JavaExec) {
1004   group = "distribution"
1005   description = "Digest the getdown website folder"
1006   dependsOn getdownWebsite
1007   classpath = files(jalviewDir + '/' + getdown_core, jalviewDir+'/'+getdown_launcher)
1008   main = "com.threerings.getdown.tools.Digester"
1009   args project.ext.getdownWebsiteDir
1010   inputs.dir(project.ext.getdownWebsiteDir)
1011   outputs.file(project.ext.getdownWebsiteDir + '/' + "digest2.txt")
1012 }
1013
1014 task getdown() {
1015   group = "distribution"
1016   description = "Create the minimal and full getdown app folder for installers and website and create digest file"
1017   dependsOn getdownDigest
1018   doLast {
1019     if (reportRsyncCommand) {
1020       def fromDir = getdownWebsiteDir + (getdownWebsiteDir.endsWith("/")?"":"/")
1021       def toDir = getdown_rsync_dest + "/" + getdownDir + (getdownDir.endsWith("/")?"":"/")
1022       println "LIKELY RSYNC COMMAND:"
1023       println "mkdir -p '$toDir'\nrsync -avh --delete '$fromDir' '$toDir'"
1024       if (RUNRSYNC == "true") {
1025         exec {
1026           commandLine "mkdir", "-p", toDir
1027         }
1028         exec {
1029           commandLine "rsync", "-avh", "--delete", fromDir, toDir
1030         }
1031       }
1032     }
1033   }
1034 }
1035
1036 clean {
1037   delete project.ext.getdownWebsiteDir
1038   delete project.ext.getdownFilesDir
1039 }
1040
1041 install4j {
1042   def install4jHomeDir = "/opt/install4j"
1043   def hostname = "hostname".execute().text.trim()
1044   if (hostname.equals("jv-bamboo")) {
1045     install4jHomeDir = System.getProperty("user.home")+"/buildtools/install4j"
1046   } else if (OperatingSystem.current().isMacOsX()) {
1047     install4jHomeDir = '/Applications/install4j.app/Contents/Resources/app'
1048     if (! file(install4jHomeDir).exists()) {
1049       install4jHomeDir = System.getProperty("user.home")+install4jHomeDir
1050     }
1051   } else if (OperatingSystem.current().isLinux()) {
1052     install4jHomeDir = System.getProperty("user.home")+"/buildtools/install4j"
1053   }
1054   installDir = file(install4jHomeDir)
1055   mediaTypes = Arrays.asList(install4jMediaTypes.split(","))
1056   if (install4jFaster.equals("true")) {
1057     faster = true
1058   }
1059 }
1060
1061 def install4jConf
1062 def macosJavaVMDir
1063 def macosJavaVMTgz
1064 def windowsJavaVMDir
1065 def windowsJavaVMTgz
1066 def install4jDir = "$jalviewDir/$install4jResourceDir"
1067 def install4jConfFile = "jalview-installers-java"+JAVA_VERSION+".install4j"
1068 install4jConf = "$install4jDir/$install4jConfFile"
1069
1070 task copyInstall4jTemplate(type: Copy) {
1071   macosJavaVMDir = System.env.HOME+"/buildtools/jre/openjdk-java_vm/getdown/macos-jre"+JAVA_VERSION+"/jre"
1072   macosJavaVMTgz = System.env.HOME+"/buildtools/jre/openjdk-java_vm/install4j/tgz/macos-jre"+JAVA_VERSION+".tar.gz"
1073   windowsJavaVMDir = System.env.HOME+"/buildtools/jre/openjdk-java_vm/getdown/windows-jre"+JAVA_VERSION+"/jre"
1074   windowsJavaVMTgz = System.env.HOME+"/buildtools/jre/openjdk-java_vm/install4j/tgz/windows-jre"+JAVA_VERSION+".tar.gz"
1075   from (install4jDir) {
1076     include install4jTemplate
1077     rename (install4jTemplate, install4jConfFile)
1078     filter(ReplaceTokens, beginToken: '', endToken: '', tokens: ['9999999999': JAVA_VERSION])
1079     filter(ReplaceTokens, beginToken: '$$', endToken: '$$',
1080     tokens: [
1081     'JAVA_VERSION': JAVA_VERSION,
1082     'JAVA_INTEGER_VERSION': JAVA_INTEGER_VERSION,
1083     'VERSION': JALVIEW_VERSION,
1084     'MACOS_JAVA_VM_DIR': macosJavaVMDir,
1085     'MACOS_JAVA_VM_TGZ': macosJavaVMTgz,
1086     'WINDOWS_JAVA_VM_DIR': windowsJavaVMDir,
1087     'WINDOWS_JAVA_VM_TGZ': windowsJavaVMTgz,
1088     'INSTALL4JINFOPLISTFILEASSOCIATIONS': install4jInfoPlistFileAssociations,
1089     'COPYRIGHT_MESSAGE': install4jCopyrightMessage,
1090     'MACOS_BUNDLE_ID': install4jMacOSBundleId,
1091     'GETDOWN_RESOURCE_DIR': getdown_resource_dir,
1092     'GETDOWN_DIST_DIR': getdown_app_dir,
1093     'GETDOWN_ALT_DIR': getdown_app_dir_alt,
1094     'GETDOWN_INSTALL_DIR': getdown_install_dir
1095     ]
1096     )
1097     if (OSX_KEYPASS=="") {
1098       filter(ReplaceTokens, beginToken: 'codeSigning macEnabled="', endToken: '"', tokens: ['true':'codeSigning macEnabled="false"'])
1099       filter(ReplaceTokens, beginToken: 'runPostProcessor="true" ',endToken: 'Processor', tokens: ['post':'runPostProcessor="false" postProcessor'])
1100     }
1101   }
1102   into install4jDir
1103   outputs.files(install4jConf)
1104
1105   doLast {
1106     // include file associations in installer
1107     def installerFileAssociationsXml = file("$install4jDir/$install4jInstallerFileAssociations").text
1108     ant.replaceregexp(
1109       byline: false,
1110       flags: "s",
1111       match: '<action name="EXTENSIONS_REPLACED_BY_GRADLE".*?</action>',
1112       replace: installerFileAssociationsXml,
1113       file: install4jConf
1114     )
1115     /*
1116     // include uninstaller applescript app files in dmg
1117     def installerDMGUninstallerXml = file("$install4jDir/$install4jDMGUninstallerAppFiles").text
1118     ant.replaceregexp(
1119     byline: false,
1120     flags: "s",
1121     match: '<file name="UNINSTALL_OLD_JALVIEW_APP_REPLACED_IN_GRADLE" file=.*?>',
1122     replace: installerDMGUninstallerXml,
1123     file: install4jConf
1124     )
1125      */
1126   }
1127 }
1128
1129 task installers(type: com.install4j.gradle.Install4jTask) {
1130   group = "distribution"
1131   description = "Create the install4j installers"
1132   dependsOn getdown
1133   dependsOn copyInstall4jTemplate
1134   projectFile = file(install4jConf)
1135   println("Using projectFile "+projectFile)
1136   variables = [majorVersion: version.substring(2, 11), build: 001, OSX_KEYSTORE: OSX_KEYSTORE, JSIGN_SH: JSIGN_SH]
1137   destination = "$jalviewDir/$install4jBuildDir/$JAVA_VERSION"
1138   buildSelected = true
1139
1140   if (OSX_KEYPASS) {
1141     macKeystorePassword=OSX_KEYPASS
1142
1143   }
1144
1145   inputs.dir(project.ext.getdownWebsiteDir)
1146   inputs.file(install4jConf)
1147   inputs.dir(macosJavaVMDir)
1148   inputs.dir(windowsJavaVMDir)
1149   outputs.dir("$jalviewDir/$install4jBuildDir/$JAVA_VERSION")
1150
1151 }
1152
1153 clean {
1154   delete install4jConf
1155 }
1156
1157 task sourceDist (type: Tar) {
1158   
1159   def VERSION_UNDERSCORES = JALVIEW_VERSION.replaceAll("\\.", "_")
1160   archiveFileName = project.name + "_" + VERSION_UNDERSCORES + ".tar.gz"
1161   
1162   compression Compression.GZIP
1163   
1164   from jalviewDir
1165   into project.name
1166  
1167    
1168   exclude (".*")
1169   exclude ("**/.*")
1170   exclude ("*.class")
1171   exclude ("**/*.class")
1172   include (eclipse_extra_jdt_prefs_file)
1173   include ("AUTHORS")
1174   include ("CITATION")
1175   include ("FEATURETODO")
1176   include ("JAVA-11-README")
1177   include ("FEATURETODO")
1178   include ("LICENSE")
1179   include ("README")
1180   include ("RELEASE")
1181   include ("THIRDPARTYLIBS")
1182   include ("build.gradle")
1183   include ("gradle.properties")
1184   include ("$sourceDir/*.java")
1185   include ("$sourceDir/**/*.java")
1186   include ("$sourceDir/**/*.cdr")
1187   include ("$j8libDir/**/*.jar")
1188   include ("$j11libDir/**/*.jar")
1189   include ("$resourceDir/**/*")
1190   include ("$helpDir/**/*")
1191   include ("$schemaDir/**/*")
1192   include ("$utilsDir/**/*")
1193   include ("$docDir/**/*")
1194   include ("$examplesDir/**/*")
1195   include ("getdown/**/*")
1196   //include ("jalview-jalopy.xml")
1197   //include ("JalviewApplet.jpx")
1198   //include ("JalviewX.jpx")
1199   //include ("nbbuild.xml")
1200   //include ("nbproject/genfiles.properties")
1201   //include ("nbproject/project.properties")
1202   //include ("nbproject/project.xml")
1203   
1204   exclude ("appletlib")
1205   exclude ("**/*locales")
1206   exclude ("*locales/**")
1207   exclude ("utils/InstallAnywhere")
1208   exclude (libDir)
1209   exclude (getdown_files_dir)
1210   exclude (getdown_website_dir)
1211
1212   // exluding these as not using jars as modules yet
1213   exclude ("$j11modDir/**/*.jar")
1214
1215 }
1216
1217 task helppages  {
1218   dependsOn copyHelp
1219   dependsOn pubhtmlhelp
1220   
1221   inputs.dir("$classes/$helpDir")
1222   outputs.file("build/distribution/help/helpTOC.html")
1223 }