Created
February 17, 2012 18:12
-
-
Save ldaley/1854686 to your computer and use it in GitHub Desktop.
Transforming HTML in a Gradle build
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.jsoup.Jsoup | |
import org.jsoup.nodes.Document | |
class JSoupFilterReader extends FilterReader { | |
Closure withDocument | |
JSoupFilterReader(Reader reader) { | |
super(new DeferringReader(reader)); | |
this.in.parent = this | |
} | |
private static class DeferringReader extends Reader { | |
private final Reader source | |
private Reader delegate | |
private JSoupFilterReader parent | |
DeferringReader(Reader source) { | |
this.source = source | |
} | |
int read(char[] cbuf, int off, int len) { | |
if (delegate == null) { | |
Document document = Jsoup.parse(source.text) | |
Closure config = parent.withDocument?.clone() as Closure | |
if (config) { | |
config.resolveStrategy = Closure.DELEGATE_FIRST | |
config.delegate = document | |
config(document) | |
} | |
delegate = new StringReader(document.toString()) | |
} | |
delegate.read(cbuf, off, len) | |
} | |
void close() {} | |
} | |
} | |
// Example usage | |
task transformHtml(type: Copy) { | |
from "src/main/html" | |
into "$buildDir/transformedHtml" | |
eachFile { | |
if (it.name.endsWith(".html")) { | |
it.filter JSoupFilterReader, withDocument: { | |
outputSettings(). | |
indentAmount(2). | |
prettyPrint(true). | |
charset("UTF-8") | |
head().getElementsByTag("meta").findAll { it.attr("name") == "generator" }*.remove() | |
head().append project.file("src/html/tracking.html").text | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment