JAL-3210 Better tar file name
[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.*
4 import groovy.transform.ExternalizeMethods
5 //import org.eclipse.osgi.*
6 import com.diffplug.gradle.GoomphCacheLocations
7
8 /*
9 buildscript {
10   repositories {
11     repos
12     mavenCentral()
13     jcenter()
14   }
15   dependencies {
16     //eclipseDeps.each { compile "p2:${it}:+" }
17     //classpath 'org.eclipse.platform:org.eclipse.osgi:3.15.0'
18     //compile group: 'org.eclipse.platform', name: 'org.eclipse.osgi', version: '3.15.0'
19     //classpath 'biz.aQute.bnd:biz.aQute.bnd.gradle:4.4.0'
20   }
21 }
22 */
23
24 plugins {
25   id 'java'
26   id 'application'
27   id 'eclipse'
28   id 'com.diffplug.gradle.oomph.ide' version '3.18.1'
29   id 'com.diffplug.gradle.equinoxlaunch' version '3.18.1'
30
31   //id 'com.diffplug.gradle.p2.asmaven' version '3.18.1'
32
33   //id 'org.eclipse.osgi' version '3.15.0'
34   //id 'osgi'
35 }
36
37
38 /*
39 def eclipseDeps = [
40     // The dependencies we actually use
41     'org.eclipse.jdt.core',
42     'org.eclipse.text',
43
44     // Their transitives
45     'org.eclipse.core.contenttype',
46     'org.eclipse.core.jobs',
47     'org.eclipse.core.runtime',
48     'org.eclipse.core.resources',
49     'org.eclipse.equinox.common',
50     'org.eclipse.equinox.preferences',
51     //'org.eclipse.osgi'
52 ]
53 */
54
55 /*
56 p2AsMaven {
57   group 'p2', {
58     repoEclipse goomph_eclipse_version
59     eclipseDeps.each { p2.addIU(it) }
60     eclipseDeps.each { p2.addIU(it + '.source') }
61   }
62 }
63 */
64
65
66 /*
67 dependencies {
68   //eclipseDeps.each { compile "p2:${it}:+" }
69   //implementation 'org.eclipse.platform:org.eclipse.osgi:3.15.0'
70   //compile 'org.eclipse.platform:org.eclipse.osgi:3.15.0'
71   //classpath 'biz.aQute.bnd:biz.aQute.bnd.gradle:4.4.0'
72 }
73 */
74
75
76
77 repositories {
78   jcenter()
79   mavenCentral()
80   flatDir {
81     dirs gradlePluginsDir
82   }
83 }
84
85 mainClassName = launcherClass
86 def classes = "$jalviewDir/$classesDir"
87
88 // configure classpath/args for j8/j11 compilation
89
90 def jalviewDirAbsolutePath = file(jalviewDir).getAbsolutePath()
91 def libDir
92 def libDistDir
93 def compile_source_compatibility
94 def compile_target_compatibility
95
96 ext {
97   buildProperties = jalviewDir + "/" + classesDir +"/" + buildPropertiesFile
98
99   gitHash = ""
100   gitBranch = ""
101
102   jalviewjsServer = ""
103 }
104
105 def JAVA_INTEGER_VERSION
106 //def additional_compiler_args = []
107 // this property is for the Java library used in eclipse
108 def eclipse_java_runtime_name
109 if (JAVA_VERSION.equals("1.8")) {
110   JAVA_INTEGER_VERSION = "8"
111   //libDir = j8libDir
112   libDir = j11libDir
113   libDistDir = j8libDir
114   compile_source_compatibility = 1.8
115   compile_target_compatibility = 1.8
116   eclipse_java_runtime_name = "JavaSE-1.8"
117 } else if (JAVA_VERSION.equals("11")) {
118   JAVA_INTEGER_VERSION = "11"
119   libDir = j11libDir
120   libDistDir = j11libDir
121   compile_source_compatibility = 11
122   compile_target_compatibility = 11
123   eclipse_java_runtime_name = "JavaSE-11"
124   /* compile without modules -- using classpath libraries
125   additional_compiler_args += [
126   '--module-path', ext.modules_compileClasspath.asPath,
127   '--add-modules', j11modules
128   ]
129   */
130 } else if (JAVA_VERSION.equals("12") || JAVA_VERSION.equals("13")) {
131   JAVA_INTEGER_VERSION = JAVA_VERSION
132   libDir = j11libDir
133   libDistDir = j11libDir
134   compile_source_compatibility = JAVA_VERSION
135   compile_target_compatibility = JAVA_VERSION
136   eclipse_java_runtime_name = "JavaSE-11"
137   /* compile without modules -- using classpath libraries
138   additional_compiler_args += [
139   '--module-path', ext.modules_compileClasspath.asPath,
140   '--add-modules', j11modules
141   ]
142   */
143 } else {
144   throw new GradleException("JAVA_VERSION=$JAVA_VERSION not currently supported by Jalview")
145 }
146
147 sourceSets {
148
149   main {
150     java {
151       srcDirs "$jalviewDir/$sourceDir"
152       outputDir = file("$classes")
153     }
154
155     resources {
156       srcDirs "$jalviewDir/$resourceDir"
157     }
158
159     compileClasspath = files(sourceSets.main.java.outputDir)
160     compileClasspath += fileTree(dir: "$jalviewDir/$libDir", include: ["*.jar"])
161
162     runtimeClasspath = compileClasspath
163   }
164
165 }
166
167 eclipse {
168   project {
169     name = eclipse_project_name
170
171     natures 'org.eclipse.jdt.core.javanature',
172     'org.eclipse.buildship.core.gradleprojectnature'
173
174     buildCommand 'org.eclipse.jdt.core.javabuilder'
175     buildCommand 'org.eclipse.buildship.core.gradleprojectbuilder'
176   }
177
178   classpath {
179     //defaultOutputDir = sourceSets.main.java.outputDir
180     def removeThese = []
181     configurations.each{ if (it.isCanBeResolved()) {
182         removeThese += it
183       }
184     }
185
186     minusConfigurations += removeThese
187     plusConfigurations = [ ]
188     file {
189
190       whenMerged { cp ->
191         def removeTheseToo = []
192         HashMap<String, Boolean> addedSrcPath = new HashMap<>();
193         cp.entries.each { entry ->
194           if (entry.kind == 'src') {
195             if (addedSrcPath.getAt(entry.path) || !(entry.path == "src" || entry.path == "test")) {
196               removeTheseToo += entry
197             } else {
198               addedSrcPath.putAt(entry.path, true)
199             }
200           }
201         }
202         cp.entries.removeAll(removeTheseToo)
203
204         if (file(eclipse_bin_dir+"/main").isDirectory()) {
205                 cp.entries += new Output(eclipse_bin_dir+"/main")
206         }
207         if (file(helpParentDir).isDirectory()) {
208                 cp.entries += new Library(fileReference(helpParentDir))
209         }
210         if (file(resourceDir).isDirectory()) {
211                 cp.entries += new Library(fileReference(resourceDir))
212         }
213
214         HashMap<String, Boolean> addedLibPath = new HashMap<>();
215
216         // changing from sourcesets.main.classpath to specific Java version lib
217         //sourceSets.main.compileClasspath.each{
218         fileTree("$jalviewDir/$libDistDir").include("**/*.jar").include("*.jar").each {
219           //don't want to add outputDir as eclipse is using its own output dir in bin/main
220           if (it.isDirectory() || ! it.exists()) {
221             // don't add dirs to classpath
222             return
223           }
224           def itPath = it.toString()
225           if (itPath.startsWith(jalviewDirAbsolutePath+"/")) {
226             itPath = itPath.substring(jalviewDirAbsolutePath.length()+1)
227           }
228           if (addedLibPath.get(itPath)) {
229             //println("Not adding duplicate entry "+itPath)
230           } else {
231             //println("Adding entry "+itPath)
232             cp.entries += new Library(fileReference(itPath))
233             addedLibPath.put(itPath, true)
234           }
235         }
236       } // whenMerged
237
238     } // file
239
240     containers 'org.eclipse.buildship.core.gradleclasspathcontainer'
241   } // classpath
242
243   jdt {
244     // for the IDE, use java 11 compatibility
245     sourceCompatibility = compile_source_compatibility
246     targetCompatibility = compile_target_compatibility
247     javaRuntimeName = eclipse_java_runtime_name
248
249     /*
250     file {
251     withProperties { props ->
252     def jalview_prefs = new Properties()
253     def ins = new FileInputStream(jalviewDirAbsolutePath+"/"+eclipse_extra_jdt_prefs_file)
254     jalview_prefs.load(ins)
255     ins.close()
256     jalview_prefs.forEach { t, v ->
257     if (props.getAt(t) == null) {
258     props.putAt(t, v)
259     }
260     }
261     }
262     }
263      */
264   } // jdt
265
266   //synchronizationTasks eclipseClasspath
267   //autoBuildTasks eclipseClasspath
268 } // eclipse
269
270 /*
271 compileJava {
272
273   doFirst {
274     sourceCompatibility = compile_source_compatibility
275     targetCompatibility = compile_target_compatibility
276     //options.compilerArgs = additional_compiler_args
277     print ("Setting target compatibility to "+targetCompatibility+"\n")
278   }
279
280 }
281
282 clean {
283   delete sourceSets.main.java.outputDir
284 }
285 */
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310 GoomphCacheLocations.override_workspaces = file(jalviewDirAbsolutePath+"/"+goomph_workspace)
311 oomphIde {
312   repoEclipse goomph_eclipse_version
313   jdt {
314     /*
315     installedJre {
316       //markDefault = true
317       //executionEnvironments = [ eclipse.jdt.javaRuntimeName ]
318     }
319     */
320     //compilerComplianceLevel( JAVA_INTEGER_VERSION )
321   }
322   //repo 'http://download.eclipse.org/buildship/updates/e45/milestones/3.x/'
323   repo goomph_repo_buildship
324         feature goomph_feature_buildship
325 }
326
327 equinoxLaunch {
328   headlessAppSetup {
329
330     launchTask 'ideJalviewjsBuild', {
331       //it.args = ["-nosplash", "--launcher.suppressErrors", "-application", "org.eclipse.jdt.apt.core.aptBuild", "-data", tempEclipseWorkspace, "-"+jalviewjs_eclipseBuildArg, eclipse_project_name ]
332       it.args = ["-nosplash", "--launcher.suppressErrors", "-application", "org.eclipse.jdt.apt.core.aptBuild", "-"+jalviewjs_eclipseBuildArg, eclipse_project_name ]
333     }
334   }
335 }
336
337 task ideCopyDropins (type: Copy) {
338   dependsOn ideSetupP2
339
340   def inputFiles = fileTree(jalviewjs_utils_dir+"/"+jalviewjs_eclipse_dropins_dir)
341   def outputDir = oomphIde.ideDir + "/" + com.diffplug.gradle.FileMisc.macContentsEclipse() + "/dropins"
342
343   from inputFiles
344   into outputDir
345   def outputFiles = []
346   rename { filename ->
347     outputFiles += outputDir+"/"+filename
348     println("COPYING ${filename} to ${outputFiles}")
349     null
350   }
351   outputs.files outputFiles
352   inputs.files inputFiles
353
354 }
355
356 ide.dependsOn eclipseProject
357 ide.dependsOn eclipseClasspath
358 ide.dependsOn eclipseJdt
359 ide.dependsOn ideCopyDropins
360 ideJalviewjsBuild.dependsOn ideSetupWorkspace
361 ideJalviewjsBuild.dependsOn ideCopyDropins
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377 def jalviewjsBuildDir
378 def jalviewjsSiteDir
379 task jalviewjsSitePath {
380   if (jalviewjs_site_dir.startsWith("/")) {
381     jalviewjsSiteDir = jalviewjs_site_dir
382   } else {
383     def relativeBuildDir = file(jalviewDirAbsolutePath).toPath().relativize(buildDir.toPath())
384     jalviewjsBuildDir = "${relativeBuildDir}/jalviewjs"
385     jalviewjsSiteDir = jalviewjsBuildDir + "/" + jalviewjs_site_dir
386   }
387 }
388
389 def tempEclipseWorkspace
390 task jalviewjsSetTempEclipseWorkspace {
391   tempEclipseWorkspace = file(jalviewjs_eclipse_workspace)
392   if (!tempEclipseWorkspace.exists()) {
393     tempEclipseWorkspace = file("${buildDir}/tmp/eclipse-workspace")
394     //tempEclipseWorkspace.deleteOnExit()
395   }
396   println("ECLIPSE WORKSPACE: "+tempEclipseWorkspace.getPath())
397 }
398
399 task jalviewjsUnzipFiles {
400   dependsOn jalviewjsSitePath
401
402   def zipFiles = fileTree(dir: jalviewjs_utils_dir+"/"+jalviewjs_libjs_dir).include("*.zip")
403   zipFiles += jalviewjs_utils_dir+"/"+jalviewjs_swingjs_zip
404
405   doLast {
406     zipFiles.each { file_zip -> 
407       copy {
408         from zipTree(file_zip)
409         into jalviewjsSiteDir
410       }
411     }
412   }
413
414   inputs.files zipFiles
415   outputs.dir jalviewjsSiteDir
416 }
417
418 def eclipseDropinsDir
419 def eclipseBinary
420 task jalviewjsEclipsePaths {
421   def eclipseRoot = jalviewjs_eclipse_root
422   if (eclipseRoot.startsWith("~")) {
423     eclipseRoot = System.getProperty("user.home") + eclipseRoot.substring(1)
424   }
425         if (OperatingSystem.current().isMacOsX()) {
426     eclipseRoot += "/Eclipse.app"
427                 eclipseDropinsDir = eclipseRoot+"/Contents/Eclipse/dropins"
428                 eclipseBinary = eclipseRoot+"/Contents/MacOS/eclipse"
429         } else if (OperatingSystem.current().isWindows()) { // check these paths!!
430                 eclipseDropinsDir = eclipseRoot+"/dropins"
431                 eclipseBinary = eclipseRoot+"/eclipse"
432         } else { // linux or unix
433                 eclipseDropinsDir = eclipseRoot+"/dropins"
434                 eclipseBinary = eclipseRoot+"/eclipse"
435         }
436 }
437
438 task jalviewjsEclipseCopyDropins (type: Copy) {
439   dependsOn jalviewjsEclipsePaths
440   def inputFiles = fileTree(jalviewjs_utils_dir+"/"+jalviewjs_eclipse_dropins_dir)
441   def outputDir = eclipseDropinsDir
442
443   from inputFiles
444   into outputDir
445   def outputFiles = []
446   rename { filename ->
447     outputFiles += outputDir+"/"+filename
448     null
449   }
450   outputs.files outputFiles
451   inputs.files inputFiles
452 }
453
454 task jalviewjsEclipseSetup {
455   dependsOn jalviewjsEclipseCopyDropins
456   dependsOn jalviewjsSetTempEclipseWorkspace
457 }
458
459
460 task jalviewjsCreateJ2sSettings(type: WriteProperties) {
461   dependsOn jalviewjsSitePath
462   outputFile (jalviewDir+"/"+jalviewjs_j2s_settings)
463   def props = project.properties.sort { it.key }
464   def siteDirProperty = "j2s.site.directory"
465   def setSiteDir = false
466   props.each { prop, val ->
467     if (prop.startsWith("j2s.") && val != null) {
468       if (prop == siteDirProperty) {
469         if (!(val.startsWith("/") || val.startsWith("file://") )) {
470           val = jalviewjsSiteDir+"/"+val
471         }
472         setSiteDir = true
473       }
474       property(prop,val)
475     }
476     if (!setSiteDir) {
477       property(siteDirProperty,"${jalviewjsSiteDir}")
478     }
479   }
480   outputs.file(outputFile)
481 }
482
483 task jalviewjsCopyResources (type: Copy) {
484   dependsOn jalviewjsSitePath
485   def inputFiles = fileTree(dir: jalviewjs_resource_dir)
486   def outputDir = jalviewjsSiteDir+"/"+jalviewjs_j2s_subdir
487
488   from inputFiles
489   into outputDir
490   def outputFiles = []
491   rename { filename ->
492     outputFiles += outputDir+"/"+filename
493     null
494   }
495   outputs.files outputFiles
496   inputs.files inputFiles
497 }
498
499 task jalviewjsCopySiteResources (type: Copy) {
500   dependsOn jalviewjsSitePath
501   def inputFiles = fileTree(dir: jalviewjs_utils_dir+"/"+jalviewjs_site_resource_dir)
502   def outputDir = jalviewjsSiteDir
503
504   from inputFiles
505   into outputDir
506   def outputFiles = []
507   rename { filename ->
508     outputFiles += outputDir+"/"+filename
509     null
510   }
511   outputs.files outputFiles
512   inputs.files inputFiles
513 }
514
515 task cleanJalviewjs {
516   dependsOn jalviewjsSitePath
517   /*
518   delete jalviewDir+"/"+jalviewjsSiteDir
519   delete jalviewDir+"/"+eclipse_bin_dir
520   delete file(tempEclipseWorkspace.getAbsolutePath()+"/.metadata")
521   delete jalviewDir+"/"+jalviewjs_j2s_settings
522   */
523 }
524
525 task jalviewjsProjectImport(type: Exec) {
526   // work out how to do this!
527   dependsOn eclipseProject
528   dependsOn eclipseClasspath
529   dependsOn eclipseJdt
530   dependsOn jalviewjsEclipsePaths
531   dependsOn jalviewjsEclipseSetup
532   executable(eclipseBinary)
533   args(["-nosplash", "--launcher.suppressErrors", "-application", "com.seeq.eclipse.importprojects.headlessimport", "-data", tempEclipseWorkspace.getPath(), "-import", jalviewDirAbsolutePath])
534
535   def projdir = tempEclipseWorkspace.getPath()+"/.metadata/.plugins/org.eclipse.core.resources/.projects/jalview/org.eclipse.jdt.core"
536   inputs.file(jalviewDir+"/.project")
537   outputs.dir(projdir)
538   outputs.upToDateWhen { file(projdir).exists() }
539 }
540
541
542
543
544
545
546
547
548 task jalviewjsTranspile(type: Exec) {
549   dependsOn jalviewjsCreateJ2sSettings 
550   dependsOn jalviewjsProjectImport
551   dependsOn jalviewjsEclipsePaths
552   executable(eclipseBinary)
553   args(["-nosplash", "--launcher.suppressErrors", "-application", "org.eclipse.jdt.apt.core.aptBuild", "-data", tempEclipseWorkspace, "-"+jalviewjs_eclipseBuildArg, eclipse_project_name ])
554
555   def stdout
556   def stderr
557   doFirst {
558     stdout = new ByteArrayOutputStream()
559     stderr = new ByteArrayOutputStream()
560     standardOutput = new org.apache.tools.ant.util.TeeOutputStream(new FileOutputStream("${jalviewjsBuildDir}/${jalviewjs_j2s_stdout}"), stdout);
561     errorOutput = new org.apache.tools.ant.util.TeeOutputStream(new FileOutputStream("${jalviewjsBuildDir}/${jalviewjs_j2s_stderr}"), stderr);
562   }
563   doLast {
564     if (stdout.toString().contains("Error processing ")) {
565       // j2s did not complete transpile
566       throw new TaskExecutionException("Error during transpilation:\n${stderr}\n")
567     }
568   }
569
570   inputs.dir(sourceDir)
571   outputs.dir(eclipse_bin_dir+"/main")
572   outputs.dir(jalviewjsSiteDir+"/"+jalviewjs_j2s_subdir)
573   outputs.file(jalviewjsSiteDir+jalviewjs_server_resource)
574   outputs.upToDateWhen { file(jalviewjsSiteDir+jalviewjs_server_resource).exists() }
575
576 }
577
578
579
580
581
582
583
584
585 task jalviewjsBuildSite {
586   dependsOn jalviewjsSitePath
587   dependsOn jalviewjsUnzipFiles
588   dependsOn jalviewjsCopyResources
589   dependsOn jalviewjsCopySiteResources
590   dependsOn jalviewjsTranspile
591 }
592
593 task jalviewjsSiteTar(type: Tar) {
594   dependsOn jalviewjsBuildSite
595   def outputFilename = "jalviewjs-site-${JALVIEW_VERSION}.tar.gz"
596   try {
597     archiveFileName = outputFilename
598   } catch (Exception e) {
599     archiveName = outputFilename
600   }
601
602   compression Compression.GZIP
603
604   from jalviewjsSiteDir
605   into jalviewjs_site_dir // this is inside the tar file
606
607   inputs.dir(jalviewjsSiteDir)
608 }
609
610 task jalviewjs {
611   dependsOn jalviewjsBuildSite
612 }
613
614 def jalviewjsServer = null
615 task jalviewjsServerStart {
616   dependsOn jalviewjsSitePath
617   doLast {
618
619     if (jalviewjsServer != null) {
620       println("SERVER ALREADY RUNNING. Go to "+jalviewjsServer.getResourceUrl(jalviewjs_server_resource)+" . Run  gradle jalviewjsServerStop  to stop.")
621     } else {
622
623       SimpleHttpFileServerFactory factory = new SimpleHttpFileServerFactory()
624       def port = Integer.valueOf(jalviewjs_server_port)
625       def start = port
626       def running = false
627       while(port < start+1000 && !running) {
628         try {
629           def doc_root = new File(jalviewDirAbsolutePath +"/"+ jalviewjsSiteDir)
630           jalviewjsServer = factory.start(doc_root, port)
631           running = true
632           println("SERVER STARTED with document root ${doc_root}.\nGo to "+jalviewjsServer.getResourceUrl(jalviewjs_server_resource)+" . Run  gradle jalviewjsServerStop  to stop.")
633           //println("Ctrl-c to stop.");java.lang.Thread.sleep(Integer.valueOf(jalviewjs_server_wait)*1000);
634         } catch (Exception e) {
635           port++;
636         }
637       }
638
639     }
640
641   }
642
643 }
644
645 /* server persists in gradle daemon but reference is not accessible across builds
646 task jalviewjsServerStop {
647   doLast {
648
649     if (jalviewjsServer != null) {
650
651       println("SERVER ON PORT "+jalviewjsServer.getPort()+" STOPPING. Run  gradle jalviewjsServerStart  to start again.")
652       jalviewjsServer.stop()
653
654     } else {
655       println("SERVER NOT RUNNING. Run  gradle jalviewjsServerStart  to start.")
656     }
657
658   }
659 }
660 */
661
662 project.afterEvaluate {
663   tasks.findByName('ideJalviewjsBuild').dependsOn eclipseProject
664   tasks.findByName('ideJalviewjsBuild').dependsOn eclipseClasspath
665   tasks.findByName('ideJalviewjsBuild').dependsOn eclipseJdt
666 }
667
668
669