prependFilename

Jody Winter Ralf D. Müller Alexander Schwartz Ralf D. Müller

1 minute to read

About This Task

When Asciidoctor renders a file, the file context only knows the name of the top-level AsciiDoc file. But an include file doesn’t know that it is being included. It simply gets the name of the master file and has no chance to get its own name as an attribute. This task crawls through all AsciiDoc files and prepends the name of the current file like this:

:filename: 015_tasks/03_task_prependFilename.adoc

This way, each file gets its own filename. This enables features like the inclusion of file contributors (see exportContributors-task).

Note
This task skips all files named config.*, _config.*, feedback.* and _feedback.*.

Source

scripts/prependFilename.gradle
import static groovy.io.FileType.*

task prependFilename(
        description: 'crawls through all AsciiDoc files and prepends the name of the current file',
        group: 'docToolchain helper',
) {
    doLast {
        File sourceFolder = new File("${docDir}/${inputPath}")
        println("sourceFolder: " + sourceFolder.canonicalPath)
        sourceFolder.traverse(type: FILES) { file ->
            if (file.name ==~ '^.*(ad|adoc|asciidoc)$') {
                if (file.name.split('[.]')[0] in ["feedback", "_feedback", "config", "_config"]) {
                    println "skipped "+file.name
                } else {
                    def text = file.getText('utf-8')
                    def name = file.canonicalPath - sourceFolder.canonicalPath
                    name = name.replace("\\", "/").replaceAll("^/", "")
                    if (text.contains(":filename:")) {
                        text = text.replaceAll(":filename:.*", ":filename: $name")
                        println "updated "+name
                    } else {
                        text = ":filename: $name\n" + text
                        println "added   "+name
                    }
                    file.write(text,'utf-8')
                }
            }
        }
    }
}