昨日のエントリーの続き。
昨日のエントリーでは、自作プラグインのテストが書けないという残念なというか、致命的な欠点があったので、強引に自作プラグインを読み込ませてみる方法をとりました。
String loadScript() { def pluginClassUrl = HelloTestKit.class.protectionDomain.codeSource.location def path = Paths.get(pluginClassUrl.toURI()) if (pluginClassUrl.protocol == 'file' && "${pluginClassUrl}".endsWith('.jar')) { return """buildscript { dependencies { classpath file('${path}') } } """ } else { def granpa = path.parent.parent def runOnIdea = granpa.endsWith('out') def resPath = runOnIdea ? path : granpa.resolve('resources/main') def urls = ([path, resPath] as Set).collect { it.toUri().toURL() }.collect { "new URL('${it}')" }.join(', ') return """[$urls].each { project.class.classLoader.addURL(it) } assert project.class.classLoader.getResource('META-INF/gradle-plugins/hello.properties') != null """ } }
HelloTestKit
というクラスが自作プラグインのクラスで、そこからjarの名前あるいはディレクトリーのURLを取り出して、それをビルドスクリプトのクラスローダーに読み込ませるという至極単純な方法です。
このときに、
assert project.class.classLoader.getResource('META-INF/gradle-plugins/hello.properties') != null
と、META-INF/gradle-plugins/hello.properties
が読み込めるかどうかをassert
しておくことで、プラグインIDが解決できることを保証しておきます(読み込めてない場合は、この部分でエラーが発生する)。
ちなみに、これ、IntelliJ IDEAでテスト走らせるとコケます(´・ω・`)し、エクリなんとかとかネットビーなんとかでは走りません。
昨日作ったレポジトリーに反映しておいたので、参考にどうぞ。