-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathbuild.gradle
525 lines (452 loc) · 13.8 KB
/
build.gradle
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
buildscript {
repositories {
mavenCentral()
}
// Make sure the build script can find the DocBook classes
dependencies {
classpath group: 'org.docbook', name: 'docbook-xslTNG', version: '1.5.4'
classpath group: 'org.docbook', name: 'schemas-docbook', version: '5.2b11'
}
}
plugins {
id "java"
id 'com.nwalsh.gradle.saxon.saxon-gradle' version '0.9.3'
id 'com.nwalsh.gradle.relaxng.validate' version '0.0.6'
}
import java.nio.file.*
import java.nio.charset.StandardCharsets
import org.gradle.internal.os.OperatingSystem
import com.nwalsh.gradle.saxon.SaxonXsltTask
import com.nwalsh.gradle.relaxng.validate.RelaxNGValidateTask
repositories {
mavenCentral()
maven {
url "https://dev.saxonica.com/maven"
}
}
configurations {
saxonj.extendsFrom(implementation)
docbook.extendsFrom(implementation)
validateRuntime.extendsFrom(testImplementation)
}
ext {
tools = [
"python3": OperatingSystem.current().isWindows() ? "python3.exe" : "python3",
"docker": OperatingSystem.current().isWindows() ? "docker.exe" : "docker",
"node": OperatingSystem.current().isWindows() ? "node" : "node",
"npm": OperatingSystem.current().isWindows() ? "npm" : "npm"
]
saxonLicenseDir = "${projectDir}/lib"
}
dependencies {
implementation (
[group: "com.saxonica", name: "Saxon-EE", version: "10.6"],
)
saxonj (
files(saxonLicenseDir),
[group: 'org.docbook', name: 'schemas-docbook', version: '5.2b10a4'],
[group: 'org.docbook', name: 'docbook-xslTNG', version: '1.5.4']
)
}
saxon.configure {
entityResolverClass "org.xmlresolver.Resolver"
uriResolverClass "org.xmlresolver.Resolver"
sourceSaxParser "org.xmlresolver.tools.ResolvingXMLReader"
stylesheetSaxParser "org.xmlresolver.tools.ResolvingXMLReader"
initializer 'org.docbook.xsltng.extensions.Register'
}
tools.keySet().each { tool ->
if (!ext.has(tool)) {
System.getenv("PATH").split(System.getProperty("path.separator")).each { dir ->
def fn = new File(dir + "/" + tools[tool])
if (fn.exists() && fn.canExecute()) {
ext.set(tool, fn.toString())
}
}
if (!ext.has(tool)) {
ext.set(tool, null)
}
}
}
println("Building with Java version ${System.getProperty('java.version')}")
def imageTag = "version${version.replace('.', '')}"
// ============================================================
void killContainer() {
if (docker == null) {
throw new GradleException("Cannot run Docker without ${tools['docker']}")
}
def kill = []
ProcessBuilder pb = new ProcessBuilder()
.command(docker,
"ps", "-a", "--format={{.ID}} {{.Image}} {{.Status}}")
Process proc = pb.start();
BufferedReader reader = new BufferedReader(
new InputStreamReader(proc.getInputStream()))
String line = reader.readLine()
while (line != null) {
def parts = line.split(" ")
if (parts.length > 2) {
def id = parts[0]
def image = parts[1]
def status = parts[2]
if (image.contains(dockerImage)) {
kill += id
}
line = reader.readLine()
}
}
proc.waitFor()
reader.close()
kill.each { id ->
pb = new ProcessBuilder()
.command(docker, "kill", id)
proc = pb.start();
proc.waitFor()
}
}
// ============================================================
// Tasks to interact with the python web server
task checkPython() {
doFirst {
if (python3 == null) {
throw new GradleException("Cannot run web server without ${tools['python3']}")
}
}
}
task pythonServerStop(dependsOn: ['checkPython']) {
// If you kill the Gradle process with Ctrl-C, the Python server
// sometimes hangs around in the background. Before we attempt to
// start it (again?), we tell it to stop. If our attempt to tell it
// to stop fails, we don't care (either it isn't running or
// something worse is going on).
doLast {
try {
URL url = new URL("http://localhost:${serverPort}/stop");
URLConnection con = url.openConnection();
HttpURLConnection http = (HttpURLConnection) con;
http.setRequestMethod("POST");
http.setDoOutput(true);
byte[] out = "Stop".getBytes(StandardCharsets.UTF_8)
http.setFixedLengthStreamingMode(out.length)
http.setRequestProperty("Content-type", "text/plain");
http.connect()
OutputStream os = http.getOutputStream()
os.write(out)
os.close()
// Give the server a chance to finish up.
Thread.sleep(1000)
} catch (Exception ex) {
// nevermind
}
}
}
task pythonServerStart(dependsOn: ['pythonServerStop']) {
// We do this the hard way so that we can report the unbuffered
// output from the script in realtime.
doLast {
def builder = new ProcessBuilder(
[python3, "python/server.py", "-p", serverPort])
def process = builder.start()
def stdoutReader = new ProcessOutputReader(process.getInputStream())
def stderrReader = new ProcessOutputReader(process.getErrorStream())
Thread stdoutThread = new Thread(stdoutReader)
Thread stderrThread = new Thread(stderrReader)
stdoutThread.start()
stderrThread.start()
process.waitFor()
stdoutThread.join()
stderrThread.join()
}
}
class ProcessOutputReader implements Runnable {
private InputStream is;
public ProcessOutputReader(InputStream is) {
this.is = is
}
public void run() {
BufferedReader br = new BufferedReader(new InputStreamReader(is))
String line = br.readLine()
while (line != null) {
println(line)
line = br.readLine()
}
}
}
// ============================================================
// Tasks to interact with Node/Docker
task nodeServerStart(type: Exec) {
def dir = projectDir
if (rootProject.ext.has('dir')) {
dir = Paths.get(projectDir.toString()).resolve(rootProject.ext.dir)
}
environment "PORT", serverPort
workingDir = "node"
commandLine "node", "server.js"
ignoreExitValue = true
}
// ============================================================
// Tasks to interact with Node/Docker
task buildContainer(type: Exec) {
doFirst {
if (docker == null) {
throw new GradleException("Cannot run Docker without ${tools['docker']}")
}
}
workingDir "${projectDir}/node"
commandLine docker, "build", "-t", "${dockerImage}:${imageTag}", "."
}
task pullContainer() {
def found = false
doFirst {
if (docker == null) {
throw new GradleException("Cannot run Docker without ${tools['docker']}")
}
}
doLast {
ProcessBuilder pb = new ProcessBuilder()
.command(docker, "images", "--format={{.Repository}} {{.Tag}}")
Process proc = pb.start();
BufferedReader reader = new BufferedReader(
new InputStreamReader(proc.getInputStream()))
String line = reader.readLine()
while (!found && line != null) {
def parts = line.split(" ")
if (parts.length > 1) {
def repo = parts[0]
def tag = parts[1]
found = found || (repo == dockerImage && tag == imageTag)
}
line = reader.readLine()
}
proc.waitFor()
reader.close()
}
doLast {
if (!found) {
println("Attempting to pull ${dockerImage}:${imageTag}")
exec {
commandLine docker, "pull", "${dockerImage}:${imageTag}"
}
}
}
}
task dockerServerStart(type: Exec, dependsOn: ['pullContainer']) {
def dir = "${projectDir}"
if (rootProject.ext.has('dir')) {
dir = Paths.get(projectDir.toString()).resolve(rootProject.ext.dir)
}
doFirst {
killContainer()
}
doLast {
killContainer()
}
// It would be more customary here to run the server in the
// container on port 80, but that leads to a slightly misleading
// message, so we simply run it on the same port that we're going
// to map to.
commandLine docker,
"run", "--rm", "-p", "${serverPort}:${serverPort}",
"-v", "${dir}:/src",
"-e", "ROOTDIR=/src",
"-e", "PORT=${serverPort}",
"${dockerImage}:${imageTag}"
ignoreExitValue = true
}
task dockerServerStop() {
doLast {
killContainer()
}
}
task parseCompilerOptions() {
// -Pxsl= -Pexport= -Pdir=
def xslFile = null
def exportFile = null
def sourceDir = null
if (rootProject.ext.has('xsl')) {
xslFile = rootProject.ext.xsl
}
if (rootProject.ext.has('export')) {
exportFile = rootProject.ext.export
} else {
if (xslFile != null) {
exportFile = xslFile.replace(".xsl", ".sef.json")
}
}
if (rootProject.ext.has('dir')) {
sourceDir = Paths.get(projectDir.toString()).resolve(rootProject.ext.dir)
} else {
sourceDir = projectDir.toString()
}
doFirst {
if (xslFile == null) {
println("You must specify an XSLT file with -Pxsl=")
}
if (sourceDir == null) {
println("You must specify the base directory with -Pdir=")
}
}
doLast {
if (xslFile != null && exportFile != null && sourceDir != null) {
parseCompilerOptions.ext.xslFile = xslFile
parseCompilerOptions.ext.exportFile = exportFile
parseCompilerOptions.ext.sourceDir = sourceDir
} else {
throw new GradleException("Missing compile parameters")
}
}
}
task eej(dependsOn: ['parseCompilerOptions']) {
doLast {
def xslFile = parseCompilerOptions.xslFile
def exportFile = parseCompilerOptions.exportFile
def sourceDir = parseCompilerOptions.sourceDir
javaexec {
classpath = configurations.saxonj
mainClass = "com.saxonica.Transform"
args "-xsl:${xslFile}",
"-export:${exportFile}",
"-target:JS", "-nogo", "-relocate:on", "-ns:##html5"
}
}
}
task node_xslt3(dependsOn: ['parseCompilerOptions']) {
doLast {
def xslFile = parseCompilerOptions.xslFile
def exportFile = parseCompilerOptions.exportFile
def sourceDir = parseCompilerOptions.sourceDir
def args = ["node", "node/node_modules/xslt3/xslt3.js",
"-xsl:${xslFile}", "-export:${exportFile}",
"-nogo", "-ns:##html5"]
exec {
commandLine args
}
}
}
task docker_xslt3(dependsOn: ['parseCompilerOptions', 'pullContainer']) {
doLast {
def xslFile = parseCompilerOptions.xslFile
def exportFile = parseCompilerOptions.exportFile
def sourceDir = parseCompilerOptions.sourceDir
def args = [docker, "run", "--rm",
"-v", "${sourceDir}:/src",
"${dockerImage}:${imageTag}",
"node", "node_modules/xslt3/xslt3.js",
"-xsl:/src/${xslFile}", "-export:/src/${exportFile}",
"-nogo", "-ns:##html5"]
exec {
commandLine args
}
}
}
task checkConfig() {
doLast {
if (rootProject.ext.has('docker')) {
println("Found Docker: ${rootProject.ext.get('docker')}")
} else {
println("Unable to find Docker (docker)")
}
if (rootProject.ext.has('python3')) {
println("Found Python: ${rootProject.ext.get('python3')}")
} else {
println("Unable to find Python 3 (python3)")
}
if (rootProject.ext.has('node') && rootProject.ext.has('npm')) {
println("Found Node: ${rootProject.ext.get('node')} and ${rootProject.ext.get('npm')}")
} else {
println("Unable to find Node (node and npm)")
}
}
}
// ============================================================
// Just my usual testing tasks.
task helloWorld() {
/*
doLast {
configurations.saxonj.resolve().each { path ->
println(path)
}
}
*/
doLast {
println("Hello, world")
}
}
// ============================================================
// Below here are the templates for building the presentation
task xincludePresentation(type: SaxonXsltTask, dependsOn: ['presentation_resources']) {
inputs.files fileTree(dir: "${projectDir}/src/main/xml")
input "${projectDir}/src/main/xml/presentation.xml"
stylesheet "${projectDir}/tools/xinclude.xsl"
output "${buildDir}/presentation.xml"
}
task validatePresentation(type: RelaxNGValidateTask, dependsOn: ['xincludePresentation']) {
input "${buildDir}/presentation.xml"
schema "${projectDir}/tools/docbook.rng"
output "${buildDir}/validated.xml"
}
task presentation(type: SaxonXsltTask, dependsOn: ['validatePresentation']) {
//outputs.upToDateWhen { false }
outputs.files fileTree(dir: "${projectDir}/presentation")
input "${buildDir}/validated.xml"
output "${projectDir}/presentation/index.html"
stylesheet "${projectDir}/tools/presentation.xsl"
parameters (
'debug': '',
// 'debug': 'chunks,chunk-cleanup,intra-chunk-refs,intra-chunk-links',
'chunk': 'index.html',
'chunk-output-base-uri': "${projectDir}/presentation/",
'mediaobject-input-base-uri': "file:${projectDir}/presentation/",
'resource-base-uri': '../presentation/',
'annotation-style': 'javascript',
'profile-outputformat': 'online',
'persistent-toc': true,
'tutorial-version': version,
'server-port': serverPort
)
}
task presentation_resources(dependsOn: ["local_presentation_resources"]) {
def dbjar = null
configurations.saxonj.each { path ->
if (path.toString().contains("docbook-xslTNG")) {
dbjar = path
}
}
doLast {
if (dbjar == null) {
throw new GradleException("Failed to locate DocBook xslTNG jar file")
}
copy {
into "${projectDir}/presentation"
from ({ zipTree(dbjar.toString()) }) {
include "org/docbook/xsltng/resources/**"
}
eachFile { fileCopyDetails ->
def originalPath = fileCopyDetails.path
fileCopyDetails.path = originalPath.replace('org/docbook/xsltng/resources/', '')
}
}
}
doLast {
delete "${projectDir}/presentation/org"
}
}
presentation_resources.onlyIf {
!file("${projectDir}/presentation/css/docbook.css").exists()
}
task local_presentation_resources() {
doFirst {
copy {
into "${projectDir}/presentation"
from ("${projectDir}/src/main/resources")
}
}
doFirst {
copy {
into "${projectDir}/presentation"
from ("${projectDir}/src/main/xml") {
include "*.png"
}
}
}
}