/
generateSite.gradle
executable file
·524 lines (496 loc) · 20.6 KB
/
generateSite.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
import groovy.util.*
import static groovy.io.FileType.*
buildscript {
repositories {
maven {
credentials {
username mavenUsername
password mavenPassword
}
url mavenRepository
}
}
dependencies {
classpath libs.asciidoctorj.diagram
}
}
repositories {
maven {
credentials {
username depsMavenUsername
password depsMavenPassword
}
url depsMavenRepository
}
}
dependencies {
jbake libs.asciidoctorj.diagram
jbake libs.pebble
config.jbake.plugins.each { plugin ->
jbake plugin
}
}
apply plugin: 'org.jbake.site'
def color = { color, text ->
def colors = [black: 30, red: 31, green: 32, yellow: 33, blue: 34, magenta: 35, cyan: 36, white: 37]
return new String((char) 27) + "[${colors[color]}m${text}" + new String((char) 27) + "[0m"
}
jbake {
version = '2.6.7'
srcDirName = "${targetDir}/microsite/tmp/site"
destDirName = "${targetDir}/microsite/output"
configuration['asciidoctor.option.requires'] = "asciidoctor-diagram"
config.microsite.each { key, value ->
configuration['site.'+key-'config.microsite.'] = value?:''
//println 'site.'+key-'config.microsite.' +" = "+ value
}
def micrositeContextPath = config.microsite.contextPath?:'/'
configuration['asciidoctor.attributes'] = [
"sourceDir=${targetDir}",
'source-highlighter=prettify@',
//'imagesDir=../images@',
"imagesoutDir=${targetDir}/microsite/output/images@",
"imagesDir=${micrositeContextPath.endsWith('/') ? micrositeContextPath : micrositeContextPath.concat('/')}images@",
"targetDir=${targetDir}",
"docDir=${docDir}",
"projectRootDir=${new File(docDir).canonicalPath}@",
]
if(config.jbake.asciidoctorAttributes) {
config.jbake.asciidoctorAttributes.each { entry ->
configuration['asciidoctor.attributes'] << entry
}
}
}
def prepareAndCopyTheme = {
//copy internal theme
println "copy internal theme ${new File(projectDir, 'src/site').canonicalPath}"
copy {
from('src/site')
into("${targetDir}/microsite/tmp/site")
}
//check if a remote pdfTheme is defined
def siteTheme = System.getenv('DTC_SITETHEME')?:""
def themeFolder = new File(projectDir, "../themes/" + siteTheme.md5())
try {
if (siteTheme) {
println "use siteTheme $siteTheme"
//check if it is already installed
if (!themeFolder.exists()) {
if (System.getenv('DTC_HEADLESS')) {
ant.yesno = "y"
} else {
println "${color 'green', """\nTheme '$siteTheme' is not installed yet. """}"
def input = ant.input(message: """
${color 'green', 'do you want me to download and install it to '}
${color 'green', ' ' + themeFolder.canonicalPath}
${color 'green', 'for you?'}\n""",
validargs: 'y,n', addproperty: 'yesno')
}
if (ant.yesno == "y") {
themeFolder.mkdirs()
download.run {
src siteTheme
dest new File(themeFolder, 'siteTheme.zip')
overwrite true
}
copy {
from zipTree(new File(themeFolder, 'siteTheme.zip'))
into themeFolder
}
delete {
delete new File(themeFolder, 'siteTheme.zip')
}
} else {
println "${color 'green', """\nI will continue without the theme for now... """}"
siteTheme = ""
}
}
//copy external theme
if (siteTheme) {
copy {
from(themeFolder) {}
into("${targetDir}/microsite/tmp/")
}
//check if the config has to be updated
// check if config still contains /** microsite **/
def configFile = new File(docDir, mainConfigFile)
def configFileText = configFile.text
if (configFileText.contains("/** start:microsite **/")) {
def configFragment = new File(targetDir,'/microsite/tmp/site/configFragment.groovy')
if (configFragment.exists()) {
println "${color 'green', """
It seems that this theme is used for the first time in this project.
Let's configure it!
If you are unsure, change these settings later in your config file
$configFile.canonicalPath
"""}"
def comment = ""
def conf = ""
def example = ""
def i = 0
configFragment.eachLine { line ->
if (line.trim()) {
if (line.startsWith("//")) {
conf += " " + line + "\n"
def tmp = line[2..-1].trim()
comment += color('green', tmp) + "\n"
if (tmp.toLowerCase().startsWith("example")) {
example = tmp.replaceAll("[^ ]* ", "")
}
} else {
//only prompt if there is something to prompt
if (line.contains("##")) {
def property = line.replaceAll("[ =].*", "")
if (!example) {
example = config.microsite[property]
}
comment = color('blue', "$property") + "\n" + comment
if (example) {
ant.input(message: comment,
addproperty: 'res' + i, defaultvalue: example)
} else {
ant.input(message: comment,
addproperty: 'res' + i)
}
(comment, example) = ["", ""]
line = line.replaceAll("##.+##", ant['res' + i])
conf += " " + line + "\n"
i++
} else {
conf += " " + line + "\n"
}
}
} else {
conf += "\n"
}
}
configFile.write(configFileText.replaceAll("(?sm)/[*][*] start:microsite [*][*]/.*/[*][*] end:microsite [*][*]/", "%%marker%%").replace("%%marker%%", conf))
println color('green', "config written\nopen ${targetDir}/microsite/output/index.html in your browser\nto see your microsite!")
}
//copy the dummy docs (blog, landing page) to the project repository
copy {
from(new File(themeFolder, 'site/doc')) {}
into(new File(docDir, inputPath))
}
}
}
}
} catch (Exception e) {
println color('red', e.message)
if (e.message.startsWith("Not Found")) {
themeFolder.deleteDir()
throw new GradleException("Couldn't find theme. Did you specify the right URL?\n"+e.message)
} else {
throw new GradleException(e.message)
}
}
//copy project theme
if (config.microsite.siteFolder) {
def projectTheme = new File(new File(docDir, inputPath), config.microsite.siteFolder)
println "copy project theme ${projectTheme.canonicalPath}"
copy {
from(projectTheme) {}
into("${targetDir}/microsite/tmp/site")
}
}
}
def convertAdditionalFormats = {
if (config.microsite.additionalConverters) {
File sourceFolder = new File(targetDir, '/microsite/tmp/site/doc')
sourceFolder.traverse(type: FILES) { file ->
def extension = '.' + file.name.split("[.]")[-1]
if (config.microsite.additionalConverters[extension]) {
def command = config.microsite.additionalConverters[extension].command
def type = config.microsite.additionalConverters[extension].type
def binding = new Binding([
file : file,
config: config
])
def shell = new GroovyShell(getClass().getClassLoader(), binding)
switch (type) {
case 'groovy':
shell.evaluate(command)
break
case 'groovyFile':
shell.evaluate(new File(docDir, command).text)
break
case 'bash':
if (command=='dtcw:rstToHtml.py') {
// this is an internal script
command = projectDir.canonicalPath+'/scripts/rstToHtml.py'
}
command = ['bash', '-c', command + ' "' + file + '"']
def process = command.execute([], new File(docDir))
process.waitFor()
if (process.exitValue()) {
def error = process.err.text
println """
can't convert '${file.canonicalPath-docDir-'/build/microsite/tmp/site/doc'}':
${error}
"""
throw new Exception("""
can't convert '${file.canonicalPath-docDir-'/build/microsite/tmp/site/doc'}':
${error}
""")
}
}
}
}
}
}
def parseAsciiDocAttribs = { origText, jbake ->
def parseAttribs = true
def text = ""
def beforeToc = ""
origText.eachLine { line ->
if (parseAttribs && line.startsWith(":jbake")) {
def parsedJbakeAttribute = (line - ":jbake-").split(": +", 2)
if(parsedJbakeAttribute.length != 2) {
logger.warn("jbake-attribute is not valid or Asciidoc conform: $line")
logger.warn("jbake-attribute $line will be ignored, trying to continue...")
} else {
jbake[parsedJbakeAttribute[0]] = parsedJbakeAttribute[1]
}
} else {
if (line.startsWith("[")) {
// stop parsing jBake-attribs when a [source] - block starts which might contain those attribs as example
parseAttribs = false
}
text += line+"\n"
//there are some attributes which have to be set before the toc
if (line.startsWith(":toc") ) {
beforeToc += line+"\n"
}
}
}
return [text, beforeToc]
}
def parseOtherAttribs = { origText, jbake ->
if (origText.contains('~~~~~~')) {
def parseAttribs = true
def text = ""
origText.eachLine { line ->
if (parseAttribs && line.contains("=")) {
line = (line - "jbake-").split("=", 2)
jbake[line[0]] = line[1]
} else {
if (line.startsWith("~~~~~~")) {
// stop parsing jBake-attribs when delimiter shows up
parseAttribs = false
} else {
text += line + "\n"
}
}
}
return text
} else {
return origText
}
}
def renderHeader = { fileName, jbake ->
def header = ''
if (fileName.toLowerCase() ==~ '^.*(html|md)$') {
jbake.each { key, value ->
if (key == 'order') {
header += "jbake-${key}=${(value ?: '1') as Integer}\n"
} else {
if (key in ['type', 'status']) {
header += "${key}=${value}\n"
} else {
header += "jbake-${key}=${value}\n"
}
}
}
header += "~~~~~~\n\n"
} else {
jbake.each { key, value ->
if (key == 'order') {
header += ":jbake-${key}: ${(value ?: '1') as Integer}\n"
} else {
header += ":jbake-${key}: ${value}\n"
}
}
}
return header
}
def fixMetaDataHeader = {
//fix MetaData-Header
File sourceFolder = new File(targetDir, '/microsite/tmp/site/doc')
logger.info("sourceFolder: " + sourceFolder.canonicalPath)
sourceFolder.traverse(type: FILES) { file ->
if (file.name.toLowerCase() ==~ '^.*(ad|adoc|asciidoc|html|md)$') {
if (file.name.startsWith("_") || file.name.startsWith(".")) {
//ignore
} else {
def origText = file.text
//parse jbake attributes
def text = ""
def jbake = [
status: "published",
order: -1,
type: 'page_toc'
]
if (file.name.toLowerCase() ==~ '^.*(md|html)$') {
// we don't have a toc for md or html
jbake.type = 'page'
}
def beforeToc = ""
if (file.name.toLowerCase() ==~ '^.*(ad|adoc|asciidoc)$') {
(text, beforeToc) = parseAsciiDocAttribs(origText, jbake)
} else {
text = parseOtherAttribs(origText, jbake)
}
def name = file.canonicalPath - (sourceFolder.canonicalPath+File.separator)
if (File.separator=='\\') {
name = name.split("\\\\")
} else {
name = name.split("/")
}
if (name.size()>1) {
if (!jbake.menu) {
jbake.menu = name[0]
if (jbake.menu ==~ /[0-9]+[-_].*/) {
jbake.menu = jbake.menu.split("[-_]", 2)[1]
}
}
def docname = name[-1]
if (docname ==~ /[0-9]+[-_].*/) {
jbake.order = docname.split("[-_]",2)[0]
docname = docname.split("[-_]",2)[1]
}
if (name.size() > 2) {
if ((jbake.order as Integer)==0) {
// let's take the order from the second level dir or file and not the file
def secondLevel = name[1]
if (secondLevel ==~ /[0-9]+[-_].*/) {
jbake.order = secondLevel.split("[-_]",2)[0]
}
} else {
if (((jbake.order?:'1') as Integer) > 0) {
//
} else {
jbake.status = "draft"
}
}
}
if (jbake.order==-1 && docname.startsWith('index')) {
jbake.order = -987654321 // special 'magic value' given to index pages.
jbake.status = "published"
}
// news blog
if (jbake.order==-1 && jbake.type=='post') {
jbake.order = 0
try {
jbake.order = Date.parse("yyyy-MM-dd", jbake.date).time / 100000
} catch ( Exception e) {
System.out.println "unparsable date ${jbake.date} in $name"
}
jbake.status = "published"
}
def leveloffset = 0
if (file.name.toLowerCase() ==~ '^.*(ad|adoc|asciidoc)$') {
text.eachLine { line ->
if (!jbake.title && line ==~ "^=+ .*") {
jbake.title = (line =~ "^=+ (.*)")[0][1]
def level = (line =~ "^(=+) .*")[0][1]
if (level == "=") {
leveloffset = 1
}
}
}
} else {
if (file.name.toLowerCase() ==~ '^.*(html)$') {
if (!jbake.title) {
text.eachLine { line ->
if (!jbake.title && line ==~ "^<h[1-9]>.*</h.*") {
jbake.title = (line =~ "^<h[1-9]>(.*)</h.*")[0][1]
}
}
}
} else {
// md
if (!jbake.title) {
text.eachLine { line ->
if (!jbake.title && line ==~ "^#+ .*") {
jbake.title = (line =~ "^#+ (.*)")[0][1]
}
}
}
}
}
if (!jbake.title) {
jbake.title = docname
}
if (leveloffset==1) {
//leveloffset needed
// we always start with "==" not with "="
// only used for adoc
text = text.replaceAll("(?ms)^(=+) ", '$1= ')
}
if (config.microsite.customConvention) {
def binding = new Binding([
file : file,
sourceFolder : sourceFolder,
config: config,
headers : jbake
])
def shell = new GroovyShell(getClass().getClassLoader(), binding)
shell.evaluate(config.microsite.customConvention)
System.out.println jbake
}
def header = renderHeader(file.name, jbake)
if (file.name.toLowerCase() ==~ '^.*(ad|adoc|asciidoc)$') {
file.write(header + "\nifndef::dtc-magic-toc[]\n:dtc-magic-toc:\n$beforeToc\n\n:toc: left\n\n++++\n<!-- endtoc -->\n++++\nendif::[]\n" + text, "utf-8")
} else {
file.write(header + "\n" + text, "utf-8")
}
}
}
}
}
}
task generateSite(
group: 'docToolchain',
description: 'generate a microsite using jBake.') {
doLast {
new File("${targetDir}/microsite/tmp").mkdirs()
println new File("${targetDir}/microsite/tmp/").canonicalPath
prepareAndCopyTheme()
//copy docs
copy {
from(new File(docDir, inputPath)) {}
into("${targetDir}/microsite/tmp/site/doc")
}
// if configured, convert restructuredText or anything else
convertAdditionalFormats()
// convention over configuration
fixMetaDataHeader()
}
}
task previewSite(
group: 'docToolchain',
dependsOn: [],
description: 'preview your Microsite',
) {
doLast {
println("previewSite command has been deprecated.")
println("To preview your site, open ${targetDir}/microsite/output/index.html in your browser.")
println("To read alternative ways to preview your site, please consult the documentation.")
}
}
previewSite.dependsOn(generateSite)
previewSite.mustRunAfter(bake)
task copyImages(type: Copy) {
config.imageDirs.each { imageDir ->
from(new File (new File(docDir, inputPath),imageDir)) {}
logger.info ('imageDir: '+imageDir)
into("${targetDir}/microsite/output/images")
}
config.resourceDirs.each { resource ->
from(new File(file(srcDir),resource.source))
logger.info ('resource: '+resource.source)
into("${targetDir}/microsite/output/" + resource.target)
}
}
bake.dependsOn copyImages
generateSite.finalizedBy bake