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).

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


import static*

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 ( ==~ '^.*(ad|adoc|asciidoc)$') {
                if ('[.]')[0] in ["feedback", "_feedback", "config", "_config"]) {
                    println "skipped "
                } 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